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,250 | use the name of the header when throwing exception for invalid chars | Fixes #65136 | pedrobsaila | 2022-03-05T20:18:11Z | 2022-03-08T16:15:18Z | 8fe2d2b0bbb7bec841c97372528531c071b29c16 | fa5dcda23c681031b5d2bd68482702baef80b836 | use the name of the header when throwing exception for invalid chars. Fixes #65136 | ./src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.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;
using System.Threading;
namespace System.Diagnostics.PerformanceData
{
/// <summary>
/// CounterSet is equivalent to "Counter Object" in native performance counter terminology,
/// or "Counter Category" in previous framework releases. It defines a abstract grouping of
/// counters, where each counter defines measurable matrix. In the new performance counter
/// infrastructure, CounterSet is defined by GUID called CounterSetGuid, and is hosted inside
/// provider application, which is also defined by another GUID called ProviderGuid.
/// </summary>
public class CounterSet : IDisposable
{
internal PerfProvider _provider;
internal Guid _providerGuid;
internal Guid _counterSet;
internal CounterSetInstanceType _instType;
private readonly object _lockObject;
private bool _instanceCreated;
internal Dictionary<string, int> _stringToId;
internal Dictionary<int, CounterType> _idToCounter;
/// <summary>
/// CounterSet constructor.
/// </summary>
/// <param name="providerGuid">ProviderGuid identifies the provider application. A provider identified by ProviderGuid could publish several CounterSets defined by different CounterSetGuids</param>
/// <param name="counterSetGuid">CounterSetGuid identifies the specific CounterSet. CounterSetGuid should be unique.</param>
/// <param name="instanceType">One of defined CounterSetInstanceType values</param>
public CounterSet(Guid providerGuid, Guid counterSetGuid, CounterSetInstanceType instanceType)
{
if (!PerfProviderCollection.ValidateCounterSetInstanceType(instanceType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterSetInstanceType, instanceType), nameof(instanceType));
}
_providerGuid = providerGuid;
_counterSet = counterSetGuid;
_instType = instanceType;
PerfProviderCollection.RegisterCounterSet(_counterSet);
_provider = PerfProviderCollection.QueryProvider(_providerGuid);
_lockObject = new object();
_stringToId = new Dictionary<string, int>();
_idToCounter = new Dictionary<int, CounterType>();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~CounterSet()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
lock (this)
{
PerfProviderCollection.UnregisterCounterSet(_counterSet);
if (_instanceCreated && _provider != null)
{
lock (_lockObject)
{
if (_provider != null)
{
Interlocked.Decrement(ref _provider._counterSet);
if (_provider._counterSet <= 0)
{
PerfProviderCollection.RemoveProvider(_providerGuid);
}
_provider = null;
}
}
}
}
}
/// <summary>
/// Add non-displayable new counter to CounterSet; that is, perfmon would not display the counter.
/// </summary>
/// <param name="counterId">CounterId uniquely identifies the counter within CounterSet</param>
/// <param name="counterType">One of defined CounterType values</param>
public void AddCounter(int counterId, CounterType counterType)
{
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (!PerfProviderCollection.ValidateCounterType(counterType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterType, counterType), nameof(counterType));
}
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
lock (_lockObject)
{
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
if (_idToCounter.ContainsKey(counterId))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterAlreadyExists, counterId, _counterSet), nameof(counterId));
}
_idToCounter.Add(counterId, counterType);
}
}
/// <summary>
/// Add named new counter to CounterSet.
/// </summary>
/// <param name="counterId">CounterId uniquely identifies the counter within CounterSet</param>
/// <param name="counterType">One of defined CounterType values</param>
/// <param name="counterName">This is friendly name to help provider developers as indexer. and it might not match what is displayed in counter consumption applications lie perfmon.</param>
public void AddCounter(int counterId, CounterType counterType, string counterName!!)
{
if (counterName.Length == 0)
{
throw new ArgumentException(SR.Perflib_Argument_EmptyCounterName, nameof(counterName));
}
if (!PerfProviderCollection.ValidateCounterType(counterType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterType, counterType), nameof(counterType));
}
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
lock (_lockObject)
{
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
if (_stringToId.ContainsKey(counterName))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterNameAlreadyExists, counterName, _counterSet), nameof(counterName));
}
if (_idToCounter.ContainsKey(counterId))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterAlreadyExists, counterId, _counterSet), nameof(counterId));
}
_stringToId.Add(counterName, counterId);
_idToCounter.Add(counterId, counterType);
}
}
/// <summary>
/// Create instances of the CounterSet. Created CounterSetInstance identifies active identity and tracks raw counter data for that identity.
/// </summary>
/// <param name="instanceName">Friendly name identifies the instance. InstanceName would be shown in counter consumption applications like perfmon.</param>
/// <returns>CounterSetInstance object</returns>
public CounterSetInstance CreateCounterSetInstance(string instanceName!!)
{
if (instanceName.Length == 0)
{
throw new ArgumentException(SR.Perflib_Argument_EmptyInstanceName, nameof(instanceName));
}
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (!_instanceCreated)
{
lock (_lockObject)
{
if (!_instanceCreated)
{
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_provider._hProvider.IsInvalid)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_idToCounter.Count == 0)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_CounterSetContainsNoCounter, _counterSet));
}
uint Status = (uint)Interop.Errors.ERROR_SUCCESS;
unsafe
{
uint CounterSetInfoSize = (uint)sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct)
+ (uint)_idToCounter.Count * (uint)sizeof(Interop.PerfCounter.PerfCounterInfoStruct);
uint CounterSetInfoUsed = 0;
byte* CounterSetBuffer = stackalloc byte[(int)CounterSetInfoSize];
Debug.Assert(sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct) == 40);
Debug.Assert(sizeof(Interop.PerfCounter.PerfCounterInfoStruct) == 32);
Interop.PerfCounter.PerfCounterSetInfoStruct* CounterSetInfo;
Interop.PerfCounter.PerfCounterInfoStruct* CounterInfo;
uint CurrentCounter = 0;
uint CurrentOffset = 0;
CounterSetInfo = (Interop.PerfCounter.PerfCounterSetInfoStruct*)CounterSetBuffer;
CounterSetInfo->CounterSetGuid = _counterSet;
CounterSetInfo->ProviderGuid = _providerGuid;
CounterSetInfo->NumCounters = (uint)_idToCounter.Count;
CounterSetInfo->InstanceType = (uint)_instType;
foreach (KeyValuePair<int, CounterType> CounterDef in _idToCounter)
{
CounterSetInfoUsed = (uint)sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct)
+ (uint)CurrentCounter * (uint)sizeof(Interop.PerfCounter.PerfCounterInfoStruct);
if (CounterSetInfoUsed < CounterSetInfoSize)
{
CounterInfo = (Interop.PerfCounter.PerfCounterInfoStruct*)(CounterSetBuffer + CounterSetInfoUsed);
CounterInfo->CounterId = (uint)CounterDef.Key;
CounterInfo->CounterType = (uint)CounterDef.Value;
CounterInfo->Attrib = 0x0000000000000001; // PERF_ATTRIB_BY_REFERENCE
CounterInfo->Size = (uint)sizeof(void*); // always use pointer size
CounterInfo->DetailLevel = 100; // PERF_DETAIL_NOVICE
CounterInfo->Scale = 0; // Default scale
CounterInfo->Offset = CurrentOffset;
CurrentOffset += CounterInfo->Size;
}
CurrentCounter++;
}
Status = Interop.PerfCounter.PerfSetCounterSetInfo(_provider._hProvider, CounterSetInfo, CounterSetInfoSize);
// ERROR_INVALID_PARAMETER, ERROR_ALREADY_EXISTS, ERROR_NOT_ENOUGH_MEMORY, ERROR_OUTOFMEMORY
if (Status != (uint)Interop.Errors.ERROR_SUCCESS)
{
throw Status switch
{
(uint)Interop.Errors.ERROR_ALREADY_EXISTS => new InvalidOperationException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet)),
_ => new Win32Exception((int)Status),
};
}
Interlocked.Increment(ref _provider._counterSet);
}
_instanceCreated = true;
}
}
}
CounterSetInstance thisInst = new CounterSetInstance(this, instanceName);
return thisInst;
}
}
}
| // 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;
using System.Threading;
namespace System.Diagnostics.PerformanceData
{
/// <summary>
/// CounterSet is equivalent to "Counter Object" in native performance counter terminology,
/// or "Counter Category" in previous framework releases. It defines a abstract grouping of
/// counters, where each counter defines measurable matrix. In the new performance counter
/// infrastructure, CounterSet is defined by GUID called CounterSetGuid, and is hosted inside
/// provider application, which is also defined by another GUID called ProviderGuid.
/// </summary>
public class CounterSet : IDisposable
{
internal PerfProvider _provider;
internal Guid _providerGuid;
internal Guid _counterSet;
internal CounterSetInstanceType _instType;
private readonly object _lockObject;
private bool _instanceCreated;
internal Dictionary<string, int> _stringToId;
internal Dictionary<int, CounterType> _idToCounter;
/// <summary>
/// CounterSet constructor.
/// </summary>
/// <param name="providerGuid">ProviderGuid identifies the provider application. A provider identified by ProviderGuid could publish several CounterSets defined by different CounterSetGuids</param>
/// <param name="counterSetGuid">CounterSetGuid identifies the specific CounterSet. CounterSetGuid should be unique.</param>
/// <param name="instanceType">One of defined CounterSetInstanceType values</param>
public CounterSet(Guid providerGuid, Guid counterSetGuid, CounterSetInstanceType instanceType)
{
if (!PerfProviderCollection.ValidateCounterSetInstanceType(instanceType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterSetInstanceType, instanceType), nameof(instanceType));
}
_providerGuid = providerGuid;
_counterSet = counterSetGuid;
_instType = instanceType;
PerfProviderCollection.RegisterCounterSet(_counterSet);
_provider = PerfProviderCollection.QueryProvider(_providerGuid);
_lockObject = new object();
_stringToId = new Dictionary<string, int>();
_idToCounter = new Dictionary<int, CounterType>();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~CounterSet()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
lock (this)
{
PerfProviderCollection.UnregisterCounterSet(_counterSet);
if (_instanceCreated && _provider != null)
{
lock (_lockObject)
{
if (_provider != null)
{
Interlocked.Decrement(ref _provider._counterSet);
if (_provider._counterSet <= 0)
{
PerfProviderCollection.RemoveProvider(_providerGuid);
}
_provider = null;
}
}
}
}
}
/// <summary>
/// Add non-displayable new counter to CounterSet; that is, perfmon would not display the counter.
/// </summary>
/// <param name="counterId">CounterId uniquely identifies the counter within CounterSet</param>
/// <param name="counterType">One of defined CounterType values</param>
public void AddCounter(int counterId, CounterType counterType)
{
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (!PerfProviderCollection.ValidateCounterType(counterType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterType, counterType), nameof(counterType));
}
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
lock (_lockObject)
{
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
if (_idToCounter.ContainsKey(counterId))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterAlreadyExists, counterId, _counterSet), nameof(counterId));
}
_idToCounter.Add(counterId, counterType);
}
}
/// <summary>
/// Add named new counter to CounterSet.
/// </summary>
/// <param name="counterId">CounterId uniquely identifies the counter within CounterSet</param>
/// <param name="counterType">One of defined CounterType values</param>
/// <param name="counterName">This is friendly name to help provider developers as indexer. and it might not match what is displayed in counter consumption applications lie perfmon.</param>
public void AddCounter(int counterId, CounterType counterType, string counterName!!)
{
if (counterName.Length == 0)
{
throw new ArgumentException(SR.Perflib_Argument_EmptyCounterName, nameof(counterName));
}
if (!PerfProviderCollection.ValidateCounterType(counterType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterType, counterType), nameof(counterType));
}
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
lock (_lockObject)
{
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
if (_stringToId.ContainsKey(counterName))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterNameAlreadyExists, counterName, _counterSet), nameof(counterName));
}
if (_idToCounter.ContainsKey(counterId))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterAlreadyExists, counterId, _counterSet), nameof(counterId));
}
_stringToId.Add(counterName, counterId);
_idToCounter.Add(counterId, counterType);
}
}
/// <summary>
/// Create instances of the CounterSet. Created CounterSetInstance identifies active identity and tracks raw counter data for that identity.
/// </summary>
/// <param name="instanceName">Friendly name identifies the instance. InstanceName would be shown in counter consumption applications like perfmon.</param>
/// <returns>CounterSetInstance object</returns>
public CounterSetInstance CreateCounterSetInstance(string instanceName!!)
{
if (instanceName.Length == 0)
{
throw new ArgumentException(SR.Perflib_Argument_EmptyInstanceName, nameof(instanceName));
}
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (!_instanceCreated)
{
lock (_lockObject)
{
if (!_instanceCreated)
{
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_provider._hProvider.IsInvalid)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_idToCounter.Count == 0)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_CounterSetContainsNoCounter, _counterSet));
}
uint Status = (uint)Interop.Errors.ERROR_SUCCESS;
unsafe
{
uint CounterSetInfoSize = (uint)sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct)
+ (uint)_idToCounter.Count * (uint)sizeof(Interop.PerfCounter.PerfCounterInfoStruct);
uint CounterSetInfoUsed = 0;
byte* CounterSetBuffer = stackalloc byte[(int)CounterSetInfoSize];
Debug.Assert(sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct) == 40);
Debug.Assert(sizeof(Interop.PerfCounter.PerfCounterInfoStruct) == 32);
Interop.PerfCounter.PerfCounterSetInfoStruct* CounterSetInfo;
Interop.PerfCounter.PerfCounterInfoStruct* CounterInfo;
uint CurrentCounter = 0;
uint CurrentOffset = 0;
CounterSetInfo = (Interop.PerfCounter.PerfCounterSetInfoStruct*)CounterSetBuffer;
CounterSetInfo->CounterSetGuid = _counterSet;
CounterSetInfo->ProviderGuid = _providerGuid;
CounterSetInfo->NumCounters = (uint)_idToCounter.Count;
CounterSetInfo->InstanceType = (uint)_instType;
foreach (KeyValuePair<int, CounterType> CounterDef in _idToCounter)
{
CounterSetInfoUsed = (uint)sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct)
+ (uint)CurrentCounter * (uint)sizeof(Interop.PerfCounter.PerfCounterInfoStruct);
if (CounterSetInfoUsed < CounterSetInfoSize)
{
CounterInfo = (Interop.PerfCounter.PerfCounterInfoStruct*)(CounterSetBuffer + CounterSetInfoUsed);
CounterInfo->CounterId = (uint)CounterDef.Key;
CounterInfo->CounterType = (uint)CounterDef.Value;
CounterInfo->Attrib = 0x0000000000000001; // PERF_ATTRIB_BY_REFERENCE
CounterInfo->Size = (uint)sizeof(void*); // always use pointer size
CounterInfo->DetailLevel = 100; // PERF_DETAIL_NOVICE
CounterInfo->Scale = 0; // Default scale
CounterInfo->Offset = CurrentOffset;
CurrentOffset += CounterInfo->Size;
}
CurrentCounter++;
}
Status = Interop.PerfCounter.PerfSetCounterSetInfo(_provider._hProvider, CounterSetInfo, CounterSetInfoSize);
// ERROR_INVALID_PARAMETER, ERROR_ALREADY_EXISTS, ERROR_NOT_ENOUGH_MEMORY, ERROR_OUTOFMEMORY
if (Status != (uint)Interop.Errors.ERROR_SUCCESS)
{
throw Status switch
{
(uint)Interop.Errors.ERROR_ALREADY_EXISTS => new InvalidOperationException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet)),
_ => new Win32Exception((int)Status),
};
}
Interlocked.Increment(ref _provider._counterSet);
}
_instanceCreated = true;
}
}
}
CounterSetInstance thisInst = new CounterSetInstance(this, instanceName);
return thisInst;
}
}
}
| -1 |
dotnet/runtime | 66,250 | use the name of the header when throwing exception for invalid chars | Fixes #65136 | pedrobsaila | 2022-03-05T20:18:11Z | 2022-03-08T16:15:18Z | 8fe2d2b0bbb7bec841c97372528531c071b29c16 | fa5dcda23c681031b5d2bd68482702baef80b836 | use the name of the header when throwing exception for invalid chars. Fixes #65136 | ./src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
[GeneratedDllImport(Interop.Libraries.SystemNative, EntryPoint = "SystemNative_GetSystemTimeAsTicks")]
[SuppressGCTransition]
internal static partial long GetSystemTimeAsTicks();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
[GeneratedDllImport(Interop.Libraries.SystemNative, EntryPoint = "SystemNative_GetSystemTimeAsTicks")]
[SuppressGCTransition]
internal static partial long GetSystemTimeAsTicks();
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/Resources/Strings.resx | <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ArrayDepthTooLarge" xml:space="preserve">
<value>The maximum configured depth of {0} has been exceeded. Cannot read next JSON array.</value>
</data>
<data name="CallFlushToAvoidDataLoss" xml:space="preserve">
<value>The JSON writer needs to be flushed before getting the current state. There are {0} bytes that have not been committed to the output.</value>
</data>
<data name="CannotReadIncompleteUTF16" xml:space="preserve">
<value>Cannot read incomplete UTF-16 JSON text as string with missing low surrogate.</value>
</data>
<data name="CannotReadInvalidUTF16" xml:space="preserve">
<value>Cannot read invalid UTF-16 JSON text as string. Invalid surrogate value: '{0}'.</value>
</data>
<data name="CannotStartObjectArrayAfterPrimitiveOrClose" xml:space="preserve">
<value>Cannot write the start of an object/array after a single JSON value or outside of an existing closed object/array. Current token type is '{0}'.</value>
</data>
<data name="CannotStartObjectArrayWithoutProperty" xml:space="preserve">
<value>Cannot write the start of an object or array without a property name. Current token type is '{0}'.</value>
</data>
<data name="CannotTranscodeInvalidUtf8" xml:space="preserve">
<value>Cannot transcode invalid UTF-8 JSON text to UTF-16 string.</value>
</data>
<data name="CannotDecodeInvalidBase64" xml:space="preserve">
<value>Cannot decode JSON text that is not encoded as valid Base64 to bytes.</value>
</data>
<data name="CannotTranscodeInvalidUtf16" xml:space="preserve">
<value>Cannot transcode invalid UTF-16 string to UTF-8 JSON text.</value>
</data>
<data name="CannotEncodeInvalidUTF16" xml:space="preserve">
<value>Cannot encode invalid UTF-16 text as JSON. Invalid surrogate value: '{0}'.</value>
</data>
<data name="CannotEncodeInvalidUTF8" xml:space="preserve">
<value>Cannot encode invalid UTF-8 text as JSON. Invalid input: '{0}'.</value>
</data>
<data name="CannotWritePropertyWithinArray" xml:space="preserve">
<value>Cannot write a JSON property within an array or as the first JSON token. Current token type is '{0}'.</value>
</data>
<data name="CannotWritePropertyAfterProperty" xml:space="preserve">
<value>Cannot write a JSON property name following another property name. A JSON value is missing.</value>
</data>
<data name="CannotWriteValueAfterPrimitiveOrClose" xml:space="preserve">
<value>Cannot write a JSON value after a single JSON value or outside of an existing closed object/array. Current token type is '{0}'.</value>
</data>
<data name="CannotWriteValueWithinObject" xml:space="preserve">
<value>Cannot write a JSON value within an object without a property name. Current token type is '{0}'.</value>
</data>
<data name="DepthTooLarge" xml:space="preserve">
<value>CurrentDepth ({0}) is equal to or larger than the maximum allowed depth of {1}. Cannot write the next JSON object or array.</value>
</data>
<data name="EmptyJsonIsInvalid" xml:space="preserve">
<value>Writing an empty JSON payload (excluding comments) is invalid.</value>
</data>
<data name="EndOfCommentNotFound" xml:space="preserve">
<value>Expected end of comment, but instead reached end of data.</value>
</data>
<data name="EndOfStringNotFound" xml:space="preserve">
<value>Expected end of string, but instead reached end of data.</value>
</data>
<data name="ExpectedEndAfterSingleJson" xml:space="preserve">
<value>'{0}' is invalid after a single JSON value. Expected end of data.</value>
</data>
<data name="ExpectedEndOfDigitNotFound" xml:space="preserve">
<value>'{0}' is an invalid end of a number. Expected a delimiter.</value>
</data>
<data name="ExpectedFalse" xml:space="preserve">
<value>'{0}' is an invalid JSON literal. Expected the literal 'false'.</value>
</data>
<data name="ExpectedJsonTokens" xml:space="preserve">
<value>The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true.</value>
</data>
<data name="ExpectedOneCompleteToken" xml:space="preserve">
<value>The input does not contain any complete JSON tokens. Expected the input to have at least one valid, complete, JSON token.</value>
</data>
<data name="ExpectedNextDigitEValueNotFound" xml:space="preserve">
<value>'{0}' is an invalid end of a number. Expected 'E' or 'e'.</value>
</data>
<data name="ExpectedNull" xml:space="preserve">
<value>'{0}' is an invalid JSON literal. Expected the literal 'null'.</value>
</data>
<data name="ExpectedSeparatorAfterPropertyNameNotFound" xml:space="preserve">
<value>'{0}' is invalid after a property name. Expected a ':'.</value>
</data>
<data name="ExpectedStartOfPropertyNotFound" xml:space="preserve">
<value>'{0}' is an invalid start of a property name. Expected a '"'.</value>
</data>
<data name="ExpectedStartOfPropertyOrValueNotFound" xml:space="preserve">
<value>Expected start of a property name or value, but instead reached end of data.</value>
</data>
<data name="ExpectedStartOfValueNotFound" xml:space="preserve">
<value>'{0}' is an invalid start of a value.</value>
</data>
<data name="ExpectedTrue" xml:space="preserve">
<value>'{0}' is an invalid JSON literal. Expected the literal 'true'.</value>
</data>
<data name="ExpectedValueAfterPropertyNameNotFound" xml:space="preserve">
<value>Expected a value, but instead reached end of data.</value>
</data>
<data name="FailedToGetLargerSpan" xml:space="preserve">
<value>The 'IBufferWriter' could not provide an output buffer that is large enough to continue writing.</value>
</data>
<data name="FoundInvalidCharacter" xml:space="preserve">
<value>'{0}' is invalid after a value. Expected either ',', '}}', or ']'.</value>
</data>
<data name="InvalidCast" xml:space="preserve">
<value>Cannot get the value of a token type '{0}' as a {1}.</value>
</data>
<data name="InvalidCharacterAfterEscapeWithinString" xml:space="preserve">
<value>'{0}' is an invalid escapable character within a JSON string. The string should be correctly escaped.</value>
</data>
<data name="InvalidCharacterWithinString" xml:space="preserve">
<value>'{0}' is invalid within a JSON string. The string should be correctly escaped.</value>
</data>
<data name="InvalidEndOfJsonNonPrimitive" xml:space="preserve">
<value>'{0}' is an invalid token type for the end of the JSON payload. Expected either 'EndArray' or 'EndObject'.</value>
</data>
<data name="InvalidHexCharacterWithinString" xml:space="preserve">
<value>'{0}' is not a hex digit following '\u' within a JSON string. The string should be correctly escaped.</value>
</data>
<data name="JsonDocumentDoesNotSupportComments" xml:space="preserve">
<value>Comments cannot be stored in a JsonDocument, only the Skip and Disallow comment handling modes are supported.</value>
</data>
<data name="JsonElementHasWrongType" xml:space="preserve">
<value>The requested operation requires an element of type '{0}', but the target element has type '{1}'.</value>
</data>
<data name="MaxDepthMustBePositive" xml:space="preserve">
<value>Max depth must be positive.</value>
</data>
<data name="CommentHandlingMustBeValid" xml:space="preserve">
<value>The JsonCommentHandling enum must be set to one of the supported values.</value>
</data>
<data name="MismatchedObjectArray" xml:space="preserve">
<value>'{0}' is invalid without a matching open.</value>
</data>
<data name="CannotWriteEndAfterProperty" xml:space="preserve">
<value>'{0}' is invalid following a property name.</value>
</data>
<data name="ObjectDepthTooLarge" xml:space="preserve">
<value>The maximum configured depth of {0} has been exceeded. Cannot read next JSON object.</value>
</data>
<data name="PropertyNameTooLarge" xml:space="preserve">
<value>The JSON property name of length {0} is too large and not supported.</value>
</data>
<data name="FormatDecimal" xml:space="preserve">
<value>The JSON value is either too large or too small for a Decimal.</value>
</data>
<data name="FormatDouble" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a Double.</value>
</data>
<data name="FormatInt32" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for an Int32.</value>
</data>
<data name="FormatInt64" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for an Int64.</value>
</data>
<data name="FormatSingle" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a Single.</value>
</data>
<data name="FormatUInt32" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a UInt32.</value>
</data>
<data name="FormatUInt64" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a UInt64.</value>
</data>
<data name="RequiredDigitNotFoundAfterDecimal" xml:space="preserve">
<value>'{0}' is invalid within a number, immediately after a decimal point ('.'). Expected a digit ('0'-'9').</value>
</data>
<data name="RequiredDigitNotFoundAfterSign" xml:space="preserve">
<value>'{0}' is invalid within a number, immediately after a sign character ('+' or '-'). Expected a digit ('0'-'9').</value>
</data>
<data name="RequiredDigitNotFoundEndOfData" xml:space="preserve">
<value>Expected a digit ('0'-'9'), but instead reached end of data.</value>
</data>
<data name="SpecialNumberValuesNotSupported" xml:space="preserve">
<value>.NET number values such as positive and negative infinity cannot be written as valid JSON. To make it work when using 'JsonSerializer', consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://docs.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).</value>
</data>
<data name="ValueTooLarge" xml:space="preserve">
<value>The JSON value of length {0} is too large and not supported.</value>
</data>
<data name="ZeroDepthAtEnd" xml:space="preserve">
<value>Expected depth to be zero at the end of the JSON payload. There is an open JSON object or array that should be closed.</value>
</data>
<data name="DeserializeUnableToConvertValue" xml:space="preserve">
<value>The JSON value could not be converted to {0}.</value>
</data>
<data name="DeserializeWrongType" xml:space="preserve">
<value>The specified type {0} must derive from the specific value's type {1}.</value>
</data>
<data name="SerializationInvalidBufferSize" xml:space="preserve">
<value>The value must be greater than zero.</value>
</data>
<data name="BufferWriterAdvancedTooFar" xml:space="preserve">
<value>Cannot advance past the end of the buffer, which has a size of {0}.</value>
</data>
<data name="InvalidComparison" xml:space="preserve">
<value>Cannot compare the value of a token type '{0}' to text.</value>
</data>
<data name="FormatDateTime" xml:space="preserve">
<value>The JSON value is not in a supported DateTime format.</value>
</data>
<data name="FormatDateTimeOffset" xml:space="preserve">
<value>The JSON value is not in a supported DateTimeOffset format.</value>
</data>
<data name="FormatTimeSpan" xml:space="preserve">
<value>The JSON value is not in a supported TimeSpan format.</value>
</data>
<data name="FormatGuid" xml:space="preserve">
<value>The JSON value is not in a supported Guid format.</value>
</data>
<data name="FormatVersion" xml:space="preserve">
<value>The JSON value is not in a supported Version format.</value>
</data>
<data name="ExpectedStartOfPropertyOrValueAfterComment" xml:space="preserve">
<value>'{0}' is an invalid start of a property name or value, after a comment.</value>
</data>
<data name="TrailingCommaNotAllowedBeforeArrayEnd" xml:space="preserve">
<value>The JSON array contains a trailing comma at the end which is not supported in this mode. Change the reader options.</value>
</data>
<data name="TrailingCommaNotAllowedBeforeObjectEnd" xml:space="preserve">
<value>The JSON object contains a trailing comma at the end which is not supported in this mode. Change the reader options.</value>
</data>
<data name="SerializerOptionsImmutable" xml:space="preserve">
<value>Serializer options cannot be changed once serialization or deserialization has occurred.</value>
</data>
<data name="StreamNotWritable" xml:space="preserve">
<value>Stream is not writable.</value>
</data>
<data name="CannotWriteCommentWithEmbeddedDelimiter" xml:space="preserve">
<value>Cannot write a comment value which contains the end of comment delimiter.</value>
</data>
<data name="SerializerPropertyNameConflict" xml:space="preserve">
<value>The JSON property name for '{0}.{1}' collides with another property.</value>
</data>
<data name="SerializerPropertyNameNull" xml:space="preserve">
<value>The JSON property name for '{0}.{1}' cannot be null.</value>
</data>
<data name="SerializationDataExtensionPropertyInvalid" xml:space="preserve">
<value>The data extension property '{0}.{1}' is invalid. It must implement 'IDictionary<string, JsonElement>' or 'IDictionary<string, object>', or be 'JsonObject'.</value>
</data>
<data name="SerializationDuplicateTypeAttribute" xml:space="preserve">
<value>The type '{0}' cannot have more than one member that has the attribute '{1}'.</value>
</data>
<data name="SerializationNotSupportedType" xml:space="preserve">
<value>The type '{0}' is not supported.</value>
</data>
<data name="TypeRequiresAsyncSerialization" xml:space="preserve">
<value>The type '{0}' can only be serialized using async serialization methods.</value>
</data>
<data name="InvalidCharacterAtStartOfComment" xml:space="preserve">
<value>'{0}' is invalid after '/' at the beginning of the comment. Expected either '/' or '*'.</value>
</data>
<data name="UnexpectedEndOfDataWhileReadingComment" xml:space="preserve">
<value>Unexpected end of data while reading a comment.</value>
</data>
<data name="CannotSkip" xml:space="preserve">
<value>Cannot skip tokens on partial JSON. Either get the whole payload and create a Utf8JsonReader instance where isFinalBlock is true or call TrySkip.</value>
</data>
<data name="NotEnoughData" xml:space="preserve">
<value>There is not enough data to read through the entire JSON array or object.</value>
</data>
<data name="UnexpectedEndOfLineSeparator" xml:space="preserve">
<value>Found invalid line or paragraph separator character while reading a comment.</value>
</data>
<data name="JsonSerializerDoesNotSupportComments" xml:space="preserve">
<value>Comments cannot be stored when deserializing objects, only the Skip and Disallow comment handling modes are supported.</value>
</data>
<data name="DeserializeNoConstructor" xml:space="preserve">
<value>Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with '{0}' is not supported. Type '{1}'.</value>
</data>
<data name="DeserializePolymorphicInterface" xml:space="preserve">
<value>Deserialization of interface types is not supported. Type '{0}'.</value>
</data>
<data name="SerializationConverterOnAttributeNotCompatible" xml:space="preserve">
<value>The converter specified on '{0}' is not compatible with the type '{1}'.</value>
</data>
<data name="SerializationConverterOnAttributeInvalid" xml:space="preserve">
<value>The converter specified on '{0}' does not derive from JsonConverter or have a public parameterless constructor.</value>
</data>
<data name="SerializationConverterRead" xml:space="preserve">
<value>The converter '{0}' read too much or not enough.</value>
</data>
<data name="SerializationConverterNotCompatible" xml:space="preserve">
<value>The converter '{0}' is not compatible with the type '{1}'.</value>
</data>
<data name="SerializationConverterWrite" xml:space="preserve">
<value>The converter '{0}' wrote too much or not enough.</value>
</data>
<data name="NamingPolicyReturnNull" xml:space="preserve">
<value>The naming policy '{0}' cannot return null.</value>
</data>
<data name="SerializationDuplicateAttribute" xml:space="preserve">
<value>The attribute '{0}' cannot exist more than once on '{1}'.</value>
</data>
<data name="SerializeUnableToSerialize" xml:space="preserve">
<value>The object or value could not be serialized.</value>
</data>
<data name="FormatByte" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for an unsigned byte.</value>
</data>
<data name="FormatInt16" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for an Int16.</value>
</data>
<data name="FormatSByte" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a signed byte.</value>
</data>
<data name="FormatUInt16" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a UInt16.</value>
</data>
<data name="SerializerCycleDetected" xml:space="preserve">
<value>A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of {0}. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.</value>
</data>
<data name="InvalidLeadingZeroInNumber" xml:space="preserve">
<value>Invalid leading zero before '{0}'.</value>
</data>
<data name="MetadataCannotParsePreservedObjectToImmutable" xml:space="preserve">
<value>Cannot parse a JSON object containing metadata properties like '$id' into an array or immutable collection type. Type '{0}'.</value>
</data>
<data name="MetadataDuplicateIdFound" xml:space="preserve">
<value>The value of the '$id' metadata property '{0}' conflicts with an existing identifier.</value>
</data>
<data name="MetadataIdIsNotFirstProperty" xml:space="preserve">
<value>The metadata property '$id' must be the first property in the JSON object.</value>
</data>
<data name="MetadataInvalidReferenceToValueType" xml:space="preserve">
<value>Invalid reference to value type '{0}'.</value>
</data>
<data name="MetadataInvalidTokenAfterValues" xml:space="preserve">
<value>The '$values' metadata property must be a JSON array. Current token type is '{0}'.</value>
</data>
<data name="MetadataPreservedArrayFailed" xml:space="preserve">
<value>Deserialization failed for one of these reasons:
1. {0}
2. {1}</value>
</data>
<data name="MetadataPreservedArrayInvalidProperty" xml:space="preserve">
<value>Invalid property '{0}' found within a JSON object that must only contain metadata properties and the nested JSON array to be preserved.</value>
</data>
<data name="MetadataPreservedArrayPropertyNotFound" xml:space="preserve">
<value>One or more metadata properties, such as '$id' and '$values', were not found within a JSON object that must only contain metadata properties and the nested JSON array to be preserved.</value>
</data>
<data name="MetadataReferenceCannotContainOtherProperties" xml:space="preserve">
<value>A JSON object that contains a '$ref' metadata property must not contain any other properties.</value>
</data>
<data name="MetadataReferenceNotFound" xml:space="preserve">
<value>Reference '{0}' not found.</value>
</data>
<data name="MetadataValueWasNotString" xml:space="preserve">
<value>The '$id' and '$ref' metadata properties must be JSON strings. Current token type is '{0}'.</value>
</data>
<data name="MetadataInvalidPropertyWithLeadingDollarSign" xml:space="preserve">
<value>Properties that start with '$' are not allowed on preserve mode, either escape the character or turn off preserve references by setting ReferenceHandler to null.</value>
</data>
<data name="MultipleMembersBindWithConstructorParameter" xml:space="preserve">
<value>Members '{0}' and '{1}' on type '{2}' cannot both bind with parameter '{3}' in the deserialization constructor.</value>
</data>
<data name="ConstructorParamIncompleteBinding" xml:space="preserve">
<value>Each parameter in the deserialization constructor on type '{0}' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.</value>
</data>
<data name="ConstructorMaxOf64Parameters" xml:space="preserve">
<value>The deserialization constructor on type '{0}' may not have more than 64 parameters for deserialization.</value>
</data>
<data name="ObjectWithParameterizedCtorRefMetadataNotHonored" xml:space="preserve">
<value>Reference metadata is not honored when deserializing types using parameterized constructors. See type '{0}'.</value>
</data>
<data name="SerializerConverterFactoryReturnsNull" xml:space="preserve">
<value>The converter '{0}' cannot return a null value.</value>
</data>
<data name="SerializationNotSupportedParentType" xml:space="preserve">
<value>The unsupported member type is located on type '{0}'.</value>
</data>
<data name="ExtensionDataCannotBindToCtorParam" xml:space="preserve">
<value>The extension data property '{0}' on type '{1}' cannot bind with a parameter in the deserialization constructor.</value>
</data>
<data name="BufferMaximumSizeExceeded" xml:space="preserve">
<value>Cannot allocate a buffer of size {0}.</value>
</data>
<data name="CannotSerializeInvalidType" xml:space="preserve">
<value>The type '{0}' is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types.</value>
</data>
<data name="SerializeTypeInstanceNotSupported" xml:space="preserve">
<value>Serialization and deserialization of '{0}' instances are not supported.</value>
</data>
<data name="JsonIncludeOnNonPublicInvalid" xml:space="preserve">
<value>The non-public property '{0}' on type '{1}' is annotated with 'JsonIncludeAttribute' which is invalid.</value>
</data>
<data name="CannotSerializeInvalidMember" xml:space="preserve">
<value>The type '{0}' of property '{1}' on type '{2}' is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types.</value>
</data>
<data name="CannotPopulateCollection" xml:space="preserve">
<value>The collection type '{0}' is abstract, an interface, or is read only, and could not be instantiated and populated.</value>
</data>
<data name="DefaultIgnoreConditionAlreadySpecified" xml:space="preserve">
<value>'IgnoreNullValues' and 'DefaultIgnoreCondition' cannot both be set to non-default values.</value>
</data>
<data name="DefaultIgnoreConditionInvalid" xml:space="preserve">
<value>The value cannot be 'JsonIgnoreCondition.Always'.</value>
</data>
<data name="FormatBoolean" xml:space="preserve">
<value>The JSON value is not in a supported Boolean format.</value>
</data>
<data name="DictionaryKeyTypeNotSupported" xml:space="preserve">
<value>The type '{0}' is not a supported dictionary key using converter of type '{1}'.</value>
</data>
<data name="IgnoreConditionOnValueTypeInvalid" xml:space="preserve">
<value>The ignore condition 'JsonIgnoreCondition.WhenWritingNull' is not valid on value-type member '{0}' on type '{1}'. Consider using 'JsonIgnoreCondition.WhenWritingDefault'.</value>
</data>
<data name="NumberHandlingOnPropertyInvalid" xml:space="preserve">
<value>'JsonNumberHandlingAttribute' is only valid on a number or a collection of numbers when applied to a property or field. See member '{0}' on type '{1}'.</value>
</data>
<data name="ConverterCanConvertMultipleTypes" xml:space="preserve">
<value>The converter '{0}' handles type '{1}' but is being asked to convert type '{2}'. Either create a separate converter for type '{2}' or change the converter's 'CanConvert' method to only return 'true' for a single type.</value>
</data>
<data name="MetadataReferenceOfTypeCannotBeAssignedToType" xml:space="preserve">
<value>The object with reference id '{0}' of type '{1}' cannot be assigned to the type '{2}'.</value>
</data>
<data name="DeserializeUnableToAssignValue" xml:space="preserve">
<value>Unable to cast object of type '{0}' to type '{1}'.</value>
</data>
<data name="DeserializeUnableToAssignNull" xml:space="preserve">
<value>Unable to assign 'null' to the property or field of type '{0}'.</value>
</data>
<data name="SerializerConverterFactoryReturnsJsonConverterFactory" xml:space="preserve">
<value>The converter '{0}' cannot return an instance of JsonConverterFactory.</value>
</data>
<data name="NodeElementWrongType" xml:space="preserve">
<value>The element must be of type '{0}'</value>
</data>
<data name="NodeElementCannotBeObjectOrArray" xml:space="preserve">
<value>The element cannot be an object or array.</value>
</data>
<data name="NodeAlreadyHasParent" xml:space="preserve">
<value>The node already has a parent.</value>
</data>
<data name="NodeCycleDetected" xml:space="preserve">
<value>A node cycle was detected.</value>
</data>
<data name="NodeUnableToConvert" xml:space="preserve">
<value>A value of type '{0}' cannot be converted to a '{1}'.</value>
</data>
<data name="NodeUnableToConvertElement" xml:space="preserve">
<value>An element of type '{0}' cannot be converted to a '{1}'.</value>
</data>
<data name="NodeValueNotAllowed" xml:space="preserve">
<value>A JsonNode cannot be used as a value.</value>
</data>
<data name="NodeWrongType" xml:space="preserve">
<value>The node must be of type '{0}'.</value>
</data>
<data name="NodeDuplicateKey" xml:space="preserve">
<value>An item with the same key has already been added. Key: {0}</value>
</data>
<data name="SerializerContextOptionsImmutable" xml:space="preserve">
<value>A 'JsonSerializerOptions' instance associated with a 'JsonSerializerContext' instance cannot be mutated once the context has been instantiated.</value>
</data>
<data name="OptionsAlreadyBoundToContext" xml:space="preserve">
<value>"The specified 'JsonSerializerOptions' instance is already bound with a 'JsonSerializerContext' instance."</value>
</data>
<data name="ConverterForPropertyMustBeValid" xml:space="preserve">
<value>The generic type of the converter for property '{0}.{1}' must match with the specified converter type '{2}'. The converter must not be 'null'.</value>
</data>
<data name="BuiltInConvertersNotRooted" xml:space="preserve">
<value>Built-in type converters have not been initialized. There is no converter available for type '{0}'. To root all built-in converters, use a 'JsonSerializerOptions'-based method of the 'JsonSerializer'.</value>
</data>
<data name="NoMetadataForType" xml:space="preserve">
<value>Metadata for type '{0}' was not provided to the serializer. The serializer method used does not support reflection-based creation of serialization-related type metadata. If using source generation, ensure that all root types passed to the serializer have been indicated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.</value>
</data>
<data name="NodeCollectionIsReadOnly" xml:space="preserve">
<value>Collection is read-only.</value>
</data>
<data name="NodeArrayIndexNegative" xml:space="preserve">
<value>Number was less than 0.</value>
</data>
<data name="NodeArrayTooSmall" xml:space="preserve">
<value>Destination array was not long enough.</value>
</data>
<data name="NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty" xml:space="preserve">
<value>A custom converter for JsonObject is not allowed on an extension property.</value>
</data>
<data name="MetadataInitFuncsNull" xml:space="preserve">
<value>Invalid configuration provided for 'propInitFunc', 'ctorParamInitFunc' and 'serializeFunc'.</value>
</data>
<data name="NoMetadataForTypeProperties" xml:space="preserve">
<value>'JsonSerializerContext' '{0}' did not provide property metadata for type '{1}'.</value>
</data>
<data name="NoDefaultOptionsForContext" xml:space="preserve">
<value>To specify a serialization implementation for type '{0}'', context '{0}' must specify default options.</value>
</data>
<data name="FieldCannotBeVirtual" xml:space="preserve">
<value>A 'field' member cannot be 'virtual'. See arguments for the '{0}' and '{1}' parameters. </value>
</data>
<data name="MissingFSharpCoreMember" xml:space="preserve">
<value>Could not locate required member '{0}' from FSharp.Core. This might happen because your application has enabled member-level trimming.</value>
</data>
<data name="FSharpDiscriminatedUnionsNotSupported" xml:space="preserve">
<value>F# discriminated union serialization is not supported. Consider authoring a custom converter for the type.</value>
</data>
<data name="NoMetadataForTypeCtorParams" xml:space="preserve">
<value>'JsonSerializerContext' '{0}' did not provide constructor parameter metadata for type '{1}'.</value>
</data>
</root>
| <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ArrayDepthTooLarge" xml:space="preserve">
<value>The maximum configured depth of {0} has been exceeded. Cannot read next JSON array.</value>
</data>
<data name="CallFlushToAvoidDataLoss" xml:space="preserve">
<value>The JSON writer needs to be flushed before getting the current state. There are {0} bytes that have not been committed to the output.</value>
</data>
<data name="CannotReadIncompleteUTF16" xml:space="preserve">
<value>Cannot read incomplete UTF-16 JSON text as string with missing low surrogate.</value>
</data>
<data name="CannotReadInvalidUTF16" xml:space="preserve">
<value>Cannot read invalid UTF-16 JSON text as string. Invalid surrogate value: '{0}'.</value>
</data>
<data name="CannotStartObjectArrayAfterPrimitiveOrClose" xml:space="preserve">
<value>Cannot write the start of an object/array after a single JSON value or outside of an existing closed object/array. Current token type is '{0}'.</value>
</data>
<data name="CannotStartObjectArrayWithoutProperty" xml:space="preserve">
<value>Cannot write the start of an object or array without a property name. Current token type is '{0}'.</value>
</data>
<data name="CannotTranscodeInvalidUtf8" xml:space="preserve">
<value>Cannot transcode invalid UTF-8 JSON text to UTF-16 string.</value>
</data>
<data name="CannotDecodeInvalidBase64" xml:space="preserve">
<value>Cannot decode JSON text that is not encoded as valid Base64 to bytes.</value>
</data>
<data name="CannotTranscodeInvalidUtf16" xml:space="preserve">
<value>Cannot transcode invalid UTF-16 string to UTF-8 JSON text.</value>
</data>
<data name="CannotEncodeInvalidUTF16" xml:space="preserve">
<value>Cannot encode invalid UTF-16 text as JSON. Invalid surrogate value: '{0}'.</value>
</data>
<data name="CannotEncodeInvalidUTF8" xml:space="preserve">
<value>Cannot encode invalid UTF-8 text as JSON. Invalid input: '{0}'.</value>
</data>
<data name="CannotWritePropertyWithinArray" xml:space="preserve">
<value>Cannot write a JSON property within an array or as the first JSON token. Current token type is '{0}'.</value>
</data>
<data name="CannotWritePropertyAfterProperty" xml:space="preserve">
<value>Cannot write a JSON property name following another property name. A JSON value is missing.</value>
</data>
<data name="CannotWriteValueAfterPrimitiveOrClose" xml:space="preserve">
<value>Cannot write a JSON value after a single JSON value or outside of an existing closed object/array. Current token type is '{0}'.</value>
</data>
<data name="CannotWriteValueWithinObject" xml:space="preserve">
<value>Cannot write a JSON value within an object without a property name. Current token type is '{0}'.</value>
</data>
<data name="DepthTooLarge" xml:space="preserve">
<value>CurrentDepth ({0}) is equal to or larger than the maximum allowed depth of {1}. Cannot write the next JSON object or array.</value>
</data>
<data name="EmptyJsonIsInvalid" xml:space="preserve">
<value>Writing an empty JSON payload (excluding comments) is invalid.</value>
</data>
<data name="EndOfCommentNotFound" xml:space="preserve">
<value>Expected end of comment, but instead reached end of data.</value>
</data>
<data name="EndOfStringNotFound" xml:space="preserve">
<value>Expected end of string, but instead reached end of data.</value>
</data>
<data name="ExpectedEndAfterSingleJson" xml:space="preserve">
<value>'{0}' is invalid after a single JSON value. Expected end of data.</value>
</data>
<data name="ExpectedEndOfDigitNotFound" xml:space="preserve">
<value>'{0}' is an invalid end of a number. Expected a delimiter.</value>
</data>
<data name="ExpectedFalse" xml:space="preserve">
<value>'{0}' is an invalid JSON literal. Expected the literal 'false'.</value>
</data>
<data name="ExpectedJsonTokens" xml:space="preserve">
<value>The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true.</value>
</data>
<data name="ExpectedOneCompleteToken" xml:space="preserve">
<value>The input does not contain any complete JSON tokens. Expected the input to have at least one valid, complete, JSON token.</value>
</data>
<data name="ExpectedNextDigitEValueNotFound" xml:space="preserve">
<value>'{0}' is an invalid end of a number. Expected 'E' or 'e'.</value>
</data>
<data name="ExpectedNull" xml:space="preserve">
<value>'{0}' is an invalid JSON literal. Expected the literal 'null'.</value>
</data>
<data name="ExpectedSeparatorAfterPropertyNameNotFound" xml:space="preserve">
<value>'{0}' is invalid after a property name. Expected a ':'.</value>
</data>
<data name="ExpectedStartOfPropertyNotFound" xml:space="preserve">
<value>'{0}' is an invalid start of a property name. Expected a '"'.</value>
</data>
<data name="ExpectedStartOfPropertyOrValueNotFound" xml:space="preserve">
<value>Expected start of a property name or value, but instead reached end of data.</value>
</data>
<data name="ExpectedStartOfValueNotFound" xml:space="preserve">
<value>'{0}' is an invalid start of a value.</value>
</data>
<data name="ExpectedTrue" xml:space="preserve">
<value>'{0}' is an invalid JSON literal. Expected the literal 'true'.</value>
</data>
<data name="ExpectedValueAfterPropertyNameNotFound" xml:space="preserve">
<value>Expected a value, but instead reached end of data.</value>
</data>
<data name="FailedToGetLargerSpan" xml:space="preserve">
<value>The 'IBufferWriter' could not provide an output buffer that is large enough to continue writing.</value>
</data>
<data name="FoundInvalidCharacter" xml:space="preserve">
<value>'{0}' is invalid after a value. Expected either ',', '}}', or ']'.</value>
</data>
<data name="InvalidCast" xml:space="preserve">
<value>Cannot get the value of a token type '{0}' as a {1}.</value>
</data>
<data name="InvalidCharacterAfterEscapeWithinString" xml:space="preserve">
<value>'{0}' is an invalid escapable character within a JSON string. The string should be correctly escaped.</value>
</data>
<data name="InvalidCharacterWithinString" xml:space="preserve">
<value>'{0}' is invalid within a JSON string. The string should be correctly escaped.</value>
</data>
<data name="InvalidEndOfJsonNonPrimitive" xml:space="preserve">
<value>'{0}' is an invalid token type for the end of the JSON payload. Expected either 'EndArray' or 'EndObject'.</value>
</data>
<data name="InvalidHexCharacterWithinString" xml:space="preserve">
<value>'{0}' is not a hex digit following '\u' within a JSON string. The string should be correctly escaped.</value>
</data>
<data name="JsonDocumentDoesNotSupportComments" xml:space="preserve">
<value>Comments cannot be stored in a JsonDocument, only the Skip and Disallow comment handling modes are supported.</value>
</data>
<data name="JsonElementHasWrongType" xml:space="preserve">
<value>The requested operation requires an element of type '{0}', but the target element has type '{1}'.</value>
</data>
<data name="MaxDepthMustBePositive" xml:space="preserve">
<value>Max depth must be positive.</value>
</data>
<data name="CommentHandlingMustBeValid" xml:space="preserve">
<value>The JsonCommentHandling enum must be set to one of the supported values.</value>
</data>
<data name="MismatchedObjectArray" xml:space="preserve">
<value>'{0}' is invalid without a matching open.</value>
</data>
<data name="CannotWriteEndAfterProperty" xml:space="preserve">
<value>'{0}' is invalid following a property name.</value>
</data>
<data name="ObjectDepthTooLarge" xml:space="preserve">
<value>The maximum configured depth of {0} has been exceeded. Cannot read next JSON object.</value>
</data>
<data name="PropertyNameTooLarge" xml:space="preserve">
<value>The JSON property name of length {0} is too large and not supported.</value>
</data>
<data name="FormatDecimal" xml:space="preserve">
<value>The JSON value is either too large or too small for a Decimal.</value>
</data>
<data name="FormatDouble" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a Double.</value>
</data>
<data name="FormatInt32" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for an Int32.</value>
</data>
<data name="FormatInt64" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for an Int64.</value>
</data>
<data name="FormatSingle" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a Single.</value>
</data>
<data name="FormatUInt32" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a UInt32.</value>
</data>
<data name="FormatUInt64" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a UInt64.</value>
</data>
<data name="RequiredDigitNotFoundAfterDecimal" xml:space="preserve">
<value>'{0}' is invalid within a number, immediately after a decimal point ('.'). Expected a digit ('0'-'9').</value>
</data>
<data name="RequiredDigitNotFoundAfterSign" xml:space="preserve">
<value>'{0}' is invalid within a number, immediately after a sign character ('+' or '-'). Expected a digit ('0'-'9').</value>
</data>
<data name="RequiredDigitNotFoundEndOfData" xml:space="preserve">
<value>Expected a digit ('0'-'9'), but instead reached end of data.</value>
</data>
<data name="SpecialNumberValuesNotSupported" xml:space="preserve">
<value>.NET number values such as positive and negative infinity cannot be written as valid JSON. To make it work when using 'JsonSerializer', consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://docs.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).</value>
</data>
<data name="ValueTooLarge" xml:space="preserve">
<value>The JSON value of length {0} is too large and not supported.</value>
</data>
<data name="ZeroDepthAtEnd" xml:space="preserve">
<value>Expected depth to be zero at the end of the JSON payload. There is an open JSON object or array that should be closed.</value>
</data>
<data name="DeserializeUnableToConvertValue" xml:space="preserve">
<value>The JSON value could not be converted to {0}.</value>
</data>
<data name="DeserializeWrongType" xml:space="preserve">
<value>The specified type {0} must derive from the specific value's type {1}.</value>
</data>
<data name="SerializationInvalidBufferSize" xml:space="preserve">
<value>The value must be greater than zero.</value>
</data>
<data name="BufferWriterAdvancedTooFar" xml:space="preserve">
<value>Cannot advance past the end of the buffer, which has a size of {0}.</value>
</data>
<data name="InvalidComparison" xml:space="preserve">
<value>Cannot compare the value of a token type '{0}' to text.</value>
</data>
<data name="FormatDateTime" xml:space="preserve">
<value>The JSON value is not in a supported DateTime format.</value>
</data>
<data name="FormatDateTimeOffset" xml:space="preserve">
<value>The JSON value is not in a supported DateTimeOffset format.</value>
</data>
<data name="FormatTimeSpan" xml:space="preserve">
<value>The JSON value is not in a supported TimeSpan format.</value>
</data>
<data name="FormatGuid" xml:space="preserve">
<value>The JSON value is not in a supported Guid format.</value>
</data>
<data name="FormatVersion" xml:space="preserve">
<value>The JSON value is not in a supported Version format.</value>
</data>
<data name="ExpectedStartOfPropertyOrValueAfterComment" xml:space="preserve">
<value>'{0}' is an invalid start of a property name or value, after a comment.</value>
</data>
<data name="TrailingCommaNotAllowedBeforeArrayEnd" xml:space="preserve">
<value>The JSON array contains a trailing comma at the end which is not supported in this mode. Change the reader options.</value>
</data>
<data name="TrailingCommaNotAllowedBeforeObjectEnd" xml:space="preserve">
<value>The JSON object contains a trailing comma at the end which is not supported in this mode. Change the reader options.</value>
</data>
<data name="SerializerOptionsImmutable" xml:space="preserve">
<value>Serializer options cannot be changed once serialization or deserialization has occurred.</value>
</data>
<data name="StreamNotWritable" xml:space="preserve">
<value>Stream is not writable.</value>
</data>
<data name="CannotWriteCommentWithEmbeddedDelimiter" xml:space="preserve">
<value>Cannot write a comment value which contains the end of comment delimiter.</value>
</data>
<data name="SerializerPropertyNameConflict" xml:space="preserve">
<value>The JSON property name for '{0}.{1}' collides with another property.</value>
</data>
<data name="SerializerPropertyNameNull" xml:space="preserve">
<value>The JSON property name for '{0}.{1}' cannot be null.</value>
</data>
<data name="SerializationDataExtensionPropertyInvalid" xml:space="preserve">
<value>The data extension property '{0}.{1}' is invalid. It must implement 'IDictionary<string, JsonElement>' or 'IDictionary<string, object>', or be 'JsonObject'.</value>
</data>
<data name="SerializationDuplicateTypeAttribute" xml:space="preserve">
<value>The type '{0}' cannot have more than one member that has the attribute '{1}'.</value>
</data>
<data name="SerializationNotSupportedType" xml:space="preserve">
<value>The type '{0}' is not supported.</value>
</data>
<data name="TypeRequiresAsyncSerialization" xml:space="preserve">
<value>The type '{0}' can only be serialized using async serialization methods.</value>
</data>
<data name="InvalidCharacterAtStartOfComment" xml:space="preserve">
<value>'{0}' is invalid after '/' at the beginning of the comment. Expected either '/' or '*'.</value>
</data>
<data name="UnexpectedEndOfDataWhileReadingComment" xml:space="preserve">
<value>Unexpected end of data while reading a comment.</value>
</data>
<data name="CannotSkip" xml:space="preserve">
<value>Cannot skip tokens on partial JSON. Either get the whole payload and create a Utf8JsonReader instance where isFinalBlock is true or call TrySkip.</value>
</data>
<data name="NotEnoughData" xml:space="preserve">
<value>There is not enough data to read through the entire JSON array or object.</value>
</data>
<data name="UnexpectedEndOfLineSeparator" xml:space="preserve">
<value>Found invalid line or paragraph separator character while reading a comment.</value>
</data>
<data name="JsonSerializerDoesNotSupportComments" xml:space="preserve">
<value>Comments cannot be stored when deserializing objects, only the Skip and Disallow comment handling modes are supported.</value>
</data>
<data name="DeserializeNoConstructor" xml:space="preserve">
<value>Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with '{0}' is not supported. Type '{1}'.</value>
</data>
<data name="DeserializePolymorphicInterface" xml:space="preserve">
<value>Deserialization of interface types is not supported. Type '{0}'.</value>
</data>
<data name="SerializationConverterOnAttributeNotCompatible" xml:space="preserve">
<value>The converter specified on '{0}' is not compatible with the type '{1}'.</value>
</data>
<data name="SerializationConverterOnAttributeInvalid" xml:space="preserve">
<value>The converter specified on '{0}' does not derive from JsonConverter or have a public parameterless constructor.</value>
</data>
<data name="SerializationConverterRead" xml:space="preserve">
<value>The converter '{0}' read too much or not enough.</value>
</data>
<data name="SerializationConverterNotCompatible" xml:space="preserve">
<value>The converter '{0}' is not compatible with the type '{1}'.</value>
</data>
<data name="SerializationConverterWrite" xml:space="preserve">
<value>The converter '{0}' wrote too much or not enough.</value>
</data>
<data name="NamingPolicyReturnNull" xml:space="preserve">
<value>The naming policy '{0}' cannot return null.</value>
</data>
<data name="SerializationDuplicateAttribute" xml:space="preserve">
<value>The attribute '{0}' cannot exist more than once on '{1}'.</value>
</data>
<data name="SerializeUnableToSerialize" xml:space="preserve">
<value>The object or value could not be serialized.</value>
</data>
<data name="FormatByte" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for an unsigned byte.</value>
</data>
<data name="FormatInt16" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for an Int16.</value>
</data>
<data name="FormatSByte" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a signed byte.</value>
</data>
<data name="FormatUInt16" xml:space="preserve">
<value>Either the JSON value is not in a supported format, or is out of bounds for a UInt16.</value>
</data>
<data name="SerializerCycleDetected" xml:space="preserve">
<value>A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of {0}. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.</value>
</data>
<data name="InvalidLeadingZeroInNumber" xml:space="preserve">
<value>Invalid leading zero before '{0}'.</value>
</data>
<data name="MetadataCannotParsePreservedObjectToImmutable" xml:space="preserve">
<value>Cannot parse a JSON object containing metadata properties like '$id' into an array or immutable collection type. Type '{0}'.</value>
</data>
<data name="MetadataDuplicateIdFound" xml:space="preserve">
<value>The value of the '$id' metadata property '{0}' conflicts with an existing identifier.</value>
</data>
<data name="MetadataIdIsNotFirstProperty" xml:space="preserve">
<value>The metadata property '$id' must be the first property in the JSON object.</value>
</data>
<data name="MetadataInvalidReferenceToValueType" xml:space="preserve">
<value>Invalid reference to value type '{0}'.</value>
</data>
<data name="MetadataInvalidTokenAfterValues" xml:space="preserve">
<value>The '$values' metadata property must be a JSON array. Current token type is '{0}'.</value>
</data>
<data name="MetadataPreservedArrayFailed" xml:space="preserve">
<value>Deserialization failed for one of these reasons:
1. {0}
2. {1}</value>
</data>
<data name="MetadataPreservedArrayInvalidProperty" xml:space="preserve">
<value>Invalid property '{0}' found within a JSON object that must only contain metadata properties and the nested JSON array to be preserved.</value>
</data>
<data name="MetadataPreservedArrayPropertyNotFound" xml:space="preserve">
<value>One or more metadata properties, such as '$id' and '$values', were not found within a JSON object that must only contain metadata properties and the nested JSON array to be preserved.</value>
</data>
<data name="MetadataReferenceCannotContainOtherProperties" xml:space="preserve">
<value>A JSON object that contains a '$ref' metadata property must not contain any other properties.</value>
</data>
<data name="MetadataReferenceNotFound" xml:space="preserve">
<value>Reference '{0}' not found.</value>
</data>
<data name="MetadataValueWasNotString" xml:space="preserve">
<value>The '$id' and '$ref' metadata properties must be JSON strings. Current token type is '{0}'.</value>
</data>
<data name="MetadataInvalidPropertyWithLeadingDollarSign" xml:space="preserve">
<value>Properties that start with '$' are not allowed on preserve mode, either escape the character or turn off preserve references by setting ReferenceHandler to null.</value>
</data>
<data name="MultipleMembersBindWithConstructorParameter" xml:space="preserve">
<value>Members '{0}' and '{1}' on type '{2}' cannot both bind with parameter '{3}' in the deserialization constructor.</value>
</data>
<data name="ConstructorParamIncompleteBinding" xml:space="preserve">
<value>Each parameter in the deserialization constructor on type '{0}' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.</value>
</data>
<data name="ConstructorMaxOf64Parameters" xml:space="preserve">
<value>The deserialization constructor on type '{0}' may not have more than 64 parameters for deserialization.</value>
</data>
<data name="ObjectWithParameterizedCtorRefMetadataNotHonored" xml:space="preserve">
<value>Reference metadata is not honored when deserializing types using parameterized constructors. See type '{0}'.</value>
</data>
<data name="SerializerConverterFactoryReturnsNull" xml:space="preserve">
<value>The converter '{0}' cannot return a null value.</value>
</data>
<data name="SerializationNotSupportedParentType" xml:space="preserve">
<value>The unsupported member type is located on type '{0}'.</value>
</data>
<data name="ExtensionDataCannotBindToCtorParam" xml:space="preserve">
<value>The extension data property '{0}' on type '{1}' cannot bind with a parameter in the deserialization constructor.</value>
</data>
<data name="BufferMaximumSizeExceeded" xml:space="preserve">
<value>Cannot allocate a buffer of size {0}.</value>
</data>
<data name="CannotSerializeInvalidType" xml:space="preserve">
<value>The type '{0}' is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types.</value>
</data>
<data name="SerializeTypeInstanceNotSupported" xml:space="preserve">
<value>Serialization and deserialization of '{0}' instances are not supported.</value>
</data>
<data name="JsonIncludeOnNonPublicInvalid" xml:space="preserve">
<value>The non-public property '{0}' on type '{1}' is annotated with 'JsonIncludeAttribute' which is invalid.</value>
</data>
<data name="CannotSerializeInvalidMember" xml:space="preserve">
<value>The type '{0}' of property '{1}' on type '{2}' is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types.</value>
</data>
<data name="CannotPopulateCollection" xml:space="preserve">
<value>The collection type '{0}' is abstract, an interface, or is read only, and could not be instantiated and populated.</value>
</data>
<data name="DefaultIgnoreConditionAlreadySpecified" xml:space="preserve">
<value>'IgnoreNullValues' and 'DefaultIgnoreCondition' cannot both be set to non-default values.</value>
</data>
<data name="DefaultIgnoreConditionInvalid" xml:space="preserve">
<value>The value cannot be 'JsonIgnoreCondition.Always'.</value>
</data>
<data name="FormatBoolean" xml:space="preserve">
<value>The JSON value is not in a supported Boolean format.</value>
</data>
<data name="DictionaryKeyTypeNotSupported" xml:space="preserve">
<value>The type '{0}' is not a supported dictionary key using converter of type '{1}'.</value>
</data>
<data name="IgnoreConditionOnValueTypeInvalid" xml:space="preserve">
<value>The ignore condition 'JsonIgnoreCondition.WhenWritingNull' is not valid on value-type member '{0}' on type '{1}'. Consider using 'JsonIgnoreCondition.WhenWritingDefault'.</value>
</data>
<data name="NumberHandlingOnPropertyInvalid" xml:space="preserve">
<value>'JsonNumberHandlingAttribute' is only valid on a number or a collection of numbers when applied to a property or field. See member '{0}' on type '{1}'.</value>
</data>
<data name="ConverterCanConvertMultipleTypes" xml:space="preserve">
<value>The converter '{0}' handles type '{1}' but is being asked to convert type '{2}'. Either create a separate converter for type '{2}' or change the converter's 'CanConvert' method to only return 'true' for a single type.</value>
</data>
<data name="MetadataReferenceOfTypeCannotBeAssignedToType" xml:space="preserve">
<value>The object with reference id '{0}' of type '{1}' cannot be assigned to the type '{2}'.</value>
</data>
<data name="DeserializeUnableToAssignValue" xml:space="preserve">
<value>Unable to cast object of type '{0}' to type '{1}'.</value>
</data>
<data name="DeserializeUnableToAssignNull" xml:space="preserve">
<value>Unable to assign 'null' to the property or field of type '{0}'.</value>
</data>
<data name="SerializerConverterFactoryReturnsJsonConverterFactory" xml:space="preserve">
<value>The converter '{0}' cannot return an instance of JsonConverterFactory.</value>
</data>
<data name="NodeElementWrongType" xml:space="preserve">
<value>The element must be of type '{0}'</value>
</data>
<data name="NodeElementCannotBeObjectOrArray" xml:space="preserve">
<value>The element cannot be an object or array.</value>
</data>
<data name="NodeAlreadyHasParent" xml:space="preserve">
<value>The node already has a parent.</value>
</data>
<data name="NodeCycleDetected" xml:space="preserve">
<value>A node cycle was detected.</value>
</data>
<data name="NodeUnableToConvert" xml:space="preserve">
<value>A value of type '{0}' cannot be converted to a '{1}'.</value>
</data>
<data name="NodeUnableToConvertElement" xml:space="preserve">
<value>An element of type '{0}' cannot be converted to a '{1}'.</value>
</data>
<data name="NodeValueNotAllowed" xml:space="preserve">
<value>A JsonNode cannot be used as a value.</value>
</data>
<data name="NodeWrongType" xml:space="preserve">
<value>The node must be of type '{0}'.</value>
</data>
<data name="NodeDuplicateKey" xml:space="preserve">
<value>An item with the same key has already been added. Key: {0}</value>
</data>
<data name="SerializerContextOptionsImmutable" xml:space="preserve">
<value>A 'JsonSerializerOptions' instance associated with a 'JsonSerializerContext' instance cannot be mutated once the context has been instantiated.</value>
</data>
<data name="ConverterForPropertyMustBeValid" xml:space="preserve">
<value>The generic type of the converter for property '{0}.{1}' must match with the specified converter type '{2}'. The converter must not be 'null'.</value>
</data>
<data name="BuiltInConvertersNotRooted" xml:space="preserve">
<value>Built-in type converters have not been initialized. There is no converter available for type '{0}'. To root all built-in converters, use a 'JsonSerializerOptions'-based method of the 'JsonSerializer'.</value>
</data>
<data name="NoMetadataForType" xml:space="preserve">
<value>Metadata for type '{0}' was not provided to the serializer. The serializer method used does not support reflection-based creation of serialization-related type metadata. If using source generation, ensure that all root types passed to the serializer have been indicated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.</value>
</data>
<data name="NodeCollectionIsReadOnly" xml:space="preserve">
<value>Collection is read-only.</value>
</data>
<data name="NodeArrayIndexNegative" xml:space="preserve">
<value>Number was less than 0.</value>
</data>
<data name="NodeArrayTooSmall" xml:space="preserve">
<value>Destination array was not long enough.</value>
</data>
<data name="NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty" xml:space="preserve">
<value>A custom converter for JsonObject is not allowed on an extension property.</value>
</data>
<data name="MetadataInitFuncsNull" xml:space="preserve">
<value>Invalid configuration provided for 'propInitFunc', 'ctorParamInitFunc' and 'serializeFunc'.</value>
</data>
<data name="NoMetadataForTypeProperties" xml:space="preserve">
<value>'JsonSerializerContext' '{0}' did not provide property metadata for type '{1}'.</value>
</data>
<data name="NoDefaultOptionsForContext" xml:space="preserve">
<value>To specify a serialization implementation for type '{0}'', context '{0}' must specify default options.</value>
</data>
<data name="FieldCannotBeVirtual" xml:space="preserve">
<value>A 'field' member cannot be 'virtual'. See arguments for the '{0}' and '{1}' parameters. </value>
</data>
<data name="MissingFSharpCoreMember" xml:space="preserve">
<value>Could not locate required member '{0}' from FSharp.Core. This might happen because your application has enabled member-level trimming.</value>
</data>
<data name="FSharpDiscriminatedUnionsNotSupported" xml:space="preserve">
<value>F# discriminated union serialization is not supported. Consider authoring a custom converter for the type.</value>
</data>
<data name="NoMetadataForTypeCtorParams" xml:space="preserve">
<value>'JsonSerializerContext' '{0}' did not provide constructor parameter metadata for type '{1}'.</value>
</data>
</root>
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.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.Text.Json.Serialization.Metadata;
namespace System.Text.Json.Serialization.Converters
{
/// <summary>
/// Provides a mechanism to invoke "fast-path" serialization logic via
/// <see cref="JsonTypeInfo{T}.SerializeHandler"/>. This type holds an optional
/// reference to an actual <see cref="JsonConverter{T}"/> for the type
/// <typeparamref name="T"/>, to provide a fallback when the fast path cannot be used.
/// </summary>
/// <typeparam name="T">The type to converter</typeparam>
internal sealed class JsonMetadataServicesConverter<T> : JsonResumableConverter<T>
{
private readonly Func<JsonConverter<T>> _converterCreator;
private readonly ConverterStrategy _converterStrategy;
private JsonConverter<T>? _converter;
// A backing converter for when fast-path logic cannot be used.
internal JsonConverter<T> Converter
{
get
{
_converter ??= _converterCreator();
Debug.Assert(_converter != null);
Debug.Assert(_converter.ConverterStrategy == _converterStrategy);
return _converter;
}
}
internal override ConverterStrategy ConverterStrategy => _converterStrategy;
internal override Type? KeyType => Converter.KeyType;
internal override Type? ElementType => Converter.ElementType;
internal override bool ConstructorIsParameterized => Converter.ConstructorIsParameterized;
public JsonMetadataServicesConverter(Func<JsonConverter<T>> converterCreator!!, ConverterStrategy converterStrategy)
{
_converterCreator = converterCreator;
_converterStrategy = converterStrategy;
}
internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T? value)
{
JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo;
if (_converterStrategy == ConverterStrategy.Object)
{
if (jsonTypeInfo.PropertyCache == null)
{
jsonTypeInfo.InitializePropCache();
}
if (jsonTypeInfo.ParameterCache == null && jsonTypeInfo.IsObjectWithParameterizedCtor)
{
jsonTypeInfo.InitializeParameterCache();
}
}
return Converter.OnTryRead(ref reader, typeToConvert, options, ref state, out value);
}
internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state)
{
JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo;
Debug.Assert(options == jsonTypeInfo.Options);
if (!state.SupportContinuation &&
jsonTypeInfo is JsonTypeInfo<T> info &&
info.SerializeHandler != null &&
info.Options._serializerContext?.CanUseSerializationLogic == true)
{
info.SerializeHandler(writer, value);
return true;
}
if (_converterStrategy == ConverterStrategy.Object && jsonTypeInfo.PropertyCache == null)
{
jsonTypeInfo.InitializePropCache();
}
return Converter.OnTryWrite(writer, value, options, ref state);
}
internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options)
=> Converter.ConfigureJsonTypeInfo(jsonTypeInfo, options);
}
}
| // 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.Text.Json.Serialization.Metadata;
namespace System.Text.Json.Serialization.Converters
{
/// <summary>
/// Provides a mechanism to invoke "fast-path" serialization logic via
/// <see cref="JsonTypeInfo{T}.SerializeHandler"/>. This type holds an optional
/// reference to an actual <see cref="JsonConverter{T}"/> for the type
/// <typeparamref name="T"/>, to provide a fallback when the fast path cannot be used.
/// </summary>
/// <typeparam name="T">The type to converter</typeparam>
internal sealed class JsonMetadataServicesConverter<T> : JsonResumableConverter<T>
{
private readonly Func<JsonConverter<T>> _converterCreator;
private readonly ConverterStrategy _converterStrategy;
private JsonConverter<T>? _converter;
// A backing converter for when fast-path logic cannot be used.
internal JsonConverter<T> Converter
{
get
{
_converter ??= _converterCreator();
Debug.Assert(_converter != null);
Debug.Assert(_converter.ConverterStrategy == _converterStrategy);
return _converter;
}
}
internal override ConverterStrategy ConverterStrategy => _converterStrategy;
internal override Type? KeyType => Converter.KeyType;
internal override Type? ElementType => Converter.ElementType;
internal override bool ConstructorIsParameterized => Converter.ConstructorIsParameterized;
public JsonMetadataServicesConverter(Func<JsonConverter<T>> converterCreator!!, ConverterStrategy converterStrategy)
{
_converterCreator = converterCreator;
_converterStrategy = converterStrategy;
}
internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T? value)
{
JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo;
if (_converterStrategy == ConverterStrategy.Object)
{
if (jsonTypeInfo.PropertyCache == null)
{
jsonTypeInfo.InitializePropCache();
}
if (jsonTypeInfo.ParameterCache == null && jsonTypeInfo.IsObjectWithParameterizedCtor)
{
jsonTypeInfo.InitializeParameterCache();
}
}
return Converter.OnTryRead(ref reader, typeToConvert, options, ref state, out value);
}
internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state)
{
JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo;
Debug.Assert(options == jsonTypeInfo.Options);
if (!state.SupportContinuation &&
jsonTypeInfo is JsonTypeInfo<T> info &&
info.SerializeHandler != null &&
info.Options.JsonSerializerContext?.CanUseSerializationLogic == true)
{
info.SerializeHandler(writer, value);
return true;
}
if (_converterStrategy == ConverterStrategy.Object && jsonTypeInfo.PropertyCache == null)
{
jsonTypeInfo.InitializePropCache();
}
return Converter.OnTryWrite(writer, value, options, ref state);
}
internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options)
=> Converter.ConfigureJsonTypeInfo(jsonTypeInfo, options);
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
public static partial class JsonSerializer
{
internal const string SerializationUnreferencedCodeMessage = "JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.";
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
private static JsonTypeInfo GetTypeInfo(JsonSerializerOptions? options, Type runtimeType)
{
Debug.Assert(runtimeType != null);
options ??= JsonSerializerOptions.Default;
if (!JsonSerializerOptions.IsInitializedForReflectionSerializer)
{
JsonSerializerOptions.InitializeForReflectionSerializer();
}
return options.GetOrAddJsonTypeInfoForRootType(runtimeType);
}
private static JsonTypeInfo GetTypeInfo(JsonSerializerContext context, Type type)
{
Debug.Assert(context != null);
Debug.Assert(type != null);
JsonTypeInfo? info = context.GetTypeInfo(type);
if (info is null)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForType(type);
}
return info;
}
internal static bool IsValidNumberHandlingValue(JsonNumberHandling handling) =>
JsonHelpers.IsInRangeInclusive((int)handling, 0,
(int)(
JsonNumberHandling.Strict |
JsonNumberHandling.AllowReadingFromString |
JsonNumberHandling.WriteAsString |
JsonNumberHandling.AllowNamedFloatingPointLiterals));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
public static partial class JsonSerializer
{
internal const string SerializationUnreferencedCodeMessage = "JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.";
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
private static JsonTypeInfo GetTypeInfo(JsonSerializerOptions? options, Type runtimeType)
{
Debug.Assert(runtimeType != null);
options ??= JsonSerializerOptions.Default;
if (!options.IsInitializedForReflectionSerializer)
{
options.InitializeForReflectionSerializer();
}
return options.GetOrAddJsonTypeInfoForRootType(runtimeType);
}
private static JsonTypeInfo GetTypeInfo(JsonSerializerContext context, Type type)
{
Debug.Assert(context != null);
Debug.Assert(type != null);
JsonTypeInfo? info = context.GetTypeInfo(type);
if (info is null)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForType(type);
}
return info;
}
internal static bool IsValidNumberHandlingValue(JsonNumberHandling handling) =>
JsonHelpers.IsInRangeInclusive((int)handling, 0,
(int)(
JsonNumberHandling.Strict |
JsonNumberHandling.AllowReadingFromString |
JsonNumberHandling.WriteAsString |
JsonNumberHandling.AllowNamedFloatingPointLiterals));
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
namespace System.Text.Json
{
public static partial class JsonSerializer
{
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
/// The Stream will be read to completion.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
/// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <param name="cancellationToken">
/// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// <typeparamref name="TValue"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <typeparamref name="TValue"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static ValueTask<TValue?> DeserializeAsync<TValue>(
Stream utf8Json!!,
JsonSerializerOptions? options = null,
CancellationToken cancellationToken = default)
{
JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue));
return ReadAllAsync<TValue>(utf8Json, jsonTypeInfo, cancellationToken);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
/// The Stream will be read to completion.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
/// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// <typeparamref name="TValue"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <typeparamref name="TValue"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static TValue? Deserialize<TValue>(
Stream utf8Json!!,
JsonSerializerOptions? options = null)
{
return ReadAllUsingOptions<TValue>(utf8Json, typeof(TValue), options);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
/// The Stream will be read to completion.
/// </summary>
/// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="returnType">The type of the object to convert to and return.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <param name="cancellationToken">
/// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// the <paramref name="returnType"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="returnType"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static ValueTask<object?> DeserializeAsync(
Stream utf8Json!!,
Type returnType!!,
JsonSerializerOptions? options = null,
CancellationToken cancellationToken = default)
{
JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
return ReadAllAsync<object?>(utf8Json, jsonTypeInfo, cancellationToken);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
/// The Stream will be read to completion.
/// </summary>
/// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="returnType">The type of the object to convert to and return.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// the <paramref name="returnType"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="returnType"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static object? Deserialize(
Stream utf8Json!!,
Type returnType!!,
JsonSerializerOptions? options = null)
{
return ReadAllUsingOptions<object>(utf8Json, returnType, options);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
/// The Stream will be read to completion.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
/// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
/// <param name="cancellationToken">
/// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// <typeparamref name="TValue"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <typeparamref name="TValue"/> or its serializable members.
/// </exception>
public static ValueTask<TValue?> DeserializeAsync<TValue>(
Stream utf8Json!!,
JsonTypeInfo<TValue> jsonTypeInfo!!,
CancellationToken cancellationToken = default)
{
return ReadAllAsync<TValue>(utf8Json, jsonTypeInfo, cancellationToken);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
/// The Stream will be read to completion.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
/// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// <typeparamref name="TValue"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <typeparamref name="TValue"/> or its serializable members.
/// </exception>
public static TValue? Deserialize<TValue>(
Stream utf8Json!!,
JsonTypeInfo<TValue> jsonTypeInfo!!)
{
return ReadAll<TValue>(utf8Json, jsonTypeInfo);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
/// The Stream will be read to completion.
/// </summary>
/// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="returnType">The type of the object to convert to and return.</param>
/// <param name="context">A metadata provider for serializable types.</param>
/// <param name="cancellationToken">
/// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// the <paramref name="returnType"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="returnType"/> or its serializable members.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
/// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
/// </exception>
public static ValueTask<object?> DeserializeAsync(
Stream utf8Json!!,
Type returnType!!,
JsonSerializerContext context!!,
CancellationToken cancellationToken = default)
{
return ReadAllAsync<object>(utf8Json, GetTypeInfo(context, returnType), cancellationToken);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
/// The Stream will be read to completion.
/// </summary>
/// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="returnType">The type of the object to convert to and return.</param>
/// <param name="context">A metadata provider for serializable types.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// the <paramref name="returnType"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="returnType"/> or its serializable members.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
/// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
/// </exception>
public static object? Deserialize(
Stream utf8Json!!,
Type returnType!!,
JsonSerializerContext context!!)
{
return ReadAll<object>(utf8Json, GetTypeInfo(context, returnType));
}
/// <summary>
/// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
/// that can be used to deserialize root-level JSON arrays in a streaming manner.
/// </summary>
/// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
/// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON array.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.</param>
/// <returns>An <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> is <see langword="null"/>.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
Stream utf8Json!!,
JsonSerializerOptions? options = null,
CancellationToken cancellationToken = default)
{
options ??= JsonSerializerOptions.Default;
if (!JsonSerializerOptions.IsInitializedForReflectionSerializer)
{
JsonSerializerOptions.InitializeForReflectionSerializer();
}
return CreateAsyncEnumerableDeserializer(utf8Json, options, cancellationToken);
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
static async IAsyncEnumerable<TValue> CreateAsyncEnumerableDeserializer(
Stream utf8Json,
JsonSerializerOptions options,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
var bufferState = new ReadBufferState(options.DefaultBufferSize);
// Hardcode the queue converter to avoid accidental use of custom converters
JsonConverter converter = QueueOfTConverter<Queue<TValue>, TValue>.Instance;
JsonTypeInfo jsonTypeInfo = CreateQueueJsonTypeInfo<TValue>(converter, options);
ReadStack readStack = default;
readStack.Initialize(jsonTypeInfo, supportContinuation: true);
var jsonReaderState = new JsonReaderState(options.GetReaderOptions());
try
{
do
{
bufferState = await ReadFromStreamAsync(utf8Json, bufferState, cancellationToken).ConfigureAwait(false);
ContinueDeserialize<Queue<TValue>>(ref bufferState, ref jsonReaderState, ref readStack, converter, options);
if (readStack.Current.ReturnValue is Queue<TValue> queue)
{
while (queue.Count > 0)
{
yield return queue.Dequeue();
}
}
}
while (!bufferState.IsFinalBlock);
}
finally
{
bufferState.Dispose();
}
}
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Workaround for https://github.com/mono/linker/issues/1416. All usages are marked as unsafe.")]
private static JsonTypeInfo CreateQueueJsonTypeInfo<TValue>(JsonConverter queueConverter, JsonSerializerOptions queueOptions) =>
new JsonTypeInfo(typeof(Queue<TValue>), queueConverter, queueOptions);
internal static async ValueTask<TValue?> ReadAllAsync<TValue>(
Stream utf8Json,
JsonTypeInfo jsonTypeInfo,
CancellationToken cancellationToken)
{
JsonSerializerOptions options = jsonTypeInfo.Options;
var bufferState = new ReadBufferState(options.DefaultBufferSize);
ReadStack readStack = default;
readStack.Initialize(jsonTypeInfo, supportContinuation: true);
JsonConverter converter = readStack.Current.JsonPropertyInfo!.ConverterBase;
var jsonReaderState = new JsonReaderState(options.GetReaderOptions());
try
{
while (true)
{
bufferState = await ReadFromStreamAsync(utf8Json, bufferState, cancellationToken).ConfigureAwait(false);
TValue value = ContinueDeserialize<TValue>(ref bufferState, ref jsonReaderState, ref readStack, converter, options);
if (bufferState.IsFinalBlock)
{
return value!;
}
}
}
finally
{
bufferState.Dispose();
}
}
internal static TValue? ReadAll<TValue>(
Stream utf8Json,
JsonTypeInfo jsonTypeInfo)
{
JsonSerializerOptions options = jsonTypeInfo.Options;
var bufferState = new ReadBufferState(options.DefaultBufferSize);
ReadStack readStack = default;
readStack.Initialize(jsonTypeInfo, supportContinuation: true);
JsonConverter converter = readStack.Current.JsonPropertyInfo!.ConverterBase;
var jsonReaderState = new JsonReaderState(options.GetReaderOptions());
try
{
while (true)
{
bufferState = ReadFromStream(utf8Json, bufferState);
TValue value = ContinueDeserialize<TValue>(ref bufferState, ref jsonReaderState, ref readStack, converter, options);
if (bufferState.IsFinalBlock)
{
return value!;
}
}
}
finally
{
bufferState.Dispose();
}
}
/// <summary>
/// Read from the stream until either our buffer is filled or we hit EOF.
/// Calling ReadCore is relatively expensive, so we minimize the number of times
/// we need to call it.
/// </summary>
internal static async ValueTask<ReadBufferState> ReadFromStreamAsync(
Stream utf8Json,
ReadBufferState bufferState,
CancellationToken cancellationToken)
{
while (true)
{
int bytesRead = await utf8Json.ReadAsync(
#if BUILDING_INBOX_LIBRARY
bufferState.Buffer.AsMemory(bufferState.BytesInBuffer),
#else
bufferState.Buffer, bufferState.BytesInBuffer, bufferState.Buffer.Length - bufferState.BytesInBuffer,
#endif
cancellationToken).ConfigureAwait(false);
if (bytesRead == 0)
{
bufferState.IsFinalBlock = true;
break;
}
bufferState.BytesInBuffer += bytesRead;
if (bufferState.BytesInBuffer == bufferState.Buffer.Length)
{
break;
}
}
return bufferState;
}
/// <summary>
/// Read from the stream until either our buffer is filled or we hit EOF.
/// Calling ReadCore is relatively expensive, so we minimize the number of times
/// we need to call it.
/// </summary>
internal static ReadBufferState ReadFromStream(
Stream utf8Json,
ReadBufferState bufferState)
{
while (true)
{
int bytesRead = utf8Json.Read(
#if BUILDING_INBOX_LIBRARY
bufferState.Buffer.AsSpan(bufferState.BytesInBuffer));
#else
bufferState.Buffer, bufferState.BytesInBuffer, bufferState.Buffer.Length - bufferState.BytesInBuffer);
#endif
if (bytesRead == 0)
{
bufferState.IsFinalBlock = true;
break;
}
bufferState.BytesInBuffer += bytesRead;
if (bufferState.BytesInBuffer == bufferState.Buffer.Length)
{
break;
}
}
return bufferState;
}
internal static TValue ContinueDeserialize<TValue>(
ref ReadBufferState bufferState,
ref JsonReaderState jsonReaderState,
ref ReadStack readStack,
JsonConverter converter,
JsonSerializerOptions options)
{
if (bufferState.BytesInBuffer > bufferState.ClearMax)
{
bufferState.ClearMax = bufferState.BytesInBuffer;
}
int start = 0;
if (bufferState.IsFirstIteration)
{
bufferState.IsFirstIteration = false;
// Handle the UTF-8 BOM if present
Debug.Assert(bufferState.Buffer.Length >= JsonConstants.Utf8Bom.Length);
if (bufferState.Buffer.AsSpan().StartsWith(JsonConstants.Utf8Bom))
{
start += JsonConstants.Utf8Bom.Length;
bufferState.BytesInBuffer -= JsonConstants.Utf8Bom.Length;
}
}
// Process the data available
TValue value = ReadCore<TValue>(
ref jsonReaderState,
bufferState.IsFinalBlock,
new ReadOnlySpan<byte>(bufferState.Buffer, start, bufferState.BytesInBuffer),
options,
ref readStack,
converter);
Debug.Assert(readStack.BytesConsumed <= bufferState.BytesInBuffer);
int bytesConsumed = checked((int)readStack.BytesConsumed);
bufferState.BytesInBuffer -= bytesConsumed;
// The reader should have thrown if we have remaining bytes.
Debug.Assert(!bufferState.IsFinalBlock || bufferState.BytesInBuffer == 0);
if (!bufferState.IsFinalBlock)
{
// Check if we need to shift or expand the buffer because there wasn't enough data to complete deserialization.
if ((uint)bufferState.BytesInBuffer > ((uint)bufferState.Buffer.Length / 2))
{
// We have less than half the buffer available, double the buffer size.
byte[] oldBuffer = bufferState.Buffer;
int oldClearMax = bufferState.ClearMax;
byte[] newBuffer = ArrayPool<byte>.Shared.Rent((bufferState.Buffer.Length < (int.MaxValue / 2)) ? bufferState.Buffer.Length * 2 : int.MaxValue);
// Copy the unprocessed data to the new buffer while shifting the processed bytes.
Buffer.BlockCopy(oldBuffer, bytesConsumed + start, newBuffer, 0, bufferState.BytesInBuffer);
bufferState.Buffer = newBuffer;
bufferState.ClearMax = bufferState.BytesInBuffer;
// Clear and return the old buffer
new Span<byte>(oldBuffer, 0, oldClearMax).Clear();
ArrayPool<byte>.Shared.Return(oldBuffer);
}
else if (bufferState.BytesInBuffer != 0)
{
// Shift the processed bytes to the beginning of buffer to make more room.
Buffer.BlockCopy(bufferState.Buffer, bytesConsumed + start, bufferState.Buffer, 0, bufferState.BytesInBuffer);
}
}
return value;
}
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
private static TValue? ReadAllUsingOptions<TValue>(
Stream utf8Json,
Type returnType,
JsonSerializerOptions? options)
{
JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
return ReadAll<TValue>(utf8Json, jsonTypeInfo);
}
private static TValue ReadCore<TValue>(
ref JsonReaderState readerState,
bool isFinalBlock,
ReadOnlySpan<byte> buffer,
JsonSerializerOptions options,
ref ReadStack state,
JsonConverter converterBase)
{
var reader = new Utf8JsonReader(buffer, isFinalBlock, readerState);
// If we haven't read in the entire stream's payload we'll need to signify that we want
// to enable read ahead behaviors to ensure we have complete json objects and arrays
// ({}, []) when needed. (Notably to successfully parse JsonElement via JsonDocument
// to assign to object and JsonElement properties in the constructed .NET object.)
state.ReadAhead = !isFinalBlock;
state.BytesConsumed = 0;
TValue? value = ReadCore<TValue>(converterBase, ref reader, options, ref state);
readerState = reader.CurrentState;
return value!;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
namespace System.Text.Json
{
public static partial class JsonSerializer
{
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
/// The Stream will be read to completion.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
/// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <param name="cancellationToken">
/// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// <typeparamref name="TValue"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <typeparamref name="TValue"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static ValueTask<TValue?> DeserializeAsync<TValue>(
Stream utf8Json!!,
JsonSerializerOptions? options = null,
CancellationToken cancellationToken = default)
{
JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue));
return ReadAllAsync<TValue>(utf8Json, jsonTypeInfo, cancellationToken);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
/// The Stream will be read to completion.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
/// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// <typeparamref name="TValue"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <typeparamref name="TValue"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static TValue? Deserialize<TValue>(
Stream utf8Json!!,
JsonSerializerOptions? options = null)
{
return ReadAllUsingOptions<TValue>(utf8Json, typeof(TValue), options);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
/// The Stream will be read to completion.
/// </summary>
/// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="returnType">The type of the object to convert to and return.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <param name="cancellationToken">
/// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// the <paramref name="returnType"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="returnType"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static ValueTask<object?> DeserializeAsync(
Stream utf8Json!!,
Type returnType!!,
JsonSerializerOptions? options = null,
CancellationToken cancellationToken = default)
{
JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
return ReadAllAsync<object?>(utf8Json, jsonTypeInfo, cancellationToken);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
/// The Stream will be read to completion.
/// </summary>
/// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="returnType">The type of the object to convert to and return.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// the <paramref name="returnType"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="returnType"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static object? Deserialize(
Stream utf8Json!!,
Type returnType!!,
JsonSerializerOptions? options = null)
{
return ReadAllUsingOptions<object>(utf8Json, returnType, options);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
/// The Stream will be read to completion.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
/// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
/// <param name="cancellationToken">
/// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// <typeparamref name="TValue"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <typeparamref name="TValue"/> or its serializable members.
/// </exception>
public static ValueTask<TValue?> DeserializeAsync<TValue>(
Stream utf8Json!!,
JsonTypeInfo<TValue> jsonTypeInfo!!,
CancellationToken cancellationToken = default)
{
return ReadAllAsync<TValue>(utf8Json, jsonTypeInfo, cancellationToken);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
/// The Stream will be read to completion.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
/// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// <typeparamref name="TValue"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <typeparamref name="TValue"/> or its serializable members.
/// </exception>
public static TValue? Deserialize<TValue>(
Stream utf8Json!!,
JsonTypeInfo<TValue> jsonTypeInfo!!)
{
return ReadAll<TValue>(utf8Json, jsonTypeInfo);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
/// The Stream will be read to completion.
/// </summary>
/// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="returnType">The type of the object to convert to and return.</param>
/// <param name="context">A metadata provider for serializable types.</param>
/// <param name="cancellationToken">
/// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// the <paramref name="returnType"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="returnType"/> or its serializable members.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
/// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
/// </exception>
public static ValueTask<object?> DeserializeAsync(
Stream utf8Json!!,
Type returnType!!,
JsonSerializerContext context!!,
CancellationToken cancellationToken = default)
{
return ReadAllAsync<object>(utf8Json, GetTypeInfo(context, returnType), cancellationToken);
}
/// <summary>
/// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
/// The Stream will be read to completion.
/// </summary>
/// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="returnType">The type of the object to convert to and return.</param>
/// <param name="context">A metadata provider for serializable types.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="JsonException">
/// The JSON is invalid,
/// the <paramref name="returnType"/> is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="returnType"/> or its serializable members.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
/// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
/// </exception>
public static object? Deserialize(
Stream utf8Json!!,
Type returnType!!,
JsonSerializerContext context!!)
{
return ReadAll<object>(utf8Json, GetTypeInfo(context, returnType));
}
/// <summary>
/// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
/// that can be used to deserialize root-level JSON arrays in a streaming manner.
/// </summary>
/// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
/// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON array.</returns>
/// <param name="utf8Json">JSON data to parse.</param>
/// <param name="options">Options to control the behavior during reading.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.</param>
/// <returns>An <typeparamref name="TValue"/> representation of the JSON value.</returns>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="utf8Json"/> is <see langword="null"/>.
/// </exception>
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
Stream utf8Json!!,
JsonSerializerOptions? options = null,
CancellationToken cancellationToken = default)
{
options ??= JsonSerializerOptions.Default;
if (!options.IsInitializedForReflectionSerializer)
{
options.InitializeForReflectionSerializer();
}
return CreateAsyncEnumerableDeserializer(utf8Json, options, cancellationToken);
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
static async IAsyncEnumerable<TValue> CreateAsyncEnumerableDeserializer(
Stream utf8Json,
JsonSerializerOptions options,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
var bufferState = new ReadBufferState(options.DefaultBufferSize);
// Hardcode the queue converter to avoid accidental use of custom converters
JsonConverter converter = QueueOfTConverter<Queue<TValue>, TValue>.Instance;
JsonTypeInfo jsonTypeInfo = CreateQueueJsonTypeInfo<TValue>(converter, options);
ReadStack readStack = default;
readStack.Initialize(jsonTypeInfo, supportContinuation: true);
var jsonReaderState = new JsonReaderState(options.GetReaderOptions());
try
{
do
{
bufferState = await ReadFromStreamAsync(utf8Json, bufferState, cancellationToken).ConfigureAwait(false);
ContinueDeserialize<Queue<TValue>>(ref bufferState, ref jsonReaderState, ref readStack, converter, options);
if (readStack.Current.ReturnValue is Queue<TValue> queue)
{
while (queue.Count > 0)
{
yield return queue.Dequeue();
}
}
}
while (!bufferState.IsFinalBlock);
}
finally
{
bufferState.Dispose();
}
}
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Workaround for https://github.com/mono/linker/issues/1416. All usages are marked as unsafe.")]
private static JsonTypeInfo CreateQueueJsonTypeInfo<TValue>(JsonConverter queueConverter, JsonSerializerOptions queueOptions) =>
new JsonTypeInfo(typeof(Queue<TValue>), queueConverter, queueOptions);
internal static async ValueTask<TValue?> ReadAllAsync<TValue>(
Stream utf8Json,
JsonTypeInfo jsonTypeInfo,
CancellationToken cancellationToken)
{
JsonSerializerOptions options = jsonTypeInfo.Options;
var bufferState = new ReadBufferState(options.DefaultBufferSize);
ReadStack readStack = default;
readStack.Initialize(jsonTypeInfo, supportContinuation: true);
JsonConverter converter = readStack.Current.JsonPropertyInfo!.ConverterBase;
var jsonReaderState = new JsonReaderState(options.GetReaderOptions());
try
{
while (true)
{
bufferState = await ReadFromStreamAsync(utf8Json, bufferState, cancellationToken).ConfigureAwait(false);
TValue value = ContinueDeserialize<TValue>(ref bufferState, ref jsonReaderState, ref readStack, converter, options);
if (bufferState.IsFinalBlock)
{
return value!;
}
}
}
finally
{
bufferState.Dispose();
}
}
internal static TValue? ReadAll<TValue>(
Stream utf8Json,
JsonTypeInfo jsonTypeInfo)
{
JsonSerializerOptions options = jsonTypeInfo.Options;
var bufferState = new ReadBufferState(options.DefaultBufferSize);
ReadStack readStack = default;
readStack.Initialize(jsonTypeInfo, supportContinuation: true);
JsonConverter converter = readStack.Current.JsonPropertyInfo!.ConverterBase;
var jsonReaderState = new JsonReaderState(options.GetReaderOptions());
try
{
while (true)
{
bufferState = ReadFromStream(utf8Json, bufferState);
TValue value = ContinueDeserialize<TValue>(ref bufferState, ref jsonReaderState, ref readStack, converter, options);
if (bufferState.IsFinalBlock)
{
return value!;
}
}
}
finally
{
bufferState.Dispose();
}
}
/// <summary>
/// Read from the stream until either our buffer is filled or we hit EOF.
/// Calling ReadCore is relatively expensive, so we minimize the number of times
/// we need to call it.
/// </summary>
internal static async ValueTask<ReadBufferState> ReadFromStreamAsync(
Stream utf8Json,
ReadBufferState bufferState,
CancellationToken cancellationToken)
{
while (true)
{
int bytesRead = await utf8Json.ReadAsync(
#if BUILDING_INBOX_LIBRARY
bufferState.Buffer.AsMemory(bufferState.BytesInBuffer),
#else
bufferState.Buffer, bufferState.BytesInBuffer, bufferState.Buffer.Length - bufferState.BytesInBuffer,
#endif
cancellationToken).ConfigureAwait(false);
if (bytesRead == 0)
{
bufferState.IsFinalBlock = true;
break;
}
bufferState.BytesInBuffer += bytesRead;
if (bufferState.BytesInBuffer == bufferState.Buffer.Length)
{
break;
}
}
return bufferState;
}
/// <summary>
/// Read from the stream until either our buffer is filled or we hit EOF.
/// Calling ReadCore is relatively expensive, so we minimize the number of times
/// we need to call it.
/// </summary>
internal static ReadBufferState ReadFromStream(
Stream utf8Json,
ReadBufferState bufferState)
{
while (true)
{
int bytesRead = utf8Json.Read(
#if BUILDING_INBOX_LIBRARY
bufferState.Buffer.AsSpan(bufferState.BytesInBuffer));
#else
bufferState.Buffer, bufferState.BytesInBuffer, bufferState.Buffer.Length - bufferState.BytesInBuffer);
#endif
if (bytesRead == 0)
{
bufferState.IsFinalBlock = true;
break;
}
bufferState.BytesInBuffer += bytesRead;
if (bufferState.BytesInBuffer == bufferState.Buffer.Length)
{
break;
}
}
return bufferState;
}
internal static TValue ContinueDeserialize<TValue>(
ref ReadBufferState bufferState,
ref JsonReaderState jsonReaderState,
ref ReadStack readStack,
JsonConverter converter,
JsonSerializerOptions options)
{
if (bufferState.BytesInBuffer > bufferState.ClearMax)
{
bufferState.ClearMax = bufferState.BytesInBuffer;
}
int start = 0;
if (bufferState.IsFirstIteration)
{
bufferState.IsFirstIteration = false;
// Handle the UTF-8 BOM if present
Debug.Assert(bufferState.Buffer.Length >= JsonConstants.Utf8Bom.Length);
if (bufferState.Buffer.AsSpan().StartsWith(JsonConstants.Utf8Bom))
{
start += JsonConstants.Utf8Bom.Length;
bufferState.BytesInBuffer -= JsonConstants.Utf8Bom.Length;
}
}
// Process the data available
TValue value = ReadCore<TValue>(
ref jsonReaderState,
bufferState.IsFinalBlock,
new ReadOnlySpan<byte>(bufferState.Buffer, start, bufferState.BytesInBuffer),
options,
ref readStack,
converter);
Debug.Assert(readStack.BytesConsumed <= bufferState.BytesInBuffer);
int bytesConsumed = checked((int)readStack.BytesConsumed);
bufferState.BytesInBuffer -= bytesConsumed;
// The reader should have thrown if we have remaining bytes.
Debug.Assert(!bufferState.IsFinalBlock || bufferState.BytesInBuffer == 0);
if (!bufferState.IsFinalBlock)
{
// Check if we need to shift or expand the buffer because there wasn't enough data to complete deserialization.
if ((uint)bufferState.BytesInBuffer > ((uint)bufferState.Buffer.Length / 2))
{
// We have less than half the buffer available, double the buffer size.
byte[] oldBuffer = bufferState.Buffer;
int oldClearMax = bufferState.ClearMax;
byte[] newBuffer = ArrayPool<byte>.Shared.Rent((bufferState.Buffer.Length < (int.MaxValue / 2)) ? bufferState.Buffer.Length * 2 : int.MaxValue);
// Copy the unprocessed data to the new buffer while shifting the processed bytes.
Buffer.BlockCopy(oldBuffer, bytesConsumed + start, newBuffer, 0, bufferState.BytesInBuffer);
bufferState.Buffer = newBuffer;
bufferState.ClearMax = bufferState.BytesInBuffer;
// Clear and return the old buffer
new Span<byte>(oldBuffer, 0, oldClearMax).Clear();
ArrayPool<byte>.Shared.Return(oldBuffer);
}
else if (bufferState.BytesInBuffer != 0)
{
// Shift the processed bytes to the beginning of buffer to make more room.
Buffer.BlockCopy(bufferState.Buffer, bytesConsumed + start, bufferState.Buffer, 0, bufferState.BytesInBuffer);
}
}
return value;
}
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
private static TValue? ReadAllUsingOptions<TValue>(
Stream utf8Json,
Type returnType,
JsonSerializerOptions? options)
{
JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
return ReadAll<TValue>(utf8Json, jsonTypeInfo);
}
private static TValue ReadCore<TValue>(
ref JsonReaderState readerState,
bool isFinalBlock,
ReadOnlySpan<byte> buffer,
JsonSerializerOptions options,
ref ReadStack state,
JsonConverter converterBase)
{
var reader = new Utf8JsonReader(buffer, isFinalBlock, readerState);
// If we haven't read in the entire stream's payload we'll need to signify that we want
// to enable read ahead behaviors to ensure we have complete json objects and arrays
// ({}, []) when needed. (Notably to successfully parse JsonElement via JsonDocument
// to assign to object and JsonElement properties in the constructed .NET object.)
state.ReadAhead = !isFinalBlock;
state.BytesConsumed = 0;
TValue? value = ReadCore<TValue>(converterBase, ref reader, options, ref state);
readerState = reader.CurrentState;
return value!;
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Helpers.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.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
public static partial class JsonSerializer
{
private static bool WriteCore<TValue>(
JsonConverter jsonConverter,
Utf8JsonWriter writer,
in TValue value,
JsonSerializerOptions options,
ref WriteStack state)
{
Debug.Assert(writer != null);
bool success;
if (jsonConverter is JsonConverter<TValue> converter)
{
// Call the strongly-typed WriteCore that will not box structs.
success = converter.WriteCore(writer, value, options, ref state);
}
else
{
// The non-generic API was called or we have a polymorphic case where TValue is not equal to the T in JsonConverter<T>.
success = jsonConverter.WriteCoreAsObject(writer, value, options, ref state);
}
writer.Flush();
return success;
}
private static void WriteUsingGeneratedSerializer<TValue>(Utf8JsonWriter writer, in TValue value, JsonTypeInfo jsonTypeInfo)
{
Debug.Assert(writer != null);
if (jsonTypeInfo.HasSerialize &&
jsonTypeInfo is JsonTypeInfo<TValue> typedInfo &&
typedInfo.Options._serializerContext?.CanUseSerializationLogic == true)
{
Debug.Assert(typedInfo.SerializeHandler != null);
typedInfo.SerializeHandler(writer, value);
writer.Flush();
}
else
{
WriteUsingSerializer(writer, value, jsonTypeInfo);
}
}
private static void WriteUsingSerializer<TValue>(Utf8JsonWriter writer, in TValue value, JsonTypeInfo jsonTypeInfo)
{
Debug.Assert(writer != null);
Debug.Assert(!jsonTypeInfo.HasSerialize ||
jsonTypeInfo is not JsonTypeInfo<TValue> ||
jsonTypeInfo.Options._serializerContext == null ||
!jsonTypeInfo.Options._serializerContext.CanUseSerializationLogic,
"Incorrect method called. WriteUsingGeneratedSerializer() should have been called instead.");
WriteStack state = default;
state.Initialize(jsonTypeInfo, supportContinuation: false);
JsonConverter converter = jsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase;
Debug.Assert(converter != null);
Debug.Assert(jsonTypeInfo.Options != null);
// For performance, the code below is a lifted WriteCore() above.
if (converter is JsonConverter<TValue> typedConverter)
{
// Call the strongly-typed WriteCore that will not box structs.
typedConverter.WriteCore(writer, value, jsonTypeInfo.Options, ref state);
}
else
{
// The non-generic API was called or we have a polymorphic case where TValue is not equal to the T in JsonConverter<T>.
converter.WriteCoreAsObject(writer, value, jsonTypeInfo.Options, ref state);
}
writer.Flush();
}
private static Type GetRuntimeType<TValue>(in TValue value)
{
Type type = typeof(TValue);
if (type == JsonTypeInfo.ObjectType && value is not null)
{
type = value.GetType();
}
return type;
}
private static Type GetRuntimeTypeAndValidateInputType(object? value, Type inputType!!)
{
if (value is not null)
{
Type runtimeType = value.GetType();
if (!inputType.IsAssignableFrom(runtimeType))
{
ThrowHelper.ThrowArgumentException_DeserializeWrongType(inputType, value);
}
if (inputType == JsonTypeInfo.ObjectType)
{
return runtimeType;
}
}
return inputType;
}
}
}
| // 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.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
public static partial class JsonSerializer
{
private static bool WriteCore<TValue>(
JsonConverter jsonConverter,
Utf8JsonWriter writer,
in TValue value,
JsonSerializerOptions options,
ref WriteStack state)
{
Debug.Assert(writer != null);
bool success;
if (jsonConverter is JsonConverter<TValue> converter)
{
// Call the strongly-typed WriteCore that will not box structs.
success = converter.WriteCore(writer, value, options, ref state);
}
else
{
// The non-generic API was called or we have a polymorphic case where TValue is not equal to the T in JsonConverter<T>.
success = jsonConverter.WriteCoreAsObject(writer, value, options, ref state);
}
writer.Flush();
return success;
}
private static void WriteUsingGeneratedSerializer<TValue>(Utf8JsonWriter writer, in TValue value, JsonTypeInfo jsonTypeInfo)
{
Debug.Assert(writer != null);
if (jsonTypeInfo.HasSerialize &&
jsonTypeInfo is JsonTypeInfo<TValue> typedInfo &&
typedInfo.Options.JsonSerializerContext?.CanUseSerializationLogic == true)
{
Debug.Assert(typedInfo.SerializeHandler != null);
typedInfo.SerializeHandler(writer, value);
writer.Flush();
}
else
{
WriteUsingSerializer(writer, value, jsonTypeInfo);
}
}
private static void WriteUsingSerializer<TValue>(Utf8JsonWriter writer, in TValue value, JsonTypeInfo jsonTypeInfo)
{
Debug.Assert(writer != null);
Debug.Assert(!jsonTypeInfo.HasSerialize ||
jsonTypeInfo is not JsonTypeInfo<TValue> ||
jsonTypeInfo.Options.JsonSerializerContext == null ||
!jsonTypeInfo.Options.JsonSerializerContext.CanUseSerializationLogic,
"Incorrect method called. WriteUsingGeneratedSerializer() should have been called instead.");
WriteStack state = default;
state.Initialize(jsonTypeInfo, supportContinuation: false);
JsonConverter converter = jsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase;
Debug.Assert(converter != null);
Debug.Assert(jsonTypeInfo.Options != null);
// For performance, the code below is a lifted WriteCore() above.
if (converter is JsonConverter<TValue> typedConverter)
{
// Call the strongly-typed WriteCore that will not box structs.
typedConverter.WriteCore(writer, value, jsonTypeInfo.Options, ref state);
}
else
{
// The non-generic API was called or we have a polymorphic case where TValue is not equal to the T in JsonConverter<T>.
converter.WriteCoreAsObject(writer, value, jsonTypeInfo.Options, ref state);
}
writer.Flush();
}
private static Type GetRuntimeType<TValue>(in TValue value)
{
Type type = typeof(TValue);
if (type == JsonTypeInfo.ObjectType && value is not null)
{
type = value.GetType();
}
return type;
}
private static Type GetRuntimeTypeAndValidateInputType(object? value, Type inputType!!)
{
if (value is not null)
{
Type runtimeType = value.GetType();
if (!inputType.IsAssignableFrom(runtimeType))
{
ThrowHelper.ThrowArgumentException_DeserializeWrongType(inputType, value);
}
if (inputType == JsonTypeInfo.ObjectType)
{
return runtimeType;
}
}
return inputType;
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json.Serialization
{
/// <summary>
/// Provides metadata about a set of types that is relevant to JSON serialization.
/// </summary>
public abstract partial class JsonSerializerContext
{
private bool? _canUseSerializationLogic;
internal JsonSerializerOptions? _options;
/// <summary>
/// Gets the run time specified options of the context. If no options were passed
/// when instanciating the context, then a new instance is bound and returned.
/// </summary>
/// <remarks>
/// The instance cannot be mutated once it is bound with the context instance.
/// </remarks>
public JsonSerializerOptions Options
{
get
{
if (_options == null)
{
_options = new JsonSerializerOptions();
_options._serializerContext = this;
}
return _options;
}
}
/// <summary>
/// Indicates whether pre-generated serialization logic for types in the context
/// is compatible with the run time specified <see cref="JsonSerializerOptions"/>.
/// </summary>
internal bool CanUseSerializationLogic
{
get
{
if (!_canUseSerializationLogic.HasValue)
{
if (GeneratedSerializerOptions == null)
{
_canUseSerializationLogic = false;
}
else
{
_canUseSerializationLogic =
// Guard against unsupported features
Options.Converters.Count == 0 &&
Options.Encoder == null &&
// Disallow custom number handling we'd need to honor when writing.
// AllowReadingFromString and Strict are fine since there's no action to take when writing.
(Options.NumberHandling & (JsonNumberHandling.WriteAsString | JsonNumberHandling.AllowNamedFloatingPointLiterals)) == 0 &&
Options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.None &&
#pragma warning disable SYSLIB0020
!Options.IgnoreNullValues && // This property is obsolete.
#pragma warning restore SYSLIB0020
// Ensure options values are consistent with expected defaults.
Options.DefaultIgnoreCondition == GeneratedSerializerOptions.DefaultIgnoreCondition &&
Options.IgnoreReadOnlyFields == GeneratedSerializerOptions.IgnoreReadOnlyFields &&
Options.IgnoreReadOnlyProperties == GeneratedSerializerOptions.IgnoreReadOnlyProperties &&
Options.IncludeFields == GeneratedSerializerOptions.IncludeFields &&
Options.PropertyNamingPolicy == GeneratedSerializerOptions.PropertyNamingPolicy &&
Options.DictionaryKeyPolicy == GeneratedSerializerOptions.DictionaryKeyPolicy &&
Options.WriteIndented == GeneratedSerializerOptions.WriteIndented;
}
}
return _canUseSerializationLogic.Value;
}
}
/// <summary>
/// The default run time options for the context. Its values are defined at design-time via <see cref="JsonSourceGenerationOptionsAttribute"/>.
/// </summary>
protected abstract JsonSerializerOptions? GeneratedSerializerOptions { get; }
/// <summary>
/// Creates an instance of <see cref="JsonSerializerContext"/> and binds it with the indicated <see cref="JsonSerializerOptions"/>.
/// </summary>
/// <param name="options">The run time provided options for the context instance.</param>
/// <remarks>
/// If no instance options are passed, then no options are set until the context is bound using <see cref="JsonSerializerOptions.AddContext{TContext}"/>,
/// or until <see cref="Options"/> is called, where a new options instance is created and bound.
/// </remarks>
protected JsonSerializerContext(JsonSerializerOptions? options)
{
if (options != null)
{
if (options._serializerContext != null)
{
ThrowHelper.ThrowInvalidOperationException_JsonSerializerOptionsAlreadyBoundToContext();
}
_options = options;
options._serializerContext = this;
}
}
/// <summary>
/// Returns a <see cref="JsonTypeInfo"/> instance representing the given type.
/// </summary>
/// <param name="type">The type to fetch metadata about.</param>
/// <returns>The metadata for the specified type, or <see langword="null" /> if the context has no metadata for the type.</returns>
public abstract JsonTypeInfo? GetTypeInfo(Type type);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json.Serialization
{
/// <summary>
/// Provides metadata about a set of types that is relevant to JSON serialization.
/// </summary>
public abstract partial class JsonSerializerContext
{
private bool? _canUseSerializationLogic;
internal JsonSerializerOptions? _options;
/// <summary>
/// Gets the run time specified options of the context. If no options were passed
/// when instanciating the context, then a new instance is bound and returned.
/// </summary>
/// <remarks>
/// The instance cannot be mutated once it is bound with the context instance.
/// </remarks>
public JsonSerializerOptions Options => _options ??= new JsonSerializerOptions { JsonSerializerContext = this };
/// <summary>
/// Indicates whether pre-generated serialization logic for types in the context
/// is compatible with the run time specified <see cref="JsonSerializerOptions"/>.
/// </summary>
internal bool CanUseSerializationLogic
{
get
{
if (!_canUseSerializationLogic.HasValue)
{
if (GeneratedSerializerOptions == null)
{
_canUseSerializationLogic = false;
}
else
{
_canUseSerializationLogic =
// Guard against unsupported features
Options.Converters.Count == 0 &&
Options.Encoder == null &&
// Disallow custom number handling we'd need to honor when writing.
// AllowReadingFromString and Strict are fine since there's no action to take when writing.
(Options.NumberHandling & (JsonNumberHandling.WriteAsString | JsonNumberHandling.AllowNamedFloatingPointLiterals)) == 0 &&
Options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.None &&
#pragma warning disable SYSLIB0020
!Options.IgnoreNullValues && // This property is obsolete.
#pragma warning restore SYSLIB0020
// Ensure options values are consistent with expected defaults.
Options.DefaultIgnoreCondition == GeneratedSerializerOptions.DefaultIgnoreCondition &&
Options.IgnoreReadOnlyFields == GeneratedSerializerOptions.IgnoreReadOnlyFields &&
Options.IgnoreReadOnlyProperties == GeneratedSerializerOptions.IgnoreReadOnlyProperties &&
Options.IncludeFields == GeneratedSerializerOptions.IncludeFields &&
Options.PropertyNamingPolicy == GeneratedSerializerOptions.PropertyNamingPolicy &&
Options.DictionaryKeyPolicy == GeneratedSerializerOptions.DictionaryKeyPolicy &&
Options.WriteIndented == GeneratedSerializerOptions.WriteIndented;
}
}
return _canUseSerializationLogic.Value;
}
}
/// <summary>
/// The default run time options for the context. Its values are defined at design-time via <see cref="JsonSourceGenerationOptionsAttribute"/>.
/// </summary>
protected abstract JsonSerializerOptions? GeneratedSerializerOptions { get; }
/// <summary>
/// Creates an instance of <see cref="JsonSerializerContext"/> and binds it with the indicated <see cref="JsonSerializerOptions"/>.
/// </summary>
/// <param name="options">The run time provided options for the context instance.</param>
/// <remarks>
/// If no instance options are passed, then no options are set until the context is bound using <see cref="JsonSerializerOptions.AddContext{TContext}"/>,
/// or until <see cref="Options"/> is called, where a new options instance is created and bound.
/// </remarks>
protected JsonSerializerContext(JsonSerializerOptions? options)
{
if (options != null)
{
options.JsonSerializerContext = this;
_options = options;
}
}
/// <summary>
/// Returns a <see cref="JsonTypeInfo"/> instance representing the given type.
/// </summary>
/// <param name="type">The type to fetch metadata about.</param>
/// <returns>The metadata for the specified type, or <see langword="null" /> if the context has no metadata for the type.</returns>
public abstract JsonTypeInfo? GetTypeInfo(Type type);
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
namespace System.Text.Json
{
public sealed partial class JsonSerializerOptions
{
/// <summary>
/// Encapsulates all cached metadata referenced by the current <see cref="JsonSerializerOptions" /> instance.
/// Context can be shared across multiple equivalent options instances.
/// </summary>
private CachingContext? _cachingContext;
// Simple LRU cache for the public (de)serialize entry points that avoid some lookups in _cachingContext.
private volatile JsonTypeInfo? _lastTypeInfo;
internal JsonTypeInfo GetOrAddJsonTypeInfo(Type type)
{
if (_cachingContext == null)
{
InitializeCachingContext();
Debug.Assert(_cachingContext != null);
}
return _cachingContext.GetOrAddJsonTypeInfo(type);
}
internal bool TryGetJsonTypeInfo(Type type, [NotNullWhen(true)] out JsonTypeInfo? typeInfo)
{
if (_cachingContext == null)
{
typeInfo = null;
return false;
}
return _cachingContext.TryGetJsonTypeInfo(type, out typeInfo);
}
internal bool IsJsonTypeInfoCached(Type type) => _cachingContext?.IsJsonTypeInfoCached(type) == true;
/// <summary>
/// Return the TypeInfo for root API calls.
/// This has an LRU cache that is intended only for public API calls that specify the root type.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal JsonTypeInfo GetOrAddJsonTypeInfoForRootType(Type type)
{
JsonTypeInfo? jsonTypeInfo = _lastTypeInfo;
if (jsonTypeInfo?.Type != type)
{
jsonTypeInfo = GetOrAddJsonTypeInfo(type);
_lastTypeInfo = jsonTypeInfo;
}
return jsonTypeInfo;
}
internal void ClearCaches()
{
_cachingContext?.Clear();
_lastTypeInfo = null;
}
private void InitializeCachingContext()
{
_cachingContext = TrackedCachingContexts.GetOrCreate(this);
}
/// <summary>
/// Stores and manages all reflection caches for one or more <see cref="JsonSerializerOptions"/> instances.
/// NB the type encapsulates the original options instance and only consults that one when building new types;
/// this is to prevent multiple options instances from leaking into the object graphs of converters which
/// could break user invariants.
/// </summary>
internal sealed class CachingContext
{
private readonly ConcurrentDictionary<Type, JsonConverter> _converterCache = new();
private readonly ConcurrentDictionary<Type, JsonTypeInfo> _jsonTypeInfoCache = new();
public CachingContext(JsonSerializerOptions options)
{
Options = options;
}
public JsonSerializerOptions Options { get; }
// Property only accessed by reflection in testing -- do not remove.
// If changing please ensure that src/ILLink.Descriptors.LibraryBuild.xml is up-to-date.
public int Count => _converterCache.Count + _jsonTypeInfoCache.Count;
public JsonConverter GetOrAddConverter(Type type) => _converterCache.GetOrAdd(type, Options.GetConverterFromType);
public JsonTypeInfo GetOrAddJsonTypeInfo(Type type) => _jsonTypeInfoCache.GetOrAdd(type, Options.GetJsonTypeInfoFromContextOrCreate);
public bool TryGetJsonTypeInfo(Type type, [NotNullWhen(true)] out JsonTypeInfo? typeInfo) => _jsonTypeInfoCache.TryGetValue(type, out typeInfo);
public bool IsJsonTypeInfoCached(Type type) => _jsonTypeInfoCache.ContainsKey(type);
public void Clear()
{
_converterCache.Clear();
_jsonTypeInfoCache.Clear();
}
}
/// <summary>
/// Defines a cache of CachingContexts; instead of using a ConditionalWeakTable which can be slow to traverse
/// this approach uses a concurrent dictionary pointing to weak references of <see cref="CachingContext"/>.
/// Relevant caching contexts are looked up using the equality comparison defined by <see cref="EqualityComparer"/>.
/// </summary>
internal static class TrackedCachingContexts
{
private const int MaxTrackedContexts = 64;
private static readonly ConcurrentDictionary<JsonSerializerOptions, WeakReference<CachingContext>> s_cache =
new(concurrencyLevel: 1, capacity: MaxTrackedContexts, new EqualityComparer());
private const int EvictionCountHistory = 16;
private static Queue<int> s_recentEvictionCounts = new(EvictionCountHistory);
private static int s_evictionRunsToSkip;
public static CachingContext GetOrCreate(JsonSerializerOptions options)
{
ConcurrentDictionary<JsonSerializerOptions, WeakReference<CachingContext>> cache = s_cache;
if (cache.TryGetValue(options, out WeakReference<CachingContext>? wr) && wr.TryGetTarget(out CachingContext? ctx))
{
return ctx;
}
lock (cache)
{
if (cache.TryGetValue(options, out wr))
{
if (!wr.TryGetTarget(out ctx))
{
// Found a dangling weak reference; replenish with a fresh instance.
ctx = new CachingContext(options);
wr.SetTarget(ctx);
}
return ctx;
}
if (cache.Count == MaxTrackedContexts)
{
if (!TryEvictDanglingEntries())
{
// Cache is full; return a fresh instance.
return new CachingContext(options);
}
}
Debug.Assert(cache.Count < MaxTrackedContexts);
// Use a defensive copy of the options instance as key to
// avoid capturing references to any caching contexts.
var key = new JsonSerializerOptions(options) { _serializerContext = options._serializerContext };
Debug.Assert(key._cachingContext == null);
ctx = new CachingContext(options);
bool success = cache.TryAdd(key, new(ctx));
Debug.Assert(success);
return ctx;
}
}
public static void Clear()
{
lock (s_cache)
{
s_cache.Clear();
s_recentEvictionCounts.Clear();
s_evictionRunsToSkip = 0;
}
}
private static bool TryEvictDanglingEntries()
{
// Worst case scenario, the cache has been filled with permanent entries.
// Evictions are synchronized and each run is in the order of microseconds,
// so we want to avoid triggering runs every time an instance is initialized,
// For this reason we use a backoff strategy to average out the cost of eviction
// across multiple initializations. The backoff count is determined by the eviction
// rates of the most recent runs.
Debug.Assert(Monitor.IsEntered(s_cache));
if (s_evictionRunsToSkip > 0)
{
--s_evictionRunsToSkip;
return false;
}
int currentEvictions = 0;
foreach (KeyValuePair<JsonSerializerOptions, WeakReference<CachingContext>> kvp in s_cache)
{
if (!kvp.Value.TryGetTarget(out _))
{
bool result = s_cache.TryRemove(kvp.Key, out _);
Debug.Assert(result);
currentEvictions++;
}
}
s_evictionRunsToSkip = EstimateEvictionRunsToSkip(currentEvictions);
return currentEvictions > 0;
// Estimate the number of eviction runs to skip based on recent eviction rates.
static int EstimateEvictionRunsToSkip(int latestEvictionCount)
{
Queue<int> recentEvictionCounts = s_recentEvictionCounts;
if (recentEvictionCounts.Count < EvictionCountHistory - 1)
{
// Insufficient data points to determine a skip count.
recentEvictionCounts.Enqueue(latestEvictionCount);
return 0;
}
else if (recentEvictionCounts.Count == EvictionCountHistory)
{
recentEvictionCounts.Dequeue();
}
recentEvictionCounts.Enqueue(latestEvictionCount);
// Calculate the total number of eviction in the latest runs
// - If we have at least one eviction per run, on average,
// do not skip any future eviction runs.
// - Otherwise, skip ~the number of runs needed per one eviction.
int totalEvictions = 0;
foreach (int evictionCount in recentEvictionCounts)
{
totalEvictions += evictionCount;
}
int evictionRunsToSkip =
totalEvictions >= EvictionCountHistory ? 0 :
(int)Math.Round((double)EvictionCountHistory / Math.Max(totalEvictions, 1));
Debug.Assert(0 <= evictionRunsToSkip && evictionRunsToSkip <= EvictionCountHistory);
return evictionRunsToSkip;
}
}
}
/// <summary>
/// Provides a conservative equality comparison for JsonSerializerOptions instances.
/// If two instances are equivalent, they should generate identical metadata caches;
/// the converse however does not necessarily hold.
/// </summary>
private sealed class EqualityComparer : IEqualityComparer<JsonSerializerOptions>
{
public bool Equals(JsonSerializerOptions? left, JsonSerializerOptions? right)
{
Debug.Assert(left != null && right != null);
return
left._dictionaryKeyPolicy == right._dictionaryKeyPolicy &&
left._jsonPropertyNamingPolicy == right._jsonPropertyNamingPolicy &&
left._readCommentHandling == right._readCommentHandling &&
left._referenceHandler == right._referenceHandler &&
left._encoder == right._encoder &&
left._defaultIgnoreCondition == right._defaultIgnoreCondition &&
left._numberHandling == right._numberHandling &&
left._unknownTypeHandling == right._unknownTypeHandling &&
left._defaultBufferSize == right._defaultBufferSize &&
left._maxDepth == right._maxDepth &&
left._allowTrailingCommas == right._allowTrailingCommas &&
left._ignoreNullValues == right._ignoreNullValues &&
left._ignoreReadOnlyProperties == right._ignoreReadOnlyProperties &&
left._ignoreReadonlyFields == right._ignoreReadonlyFields &&
left._includeFields == right._includeFields &&
left._propertyNameCaseInsensitive == right._propertyNameCaseInsensitive &&
left._writeIndented == right._writeIndented &&
left._serializerContext == right._serializerContext &&
CompareConverters(left._converters, right._converters);
static bool CompareConverters(ConverterList left, ConverterList right)
{
int n;
if ((n = left.Count) != right.Count)
{
return false;
}
for (int i = 0; i < n; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
}
public int GetHashCode(JsonSerializerOptions options)
{
HashCode hc = default;
hc.Add(options._dictionaryKeyPolicy);
hc.Add(options._jsonPropertyNamingPolicy);
hc.Add(options._readCommentHandling);
hc.Add(options._referenceHandler);
hc.Add(options._encoder);
hc.Add(options._defaultIgnoreCondition);
hc.Add(options._numberHandling);
hc.Add(options._unknownTypeHandling);
hc.Add(options._defaultBufferSize);
hc.Add(options._maxDepth);
hc.Add(options._allowTrailingCommas);
hc.Add(options._ignoreNullValues);
hc.Add(options._ignoreReadOnlyProperties);
hc.Add(options._ignoreReadonlyFields);
hc.Add(options._includeFields);
hc.Add(options._propertyNameCaseInsensitive);
hc.Add(options._writeIndented);
hc.Add(options._serializerContext);
for (int i = 0; i < options._converters.Count; i++)
{
hc.Add(options._converters[i]);
}
return hc.ToHashCode();
}
#if !NETCOREAPP
/// <summary>
/// Polyfill for System.HashCode.
/// </summary>
private struct HashCode
{
private int _hashCode;
public void Add<T>(T? value) => _hashCode = (_hashCode, value).GetHashCode();
public int ToHashCode() => _hashCode;
}
#endif
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
namespace System.Text.Json
{
public sealed partial class JsonSerializerOptions
{
/// <summary>
/// Encapsulates all cached metadata referenced by the current <see cref="JsonSerializerOptions" /> instance.
/// Context can be shared across multiple equivalent options instances.
/// </summary>
private CachingContext? _cachingContext;
// Simple LRU cache for the public (de)serialize entry points that avoid some lookups in _cachingContext.
private volatile JsonTypeInfo? _lastTypeInfo;
internal JsonTypeInfo GetOrAddJsonTypeInfo(Type type)
{
if (_cachingContext == null)
{
InitializeCachingContext();
Debug.Assert(_cachingContext != null);
}
return _cachingContext.GetOrAddJsonTypeInfo(type);
}
internal bool TryGetJsonTypeInfo(Type type, [NotNullWhen(true)] out JsonTypeInfo? typeInfo)
{
if (_cachingContext == null)
{
typeInfo = null;
return false;
}
return _cachingContext.TryGetJsonTypeInfo(type, out typeInfo);
}
internal bool IsJsonTypeInfoCached(Type type) => _cachingContext?.IsJsonTypeInfoCached(type) == true;
/// <summary>
/// Return the TypeInfo for root API calls.
/// This has an LRU cache that is intended only for public API calls that specify the root type.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal JsonTypeInfo GetOrAddJsonTypeInfoForRootType(Type type)
{
JsonTypeInfo? jsonTypeInfo = _lastTypeInfo;
if (jsonTypeInfo?.Type != type)
{
jsonTypeInfo = GetOrAddJsonTypeInfo(type);
_lastTypeInfo = jsonTypeInfo;
}
return jsonTypeInfo;
}
internal void ClearCaches()
{
_cachingContext?.Clear();
_lastTypeInfo = null;
}
private void InitializeCachingContext()
{
_cachingContext = TrackedCachingContexts.GetOrCreate(this);
if (IsInitializedForReflectionSerializer)
{
_cachingContext.Options.IsInitializedForReflectionSerializer = true;
}
}
/// <summary>
/// Stores and manages all reflection caches for one or more <see cref="JsonSerializerOptions"/> instances.
/// NB the type encapsulates the original options instance and only consults that one when building new types;
/// this is to prevent multiple options instances from leaking into the object graphs of converters which
/// could break user invariants.
/// </summary>
internal sealed class CachingContext
{
private readonly ConcurrentDictionary<Type, JsonConverter> _converterCache = new();
private readonly ConcurrentDictionary<Type, JsonTypeInfo> _jsonTypeInfoCache = new();
public CachingContext(JsonSerializerOptions options)
{
Options = options;
}
public JsonSerializerOptions Options { get; }
// Property only accessed by reflection in testing -- do not remove.
// If changing please ensure that src/ILLink.Descriptors.LibraryBuild.xml is up-to-date.
public int Count => _converterCache.Count + _jsonTypeInfoCache.Count;
public JsonConverter GetOrAddConverter(Type type) => _converterCache.GetOrAdd(type, Options.GetConverterFromType);
public JsonTypeInfo GetOrAddJsonTypeInfo(Type type) => _jsonTypeInfoCache.GetOrAdd(type, Options.GetJsonTypeInfoFromContextOrCreate);
public bool TryGetJsonTypeInfo(Type type, [NotNullWhen(true)] out JsonTypeInfo? typeInfo) => _jsonTypeInfoCache.TryGetValue(type, out typeInfo);
public bool IsJsonTypeInfoCached(Type type) => _jsonTypeInfoCache.ContainsKey(type);
public void Clear()
{
_converterCache.Clear();
_jsonTypeInfoCache.Clear();
}
}
/// <summary>
/// Defines a cache of CachingContexts; instead of using a ConditionalWeakTable which can be slow to traverse
/// this approach uses a concurrent dictionary pointing to weak references of <see cref="CachingContext"/>.
/// Relevant caching contexts are looked up using the equality comparison defined by <see cref="EqualityComparer"/>.
/// </summary>
internal static class TrackedCachingContexts
{
private const int MaxTrackedContexts = 64;
private static readonly ConcurrentDictionary<JsonSerializerOptions, WeakReference<CachingContext>> s_cache =
new(concurrencyLevel: 1, capacity: MaxTrackedContexts, new EqualityComparer());
private const int EvictionCountHistory = 16;
private static Queue<int> s_recentEvictionCounts = new(EvictionCountHistory);
private static int s_evictionRunsToSkip;
public static CachingContext GetOrCreate(JsonSerializerOptions options)
{
ConcurrentDictionary<JsonSerializerOptions, WeakReference<CachingContext>> cache = s_cache;
if (cache.TryGetValue(options, out WeakReference<CachingContext>? wr) && wr.TryGetTarget(out CachingContext? ctx))
{
return ctx;
}
lock (cache)
{
if (cache.TryGetValue(options, out wr))
{
if (!wr.TryGetTarget(out ctx))
{
// Found a dangling weak reference; replenish with a fresh instance.
ctx = new CachingContext(options);
wr.SetTarget(ctx);
}
return ctx;
}
if (cache.Count == MaxTrackedContexts)
{
if (!TryEvictDanglingEntries())
{
// Cache is full; return a fresh instance.
return new CachingContext(options);
}
}
Debug.Assert(cache.Count < MaxTrackedContexts);
// Use a defensive copy of the options instance as key to
// avoid capturing references to any caching contexts.
var key = new JsonSerializerOptions(options)
{
// Copy fields ignored by the copy constructor
// but are necessary to determine equivalence.
_serializerContext = options._serializerContext,
};
Debug.Assert(key._cachingContext == null);
ctx = new CachingContext(options);
bool success = cache.TryAdd(key, new(ctx));
Debug.Assert(success);
return ctx;
}
}
public static void Clear()
{
lock (s_cache)
{
s_cache.Clear();
s_recentEvictionCounts.Clear();
s_evictionRunsToSkip = 0;
}
}
private static bool TryEvictDanglingEntries()
{
// Worst case scenario, the cache has been filled with permanent entries.
// Evictions are synchronized and each run is in the order of microseconds,
// so we want to avoid triggering runs every time an instance is initialized,
// For this reason we use a backoff strategy to average out the cost of eviction
// across multiple initializations. The backoff count is determined by the eviction
// rates of the most recent runs.
Debug.Assert(Monitor.IsEntered(s_cache));
if (s_evictionRunsToSkip > 0)
{
--s_evictionRunsToSkip;
return false;
}
int currentEvictions = 0;
foreach (KeyValuePair<JsonSerializerOptions, WeakReference<CachingContext>> kvp in s_cache)
{
if (!kvp.Value.TryGetTarget(out _))
{
bool result = s_cache.TryRemove(kvp.Key, out _);
Debug.Assert(result);
currentEvictions++;
}
}
s_evictionRunsToSkip = EstimateEvictionRunsToSkip(currentEvictions);
return currentEvictions > 0;
// Estimate the number of eviction runs to skip based on recent eviction rates.
static int EstimateEvictionRunsToSkip(int latestEvictionCount)
{
Queue<int> recentEvictionCounts = s_recentEvictionCounts;
if (recentEvictionCounts.Count < EvictionCountHistory - 1)
{
// Insufficient data points to determine a skip count.
recentEvictionCounts.Enqueue(latestEvictionCount);
return 0;
}
else if (recentEvictionCounts.Count == EvictionCountHistory)
{
recentEvictionCounts.Dequeue();
}
recentEvictionCounts.Enqueue(latestEvictionCount);
// Calculate the total number of eviction in the latest runs
// - If we have at least one eviction per run, on average,
// do not skip any future eviction runs.
// - Otherwise, skip ~the number of runs needed per one eviction.
int totalEvictions = 0;
foreach (int evictionCount in recentEvictionCounts)
{
totalEvictions += evictionCount;
}
int evictionRunsToSkip =
totalEvictions >= EvictionCountHistory ? 0 :
(int)Math.Round((double)EvictionCountHistory / Math.Max(totalEvictions, 1));
Debug.Assert(0 <= evictionRunsToSkip && evictionRunsToSkip <= EvictionCountHistory);
return evictionRunsToSkip;
}
}
}
/// <summary>
/// Provides a conservative equality comparison for JsonSerializerOptions instances.
/// If two instances are equivalent, they should generate identical metadata caches;
/// the converse however does not necessarily hold.
/// </summary>
private sealed class EqualityComparer : IEqualityComparer<JsonSerializerOptions>
{
public bool Equals(JsonSerializerOptions? left, JsonSerializerOptions? right)
{
Debug.Assert(left != null && right != null);
return
left._dictionaryKeyPolicy == right._dictionaryKeyPolicy &&
left._jsonPropertyNamingPolicy == right._jsonPropertyNamingPolicy &&
left._readCommentHandling == right._readCommentHandling &&
left._referenceHandler == right._referenceHandler &&
left._encoder == right._encoder &&
left._defaultIgnoreCondition == right._defaultIgnoreCondition &&
left._numberHandling == right._numberHandling &&
left._unknownTypeHandling == right._unknownTypeHandling &&
left._defaultBufferSize == right._defaultBufferSize &&
left._maxDepth == right._maxDepth &&
left._allowTrailingCommas == right._allowTrailingCommas &&
left._ignoreNullValues == right._ignoreNullValues &&
left._ignoreReadOnlyProperties == right._ignoreReadOnlyProperties &&
left._ignoreReadonlyFields == right._ignoreReadonlyFields &&
left._includeFields == right._includeFields &&
left._propertyNameCaseInsensitive == right._propertyNameCaseInsensitive &&
left._writeIndented == right._writeIndented &&
left._serializerContext == right._serializerContext &&
CompareConverters(left._converters, right._converters);
static bool CompareConverters(ConverterList left, ConverterList right)
{
int n;
if ((n = left.Count) != right.Count)
{
return false;
}
for (int i = 0; i < n; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
}
public int GetHashCode(JsonSerializerOptions options)
{
HashCode hc = default;
hc.Add(options._dictionaryKeyPolicy);
hc.Add(options._jsonPropertyNamingPolicy);
hc.Add(options._readCommentHandling);
hc.Add(options._referenceHandler);
hc.Add(options._encoder);
hc.Add(options._defaultIgnoreCondition);
hc.Add(options._numberHandling);
hc.Add(options._unknownTypeHandling);
hc.Add(options._defaultBufferSize);
hc.Add(options._maxDepth);
hc.Add(options._allowTrailingCommas);
hc.Add(options._ignoreNullValues);
hc.Add(options._ignoreReadOnlyProperties);
hc.Add(options._ignoreReadonlyFields);
hc.Add(options._includeFields);
hc.Add(options._propertyNameCaseInsensitive);
hc.Add(options._writeIndented);
hc.Add(options._serializerContext);
for (int i = 0; i < options._converters.Count; i++)
{
hc.Add(options._converters[i]);
}
return hc.ToHashCode();
}
#if !NETCOREAPP
/// <summary>
/// Polyfill for System.HashCode.
/// </summary>
private struct HashCode
{
private int _hashCode;
public void Add<T>(T? value) => _hashCode = (_hashCode, value).GetHashCode();
public int ToHashCode() => _hashCode;
}
#endif
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Json.Reflection;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
/// <summary>
/// Provides options to be used with <see cref="JsonSerializer"/>.
/// </summary>
public sealed partial class JsonSerializerOptions
{
// The global list of built-in simple converters.
private static Dictionary<Type, JsonConverter>? s_defaultSimpleConverters;
// The global list of built-in converters that override CanConvert().
private static JsonConverter[]? s_defaultFactoryConverters;
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
private static void RootBuiltInConverters()
{
s_defaultSimpleConverters = GetDefaultSimpleConverters();
s_defaultFactoryConverters = new JsonConverter[]
{
// Check for disallowed types.
new UnsupportedTypeConverterFactory(),
// Nullable converter should always be next since it forwards to any nullable type.
new NullableConverterFactory(),
new EnumConverterFactory(),
new JsonNodeConverterFactory(),
new FSharpTypeConverterFactory(),
// IAsyncEnumerable takes precedence over IEnumerable.
new IAsyncEnumerableConverterFactory(),
// IEnumerable should always be second to last since they can convert any IEnumerable.
new IEnumerableConverterFactory(),
// Object should always be last since it converts any type.
new ObjectConverterFactory()
};
}
private static Dictionary<Type, JsonConverter> GetDefaultSimpleConverters()
{
const int NumberOfSimpleConverters = 24;
var converters = new Dictionary<Type, JsonConverter>(NumberOfSimpleConverters);
// Use a dictionary for simple converters.
// When adding to this, update NumberOfSimpleConverters above.
Add(JsonMetadataServices.BooleanConverter);
Add(JsonMetadataServices.ByteConverter);
Add(JsonMetadataServices.ByteArrayConverter);
Add(JsonMetadataServices.CharConverter);
Add(JsonMetadataServices.DateTimeConverter);
Add(JsonMetadataServices.DateTimeOffsetConverter);
Add(JsonMetadataServices.DoubleConverter);
Add(JsonMetadataServices.DecimalConverter);
Add(JsonMetadataServices.GuidConverter);
Add(JsonMetadataServices.Int16Converter);
Add(JsonMetadataServices.Int32Converter);
Add(JsonMetadataServices.Int64Converter);
Add(new JsonElementConverter());
Add(new JsonDocumentConverter());
Add(JsonMetadataServices.ObjectConverter);
Add(JsonMetadataServices.SByteConverter);
Add(JsonMetadataServices.SingleConverter);
Add(JsonMetadataServices.StringConverter);
Add(JsonMetadataServices.TimeSpanConverter);
Add(JsonMetadataServices.UInt16Converter);
Add(JsonMetadataServices.UInt32Converter);
Add(JsonMetadataServices.UInt64Converter);
Add(JsonMetadataServices.UriConverter);
Add(JsonMetadataServices.VersionConverter);
Debug.Assert(NumberOfSimpleConverters == converters.Count);
return converters;
void Add(JsonConverter converter) =>
converters.Add(converter.TypeToConvert, converter);
}
/// <summary>
/// The list of custom converters.
/// </summary>
/// <remarks>
/// Once serialization or deserialization occurs, the list cannot be modified.
/// </remarks>
public IList<JsonConverter> Converters => _converters;
internal JsonConverter GetConverterFromMember(Type? parentClassType, Type propertyType, MemberInfo? memberInfo)
{
JsonConverter converter = null!;
// Priority 1: attempt to get converter from JsonConverterAttribute on property.
if (memberInfo != null)
{
Debug.Assert(parentClassType != null);
JsonConverterAttribute? converterAttribute = (JsonConverterAttribute?)
GetAttributeThatCanHaveMultiple(parentClassType!, typeof(JsonConverterAttribute), memberInfo);
if (converterAttribute != null)
{
converter = GetConverterFromAttribute(converterAttribute, typeToConvert: propertyType, classTypeAttributeIsOn: parentClassType!, memberInfo);
}
}
if (converter == null)
{
converter = GetConverterInternal(propertyType);
Debug.Assert(converter != null);
}
if (converter is JsonConverterFactory factory)
{
converter = factory.GetConverterInternal(propertyType, this);
// A factory cannot return null; GetConverterInternal checked for that.
Debug.Assert(converter != null);
}
// User has indicated that either:
// a) a non-nullable-struct handling converter should handle a nullable struct type or
// b) a nullable-struct handling converter should handle a non-nullable struct type.
// User should implement a custom converter for the underlying struct and remove the unnecessary CanConvert method override.
// The serializer will automatically wrap the custom converter with NullableConverter<T>.
//
// We also throw to avoid passing an invalid argument to setters for nullable struct properties,
// which would cause an InvalidProgramException when the generated IL is invoked.
if (propertyType.IsValueType && converter.IsValueType &&
(propertyType.IsNullableOfT() ^ converter.TypeToConvert.IsNullableOfT()))
{
ThrowHelper.ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(propertyType, converter);
}
return converter;
}
/// <summary>
/// Returns the converter for the specified type.
/// </summary>
/// <param name="typeToConvert">The type to return a converter for.</param>
/// <returns>
/// The converter for the given type.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The configured <see cref="JsonConverter"/> for <paramref name="typeToConvert"/> returned an invalid converter.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="typeToConvert"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode("Getting a converter for a type may require reflection which depends on unreferenced code.")]
public JsonConverter GetConverter(Type typeToConvert!!)
{
RootBuiltInConverters();
return GetConverterInternal(typeToConvert);
}
internal JsonConverter GetConverterInternal(Type typeToConvert)
{
// Only cache the value once (de)serialization has occurred since new converters can be added that may change the result.
if (_cachingContext != null)
{
return _cachingContext.GetOrAddConverter(typeToConvert);
}
return GetConverterFromType(typeToConvert);
}
private JsonConverter GetConverterFromType(Type typeToConvert)
{
Debug.Assert(typeToConvert != null);
// Priority 1: If there is a JsonSerializerContext, fetch the converter from there.
JsonConverter? converter = _serializerContext?.GetTypeInfo(typeToConvert)?.PropertyInfoForTypeInfo?.ConverterBase;
// Priority 2: Attempt to get custom converter added at runtime.
// Currently there is not a way at runtime to override the [JsonConverter] when applied to a property.
foreach (JsonConverter item in _converters)
{
if (item.CanConvert(typeToConvert))
{
converter = item;
break;
}
}
// Priority 3: Attempt to get converter from [JsonConverter] on the type being converted.
if (converter == null)
{
JsonConverterAttribute? converterAttribute = (JsonConverterAttribute?)
GetAttributeThatCanHaveMultiple(typeToConvert, typeof(JsonConverterAttribute));
if (converterAttribute != null)
{
converter = GetConverterFromAttribute(converterAttribute, typeToConvert: typeToConvert, classTypeAttributeIsOn: typeToConvert, memberInfo: null);
}
}
// Priority 4: Attempt to get built-in converter.
if (converter == null)
{
if (s_defaultSimpleConverters == null || s_defaultFactoryConverters == null)
{
// (De)serialization using serializer's options-based methods has not yet occurred, so the built-in converters are not rooted.
// Even though source-gen code paths do not call this method <i.e. JsonSerializerOptions.GetConverter(Type)>, we do not root all the
// built-in converters here since we fetch converters for any type included for source generation from the binded context (Priority 1).
Debug.Assert(s_defaultSimpleConverters == null);
Debug.Assert(s_defaultFactoryConverters == null);
ThrowHelper.ThrowNotSupportedException_BuiltInConvertersNotRooted(typeToConvert);
return null!;
}
if (s_defaultSimpleConverters.TryGetValue(typeToConvert, out JsonConverter? foundConverter))
{
converter = foundConverter;
}
else
{
foreach (JsonConverter item in s_defaultFactoryConverters)
{
if (item.CanConvert(typeToConvert))
{
converter = item;
break;
}
}
// Since the object and IEnumerable converters cover all types, we should have a converter.
Debug.Assert(converter != null);
}
}
// Allow redirection for generic types or the enum converter.
if (converter is JsonConverterFactory factory)
{
converter = factory.GetConverterInternal(typeToConvert, this);
// A factory cannot return null; GetConverterInternal checked for that.
Debug.Assert(converter != null);
}
Type converterTypeToConvert = converter.TypeToConvert;
if (!converterTypeToConvert.IsAssignableFromInternal(typeToConvert)
&& !typeToConvert.IsAssignableFromInternal(converterTypeToConvert))
{
ThrowHelper.ThrowInvalidOperationException_SerializationConverterNotCompatible(converter.GetType(), typeToConvert);
}
return converter;
}
private JsonConverter GetConverterFromAttribute(JsonConverterAttribute converterAttribute, Type typeToConvert, Type classTypeAttributeIsOn, MemberInfo? memberInfo)
{
JsonConverter? converter;
Type? type = converterAttribute.ConverterType;
if (type == null)
{
// Allow the attribute to create the converter.
converter = converterAttribute.CreateConverter(typeToConvert);
if (converter == null)
{
ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, memberInfo, typeToConvert);
}
}
else
{
ConstructorInfo? ctor = type.GetConstructor(Type.EmptyTypes);
if (!typeof(JsonConverter).IsAssignableFrom(type) || ctor == null || !ctor.IsPublic)
{
ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(classTypeAttributeIsOn, memberInfo);
}
converter = (JsonConverter)Activator.CreateInstance(type)!;
}
Debug.Assert(converter != null);
if (!converter.CanConvert(typeToConvert))
{
Type? underlyingType = Nullable.GetUnderlyingType(typeToConvert);
if (underlyingType != null && converter.CanConvert(underlyingType))
{
if (converter is JsonConverterFactory converterFactory)
{
converter = converterFactory.GetConverterInternal(underlyingType, this);
}
// Allow nullable handling to forward to the underlying type's converter.
return NullableConverterFactory.CreateValueConverter(underlyingType, converter);
}
ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, memberInfo, typeToConvert);
}
return converter;
}
internal bool TryGetDefaultSimpleConverter(Type typeToConvert, [NotNullWhen(true)] out JsonConverter? converter)
{
if (_serializerContext == null && // For consistency do not return any default converters for
// options instances linked to a JsonSerializerContext,
// even if the default converters might have been rooted.
s_defaultSimpleConverters != null &&
s_defaultSimpleConverters.TryGetValue(typeToConvert, out converter))
{
return true;
}
converter = null;
return false;
}
private static Attribute? GetAttributeThatCanHaveMultiple(Type classType, Type attributeType, MemberInfo memberInfo)
{
object[] attributes = memberInfo.GetCustomAttributes(attributeType, inherit: false);
return GetAttributeThatCanHaveMultiple(attributeType, classType, memberInfo, attributes);
}
internal static Attribute? GetAttributeThatCanHaveMultiple(Type classType, Type attributeType)
{
object[] attributes = classType.GetCustomAttributes(attributeType, inherit: false);
return GetAttributeThatCanHaveMultiple(attributeType, classType, null, attributes);
}
private static Attribute? GetAttributeThatCanHaveMultiple(Type attributeType, Type classType, MemberInfo? memberInfo, object[] attributes)
{
if (attributes.Length == 0)
{
return null;
}
if (attributes.Length == 1)
{
return (Attribute)attributes[0];
}
ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateAttribute(attributeType, classType, memberInfo);
return default;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Json.Reflection;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
/// <summary>
/// Provides options to be used with <see cref="JsonSerializer"/>.
/// </summary>
public sealed partial class JsonSerializerOptions
{
// The global list of built-in simple converters.
private static Dictionary<Type, JsonConverter>? s_defaultSimpleConverters;
// The global list of built-in converters that override CanConvert().
private static JsonConverter[]? s_defaultFactoryConverters;
// Stores the JsonTypeInfo factory, which requires unreferenced code and must be rooted by the reflection-based serializer.
private static Func<Type, JsonSerializerOptions, JsonTypeInfo>? s_typeInfoCreationFunc;
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
private static void RootReflectionSerializerDependencies()
{
if (s_defaultSimpleConverters is null)
{
s_defaultSimpleConverters = GetDefaultSimpleConverters();
s_defaultFactoryConverters = GetDefaultFactoryConverters();
s_typeInfoCreationFunc = CreateJsonTypeInfo;
}
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options) => new JsonTypeInfo(type, options);
}
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
private static JsonConverter[] GetDefaultFactoryConverters()
{
return new JsonConverter[]
{
// Check for disallowed types.
new UnsupportedTypeConverterFactory(),
// Nullable converter should always be next since it forwards to any nullable type.
new NullableConverterFactory(),
new EnumConverterFactory(),
new JsonNodeConverterFactory(),
new FSharpTypeConverterFactory(),
// IAsyncEnumerable takes precedence over IEnumerable.
new IAsyncEnumerableConverterFactory(),
// IEnumerable should always be second to last since they can convert any IEnumerable.
new IEnumerableConverterFactory(),
// Object should always be last since it converts any type.
new ObjectConverterFactory()
};
}
private static Dictionary<Type, JsonConverter> GetDefaultSimpleConverters()
{
const int NumberOfSimpleConverters = 24;
var converters = new Dictionary<Type, JsonConverter>(NumberOfSimpleConverters);
// Use a dictionary for simple converters.
// When adding to this, update NumberOfSimpleConverters above.
Add(JsonMetadataServices.BooleanConverter);
Add(JsonMetadataServices.ByteConverter);
Add(JsonMetadataServices.ByteArrayConverter);
Add(JsonMetadataServices.CharConverter);
Add(JsonMetadataServices.DateTimeConverter);
Add(JsonMetadataServices.DateTimeOffsetConverter);
Add(JsonMetadataServices.DoubleConverter);
Add(JsonMetadataServices.DecimalConverter);
Add(JsonMetadataServices.GuidConverter);
Add(JsonMetadataServices.Int16Converter);
Add(JsonMetadataServices.Int32Converter);
Add(JsonMetadataServices.Int64Converter);
Add(new JsonElementConverter());
Add(new JsonDocumentConverter());
Add(JsonMetadataServices.ObjectConverter);
Add(JsonMetadataServices.SByteConverter);
Add(JsonMetadataServices.SingleConverter);
Add(JsonMetadataServices.StringConverter);
Add(JsonMetadataServices.TimeSpanConverter);
Add(JsonMetadataServices.UInt16Converter);
Add(JsonMetadataServices.UInt32Converter);
Add(JsonMetadataServices.UInt64Converter);
Add(JsonMetadataServices.UriConverter);
Add(JsonMetadataServices.VersionConverter);
Debug.Assert(NumberOfSimpleConverters == converters.Count);
return converters;
void Add(JsonConverter converter) =>
converters.Add(converter.TypeToConvert, converter);
}
/// <summary>
/// The list of custom converters.
/// </summary>
/// <remarks>
/// Once serialization or deserialization occurs, the list cannot be modified.
/// </remarks>
public IList<JsonConverter> Converters => _converters;
internal JsonConverter GetConverterFromMember(Type? parentClassType, Type propertyType, MemberInfo? memberInfo)
{
JsonConverter converter = null!;
// Priority 1: attempt to get converter from JsonConverterAttribute on property.
if (memberInfo != null)
{
Debug.Assert(parentClassType != null);
JsonConverterAttribute? converterAttribute = (JsonConverterAttribute?)
GetAttributeThatCanHaveMultiple(parentClassType!, typeof(JsonConverterAttribute), memberInfo);
if (converterAttribute != null)
{
converter = GetConverterFromAttribute(converterAttribute, typeToConvert: propertyType, classTypeAttributeIsOn: parentClassType!, memberInfo);
}
}
if (converter == null)
{
converter = GetConverterInternal(propertyType);
Debug.Assert(converter != null);
}
if (converter is JsonConverterFactory factory)
{
converter = factory.GetConverterInternal(propertyType, this);
// A factory cannot return null; GetConverterInternal checked for that.
Debug.Assert(converter != null);
}
// User has indicated that either:
// a) a non-nullable-struct handling converter should handle a nullable struct type or
// b) a nullable-struct handling converter should handle a non-nullable struct type.
// User should implement a custom converter for the underlying struct and remove the unnecessary CanConvert method override.
// The serializer will automatically wrap the custom converter with NullableConverter<T>.
//
// We also throw to avoid passing an invalid argument to setters for nullable struct properties,
// which would cause an InvalidProgramException when the generated IL is invoked.
if (propertyType.IsValueType && converter.IsValueType &&
(propertyType.IsNullableOfT() ^ converter.TypeToConvert.IsNullableOfT()))
{
ThrowHelper.ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(propertyType, converter);
}
return converter;
}
/// <summary>
/// Returns the converter for the specified type.
/// </summary>
/// <param name="typeToConvert">The type to return a converter for.</param>
/// <returns>
/// The converter for the given type.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The configured <see cref="JsonConverter"/> for <paramref name="typeToConvert"/> returned an invalid converter.
/// </exception>
/// <exception cref="NotSupportedException">
/// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
/// for <paramref name="typeToConvert"/> or its serializable members.
/// </exception>
[RequiresUnreferencedCode("Getting a converter for a type may require reflection which depends on unreferenced code.")]
public JsonConverter GetConverter(Type typeToConvert!!)
{
RootReflectionSerializerDependencies();
return GetConverterInternal(typeToConvert);
}
internal JsonConverter GetConverterInternal(Type typeToConvert)
{
// Only cache the value once (de)serialization has occurred since new converters can be added that may change the result.
if (_cachingContext != null)
{
return _cachingContext.GetOrAddConverter(typeToConvert);
}
return GetConverterFromType(typeToConvert);
}
private JsonConverter GetConverterFromType(Type typeToConvert)
{
Debug.Assert(typeToConvert != null);
// Priority 1: If there is a JsonSerializerContext, fetch the converter from there.
JsonConverter? converter = _serializerContext?.GetTypeInfo(typeToConvert)?.PropertyInfoForTypeInfo?.ConverterBase;
// Priority 2: Attempt to get custom converter added at runtime.
// Currently there is not a way at runtime to override the [JsonConverter] when applied to a property.
foreach (JsonConverter item in _converters)
{
if (item.CanConvert(typeToConvert))
{
converter = item;
break;
}
}
// Priority 3: Attempt to get converter from [JsonConverter] on the type being converted.
if (converter == null)
{
JsonConverterAttribute? converterAttribute = (JsonConverterAttribute?)
GetAttributeThatCanHaveMultiple(typeToConvert, typeof(JsonConverterAttribute));
if (converterAttribute != null)
{
converter = GetConverterFromAttribute(converterAttribute, typeToConvert: typeToConvert, classTypeAttributeIsOn: typeToConvert, memberInfo: null);
}
}
// Priority 4: Attempt to get built-in converter.
if (converter == null)
{
if (s_defaultSimpleConverters == null || s_defaultFactoryConverters == null)
{
// (De)serialization using serializer's options-based methods has not yet occurred, so the built-in converters are not rooted.
// Even though source-gen code paths do not call this method <i.e. JsonSerializerOptions.GetConverter(Type)>, we do not root all the
// built-in converters here since we fetch converters for any type included for source generation from the binded context (Priority 1).
Debug.Assert(s_defaultSimpleConverters == null);
Debug.Assert(s_defaultFactoryConverters == null);
ThrowHelper.ThrowNotSupportedException_BuiltInConvertersNotRooted(typeToConvert);
return null!;
}
if (s_defaultSimpleConverters.TryGetValue(typeToConvert, out JsonConverter? foundConverter))
{
converter = foundConverter;
}
else
{
foreach (JsonConverter item in s_defaultFactoryConverters)
{
if (item.CanConvert(typeToConvert))
{
converter = item;
break;
}
}
// Since the object and IEnumerable converters cover all types, we should have a converter.
Debug.Assert(converter != null);
}
}
// Allow redirection for generic types or the enum converter.
if (converter is JsonConverterFactory factory)
{
converter = factory.GetConverterInternal(typeToConvert, this);
// A factory cannot return null; GetConverterInternal checked for that.
Debug.Assert(converter != null);
}
Type converterTypeToConvert = converter.TypeToConvert;
if (!converterTypeToConvert.IsAssignableFromInternal(typeToConvert)
&& !typeToConvert.IsAssignableFromInternal(converterTypeToConvert))
{
ThrowHelper.ThrowInvalidOperationException_SerializationConverterNotCompatible(converter.GetType(), typeToConvert);
}
return converter;
}
private JsonConverter GetConverterFromAttribute(JsonConverterAttribute converterAttribute, Type typeToConvert, Type classTypeAttributeIsOn, MemberInfo? memberInfo)
{
JsonConverter? converter;
Type? type = converterAttribute.ConverterType;
if (type == null)
{
// Allow the attribute to create the converter.
converter = converterAttribute.CreateConverter(typeToConvert);
if (converter == null)
{
ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, memberInfo, typeToConvert);
}
}
else
{
ConstructorInfo? ctor = type.GetConstructor(Type.EmptyTypes);
if (!typeof(JsonConverter).IsAssignableFrom(type) || ctor == null || !ctor.IsPublic)
{
ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(classTypeAttributeIsOn, memberInfo);
}
converter = (JsonConverter)Activator.CreateInstance(type)!;
}
Debug.Assert(converter != null);
if (!converter.CanConvert(typeToConvert))
{
Type? underlyingType = Nullable.GetUnderlyingType(typeToConvert);
if (underlyingType != null && converter.CanConvert(underlyingType))
{
if (converter is JsonConverterFactory converterFactory)
{
converter = converterFactory.GetConverterInternal(underlyingType, this);
}
// Allow nullable handling to forward to the underlying type's converter.
return NullableConverterFactory.CreateValueConverter(underlyingType, converter);
}
ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, memberInfo, typeToConvert);
}
return converter;
}
internal bool TryGetDefaultSimpleConverter(Type typeToConvert, [NotNullWhen(true)] out JsonConverter? converter)
{
if (_serializerContext == null && // For consistency do not return any default converters for
// options instances linked to a JsonSerializerContext,
// even if the default converters might have been rooted.
s_defaultSimpleConverters != null &&
s_defaultSimpleConverters.TryGetValue(typeToConvert, out converter))
{
return true;
}
converter = null;
return false;
}
private static Attribute? GetAttributeThatCanHaveMultiple(Type classType, Type attributeType, MemberInfo memberInfo)
{
object[] attributes = memberInfo.GetCustomAttributes(attributeType, inherit: false);
return GetAttributeThatCanHaveMultiple(attributeType, classType, memberInfo, attributes);
}
internal static Attribute? GetAttributeThatCanHaveMultiple(Type classType, Type attributeType)
{
object[] attributes = classType.GetCustomAttributes(attributeType, inherit: false);
return GetAttributeThatCanHaveMultiple(attributeType, classType, null, attributes);
}
private static Attribute? GetAttributeThatCanHaveMultiple(Type attributeType, Type classType, MemberInfo? memberInfo, object[] attributes)
{
if (attributes.Length == 0)
{
return null;
}
if (attributes.Length == 1)
{
return (Attribute)attributes[0];
}
ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateAttribute(attributeType, classType, memberInfo);
return default;
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
/// <summary>
/// Provides options to be used with <see cref="JsonSerializer"/>.
/// </summary>
public sealed partial class JsonSerializerOptions
{
internal const int BufferSizeDefault = 16 * 1024;
// For backward compatibility the default max depth for JsonSerializer is 64,
// the minimum of JsonReaderOptions.DefaultMaxDepth and JsonWriterOptions.DefaultMaxDepth.
internal const int DefaultMaxDepth = JsonReaderOptions.DefaultMaxDepth;
/// <summary>
/// Gets a read-only, singleton instance of <see cref="JsonSerializerOptions" /> that uses the default configuration.
/// </summary>
/// <remarks>
/// Each <see cref="JsonSerializerOptions" /> instance encapsulates its own serialization metadata caches,
/// so using fresh default instances every time one is needed can result in redundant recomputation of converters.
/// This property provides a shared instance that can be consumed by any number of components without necessitating any converter recomputation.
/// </remarks>
public static JsonSerializerOptions Default { get; } = CreateDefaultImmutableInstance();
internal JsonSerializerContext? _serializerContext;
// Stores the JsonTypeInfo factory, which requires unreferenced code and must be rooted by the reflection-based serializer.
private static Func<Type, JsonSerializerOptions, JsonTypeInfo>? s_typeInfoCreationFunc;
// For any new option added, adding it to the options copied in the copy constructor below must be considered.
private MemberAccessor? _memberAccessorStrategy;
private JsonNamingPolicy? _dictionaryKeyPolicy;
private JsonNamingPolicy? _jsonPropertyNamingPolicy;
private JsonCommentHandling _readCommentHandling;
private ReferenceHandler? _referenceHandler;
private JavaScriptEncoder? _encoder;
private ConverterList _converters;
private JsonIgnoreCondition _defaultIgnoreCondition;
private JsonNumberHandling _numberHandling;
private JsonUnknownTypeHandling _unknownTypeHandling;
private int _defaultBufferSize = BufferSizeDefault;
private int _maxDepth;
private bool _allowTrailingCommas;
private bool _ignoreNullValues;
private bool _ignoreReadOnlyProperties;
private bool _ignoreReadonlyFields;
private bool _includeFields;
private bool _propertyNameCaseInsensitive;
private bool _writeIndented;
/// <summary>
/// Constructs a new <see cref="JsonSerializerOptions"/> instance.
/// </summary>
public JsonSerializerOptions()
{
_converters = new ConverterList(this);
TrackOptionsInstance(this);
}
/// <summary>
/// Copies the options from a <see cref="JsonSerializerOptions"/> instance to a new instance.
/// </summary>
/// <param name="options">The <see cref="JsonSerializerOptions"/> instance to copy options from.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="options"/> is <see langword="null"/>.
/// </exception>
public JsonSerializerOptions(JsonSerializerOptions options!!)
{
_memberAccessorStrategy = options._memberAccessorStrategy;
_dictionaryKeyPolicy = options._dictionaryKeyPolicy;
_jsonPropertyNamingPolicy = options._jsonPropertyNamingPolicy;
_readCommentHandling = options._readCommentHandling;
_referenceHandler = options._referenceHandler;
_encoder = options._encoder;
_defaultIgnoreCondition = options._defaultIgnoreCondition;
_numberHandling = options._numberHandling;
_unknownTypeHandling = options._unknownTypeHandling;
_defaultBufferSize = options._defaultBufferSize;
_maxDepth = options._maxDepth;
_allowTrailingCommas = options._allowTrailingCommas;
_ignoreNullValues = options._ignoreNullValues;
_ignoreReadOnlyProperties = options._ignoreReadOnlyProperties;
_ignoreReadonlyFields = options._ignoreReadonlyFields;
_includeFields = options._includeFields;
_propertyNameCaseInsensitive = options._propertyNameCaseInsensitive;
_writeIndented = options._writeIndented;
_converters = new ConverterList(this, options._converters);
EffectiveMaxDepth = options.EffectiveMaxDepth;
ReferenceHandlingStrategy = options.ReferenceHandlingStrategy;
// _classes is not copied as sharing the JsonTypeInfo and JsonPropertyInfo caches can result in
// unnecessary references to type metadata, potentially hindering garbage collection on the source options.
// _haveTypesBeenCreated is not copied; it's okay to make changes to this options instance as (de)serialization has not occurred.
TrackOptionsInstance(this);
}
/// <summary>Tracks the options instance to enable all instances to be enumerated.</summary>
private static void TrackOptionsInstance(JsonSerializerOptions options) => TrackedOptionsInstances.All.Add(options, null);
internal static class TrackedOptionsInstances
{
/// <summary>Tracks all live JsonSerializerOptions instances.</summary>
/// <remarks>Instances are added to the table in their constructor.</remarks>
public static ConditionalWeakTable<JsonSerializerOptions, object?> All { get; } =
// TODO https://github.com/dotnet/runtime/issues/51159:
// Look into linking this away / disabling it when hot reload isn't in use.
new ConditionalWeakTable<JsonSerializerOptions, object?>();
}
/// <summary>
/// Constructs a new <see cref="JsonSerializerOptions"/> instance with a predefined set of options determined by the specified <see cref="JsonSerializerDefaults"/>.
/// </summary>
/// <param name="defaults"> The <see cref="JsonSerializerDefaults"/> to reason about.</param>
public JsonSerializerOptions(JsonSerializerDefaults defaults) : this()
{
if (defaults == JsonSerializerDefaults.Web)
{
_propertyNameCaseInsensitive = true;
_jsonPropertyNamingPolicy = JsonNamingPolicy.CamelCase;
_numberHandling = JsonNumberHandling.AllowReadingFromString;
}
else if (defaults != JsonSerializerDefaults.General)
{
throw new ArgumentOutOfRangeException(nameof(defaults));
}
}
/// <summary>
/// Binds current <see cref="JsonSerializerOptions"/> instance with a new instance of the specified <see cref="JsonSerializerContext"/> type.
/// </summary>
/// <typeparam name="TContext">The generic definition of the specified context type.</typeparam>
/// <remarks>When serializing and deserializing types using the options
/// instance, metadata for the types will be fetched from the context instance.
/// </remarks>
public void AddContext<TContext>() where TContext : JsonSerializerContext, new()
{
if (_serializerContext != null)
{
ThrowHelper.ThrowInvalidOperationException_JsonSerializerOptionsAlreadyBoundToContext();
}
TContext context = new();
_serializerContext = context;
context._options = this;
}
/// <summary>
/// Defines whether an extra comma at the end of a list of JSON values in an object or array
/// is allowed (and ignored) within the JSON payload being deserialized.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <remarks>
/// By default, it's set to false, and <exception cref="JsonException"/> is thrown if a trailing comma is encountered.
/// </remarks>
public bool AllowTrailingCommas
{
get
{
return _allowTrailingCommas;
}
set
{
VerifyMutable();
_allowTrailingCommas = value;
}
}
/// <summary>
/// The default buffer size in bytes used when creating temporary buffers.
/// </summary>
/// <remarks>The default size is 16K.</remarks>
/// <exception cref="System.ArgumentException">Thrown when the buffer size is less than 1.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public int DefaultBufferSize
{
get
{
return _defaultBufferSize;
}
set
{
VerifyMutable();
if (value < 1)
{
throw new ArgumentException(SR.SerializationInvalidBufferSize);
}
_defaultBufferSize = value;
}
}
/// <summary>
/// The encoder to use when escaping strings, or <see langword="null" /> to use the default encoder.
/// </summary>
public JavaScriptEncoder? Encoder
{
get
{
return _encoder;
}
set
{
VerifyMutable();
_encoder = value;
}
}
/// <summary>
/// Specifies the policy used to convert a <see cref="System.Collections.IDictionary"/> key's name to another format, such as camel-casing.
/// </summary>
/// <remarks>
/// This property can be set to <see cref="JsonNamingPolicy.CamelCase"/> to specify a camel-casing policy.
/// It is not used when deserializing.
/// </remarks>
public JsonNamingPolicy? DictionaryKeyPolicy
{
get
{
return _dictionaryKeyPolicy;
}
set
{
VerifyMutable();
_dictionaryKeyPolicy = value;
}
}
/// <summary>
/// Determines whether null values are ignored during serialization and deserialization.
/// The default value is false.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// or <see cref="DefaultIgnoreCondition"/> has been set to a non-default value. These properties cannot be used together.
/// </exception>
[Obsolete(Obsoletions.JsonSerializerOptionsIgnoreNullValuesMessage, DiagnosticId = Obsoletions.JsonSerializerOptionsIgnoreNullValuesDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool IgnoreNullValues
{
get
{
return _ignoreNullValues;
}
set
{
VerifyMutable();
if (value && _defaultIgnoreCondition != JsonIgnoreCondition.Never)
{
throw new InvalidOperationException(SR.DefaultIgnoreConditionAlreadySpecified);
}
_ignoreNullValues = value;
}
}
/// <summary>
/// Specifies a condition to determine when properties with default values are ignored during serialization or deserialization.
/// The default value is <see cref="JsonIgnoreCondition.Never" />.
/// </summary>
/// <exception cref="ArgumentException">
/// Thrown if this property is set to <see cref="JsonIgnoreCondition.Always"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred,
/// or <see cref="IgnoreNullValues"/> has been set to <see langword="true"/>. These properties cannot be used together.
/// </exception>
public JsonIgnoreCondition DefaultIgnoreCondition
{
get
{
return _defaultIgnoreCondition;
}
set
{
VerifyMutable();
if (value == JsonIgnoreCondition.Always)
{
throw new ArgumentException(SR.DefaultIgnoreConditionInvalid);
}
if (value != JsonIgnoreCondition.Never && _ignoreNullValues)
{
throw new InvalidOperationException(SR.DefaultIgnoreConditionAlreadySpecified);
}
_defaultIgnoreCondition = value;
}
}
/// <summary>
/// Specifies how number types should be handled when serializing or deserializing.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public JsonNumberHandling NumberHandling
{
get => _numberHandling;
set
{
VerifyMutable();
if (!JsonSerializer.IsValidNumberHandlingValue(value))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_numberHandling = value;
}
}
/// <summary>
/// Determines whether read-only properties are ignored during serialization.
/// A property is read-only if it contains a public getter but not a public setter.
/// The default value is false.
/// </summary>
/// <remarks>
/// Read-only properties are not deserialized regardless of this setting.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IgnoreReadOnlyProperties
{
get
{
return _ignoreReadOnlyProperties;
}
set
{
VerifyMutable();
_ignoreReadOnlyProperties = value;
}
}
/// <summary>
/// Determines whether read-only fields are ignored during serialization.
/// A field is read-only if it is marked with the <c>readonly</c> keyword.
/// The default value is false.
/// </summary>
/// <remarks>
/// Read-only fields are not deserialized regardless of this setting.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IgnoreReadOnlyFields
{
get
{
return _ignoreReadonlyFields;
}
set
{
VerifyMutable();
_ignoreReadonlyFields = value;
}
}
/// <summary>
/// Determines whether fields are handled on serialization and deserialization.
/// The default value is false.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IncludeFields
{
get
{
return _includeFields;
}
set
{
VerifyMutable();
_includeFields = value;
}
}
/// <summary>
/// Gets or sets the maximum depth allowed when serializing or deserializing JSON, with the default (i.e. 0) indicating a max depth of 64.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the max depth is set to a negative value.
/// </exception>
/// <remarks>
/// Going past this depth will throw a <exception cref="JsonException"/>.
/// </remarks>
public int MaxDepth
{
get => _maxDepth;
set
{
VerifyMutable();
if (value < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException_MaxDepthMustBePositive(nameof(value));
}
_maxDepth = value;
EffectiveMaxDepth = (value == 0 ? DefaultMaxDepth : value);
}
}
internal int EffectiveMaxDepth { get; private set; } = DefaultMaxDepth;
/// <summary>
/// Specifies the policy used to convert a property's name on an object to another format, such as camel-casing.
/// The resulting property name is expected to match the JSON payload during deserialization, and
/// will be used when writing the property name during serialization.
/// </summary>
/// <remarks>
/// The policy is not used for properties that have a <see cref="JsonPropertyNameAttribute"/> applied.
/// This property can be set to <see cref="JsonNamingPolicy.CamelCase"/> to specify a camel-casing policy.
/// </remarks>
public JsonNamingPolicy? PropertyNamingPolicy
{
get
{
return _jsonPropertyNamingPolicy;
}
set
{
VerifyMutable();
_jsonPropertyNamingPolicy = value;
}
}
/// <summary>
/// Determines whether a property's name uses a case-insensitive comparison during deserialization.
/// The default value is false.
/// </summary>
/// <remarks>There is a performance cost associated when the value is true.</remarks>
public bool PropertyNameCaseInsensitive
{
get
{
return _propertyNameCaseInsensitive;
}
set
{
VerifyMutable();
_propertyNameCaseInsensitive = value;
}
}
/// <summary>
/// Defines how the comments are handled during deserialization.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the comment handling enum is set to a value that is not supported (or not within the <see cref="JsonCommentHandling"/> enum range).
/// </exception>
/// <remarks>
/// By default <exception cref="JsonException"/> is thrown if a comment is encountered.
/// </remarks>
public JsonCommentHandling ReadCommentHandling
{
get
{
return _readCommentHandling;
}
set
{
VerifyMutable();
Debug.Assert(value >= 0);
if (value > JsonCommentHandling.Skip)
throw new ArgumentOutOfRangeException(nameof(value), SR.JsonSerializerDoesNotSupportComments);
_readCommentHandling = value;
}
}
/// <summary>
/// Defines how deserializing a type declared as an <see cref="object"/> is handled during deserialization.
/// </summary>
public JsonUnknownTypeHandling UnknownTypeHandling
{
get => _unknownTypeHandling;
set
{
VerifyMutable();
_unknownTypeHandling = value;
}
}
/// <summary>
/// Defines whether JSON should pretty print which includes:
/// indenting nested JSON tokens, adding new lines, and adding white space between property names and values.
/// By default, the JSON is serialized without any extra white space.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool WriteIndented
{
get
{
return _writeIndented;
}
set
{
VerifyMutable();
_writeIndented = value;
}
}
/// <summary>
/// Configures how object references are handled when reading and writing JSON.
/// </summary>
public ReferenceHandler? ReferenceHandler
{
get => _referenceHandler;
set
{
VerifyMutable();
_referenceHandler = value;
ReferenceHandlingStrategy = value?.HandlingStrategy ?? ReferenceHandlingStrategy.None;
}
}
// The cached value used to determine if ReferenceHandler should use Preserve or IgnoreCycles semanitcs or None of them.
internal ReferenceHandlingStrategy ReferenceHandlingStrategy = ReferenceHandlingStrategy.None;
internal MemberAccessor MemberAccessorStrategy
{
get
{
if (_memberAccessorStrategy == null)
{
#if NETCOREAPP
// if dynamic code isn't supported, fallback to reflection
_memberAccessorStrategy = RuntimeFeature.IsDynamicCodeSupported ?
new ReflectionEmitCachingMemberAccessor() :
new ReflectionMemberAccessor();
#elif NETFRAMEWORK
_memberAccessorStrategy = new ReflectionEmitCachingMemberAccessor();
#else
_memberAccessorStrategy = new ReflectionMemberAccessor();
#endif
}
return _memberAccessorStrategy;
}
}
/// <summary>
/// Whether <see cref="InitializeForReflectionSerializer()"/> needs to be called.
/// </summary>
internal static bool IsInitializedForReflectionSerializer { get; set; }
/// <summary>
/// Initializes the converters for the reflection-based serializer.
/// <seealso cref="InitializeForReflectionSerializer"/> must be checked before calling.
/// </summary>
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
internal static void InitializeForReflectionSerializer()
{
// For threading cases, the state that is set here can be overwritten.
RootBuiltInConverters();
s_typeInfoCreationFunc = CreateJsonTypeInfo;
IsInitializedForReflectionSerializer = true;
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options) => new JsonTypeInfo(type, options);
}
private JsonTypeInfo GetJsonTypeInfoFromContextOrCreate(Type type)
{
JsonTypeInfo? info = _serializerContext?.GetTypeInfo(type);
if (info != null)
{
return info;
}
if (s_typeInfoCreationFunc == null)
{
ThrowHelper.ThrowNotSupportedException_NoMetadataForType(type);
return null!;
}
return s_typeInfoCreationFunc(type, this);
}
internal JsonDocumentOptions GetDocumentOptions()
{
return new JsonDocumentOptions
{
AllowTrailingCommas = AllowTrailingCommas,
CommentHandling = ReadCommentHandling,
MaxDepth = MaxDepth
};
}
internal JsonNodeOptions GetNodeOptions()
{
return new JsonNodeOptions
{
PropertyNameCaseInsensitive = PropertyNameCaseInsensitive
};
}
internal JsonReaderOptions GetReaderOptions()
{
return new JsonReaderOptions
{
AllowTrailingCommas = AllowTrailingCommas,
CommentHandling = ReadCommentHandling,
MaxDepth = EffectiveMaxDepth
};
}
internal JsonWriterOptions GetWriterOptions()
{
return new JsonWriterOptions
{
Encoder = Encoder,
Indented = WriteIndented,
MaxDepth = EffectiveMaxDepth,
#if !DEBUG
SkipValidation = true
#endif
};
}
internal void VerifyMutable()
{
if (_cachingContext != null || _serializerContext != null)
{
ThrowHelper.ThrowInvalidOperationException_SerializerOptionsImmutable(_serializerContext);
}
}
private static JsonSerializerOptions CreateDefaultImmutableInstance()
{
var options = new JsonSerializerOptions();
options.InitializeCachingContext(); // eagerly initialize caching context to close type for modification.
return options;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
/// <summary>
/// Provides options to be used with <see cref="JsonSerializer"/>.
/// </summary>
public sealed partial class JsonSerializerOptions
{
internal const int BufferSizeDefault = 16 * 1024;
// For backward compatibility the default max depth for JsonSerializer is 64,
// the minimum of JsonReaderOptions.DefaultMaxDepth and JsonWriterOptions.DefaultMaxDepth.
internal const int DefaultMaxDepth = JsonReaderOptions.DefaultMaxDepth;
/// <summary>
/// Gets a read-only, singleton instance of <see cref="JsonSerializerOptions" /> that uses the default configuration.
/// </summary>
/// <remarks>
/// Each <see cref="JsonSerializerOptions" /> instance encapsulates its own serialization metadata caches,
/// so using fresh default instances every time one is needed can result in redundant recomputation of converters.
/// This property provides a shared instance that can be consumed by any number of components without necessitating any converter recomputation.
/// </remarks>
public static JsonSerializerOptions Default { get; } = CreateDefaultImmutableInstance();
// For any new option added, adding it to the options copied in the copy constructor below must be considered.
private JsonSerializerContext? _serializerContext;
private MemberAccessor? _memberAccessorStrategy;
private JsonNamingPolicy? _dictionaryKeyPolicy;
private JsonNamingPolicy? _jsonPropertyNamingPolicy;
private JsonCommentHandling _readCommentHandling;
private ReferenceHandler? _referenceHandler;
private JavaScriptEncoder? _encoder;
private ConverterList _converters;
private JsonIgnoreCondition _defaultIgnoreCondition;
private JsonNumberHandling _numberHandling;
private JsonUnknownTypeHandling _unknownTypeHandling;
private int _defaultBufferSize = BufferSizeDefault;
private int _maxDepth;
private bool _allowTrailingCommas;
private bool _ignoreNullValues;
private bool _ignoreReadOnlyProperties;
private bool _ignoreReadonlyFields;
private bool _includeFields;
private bool _propertyNameCaseInsensitive;
private bool _writeIndented;
/// <summary>
/// Constructs a new <see cref="JsonSerializerOptions"/> instance.
/// </summary>
public JsonSerializerOptions()
{
_converters = new ConverterList(this);
TrackOptionsInstance(this);
}
/// <summary>
/// Copies the options from a <see cref="JsonSerializerOptions"/> instance to a new instance.
/// </summary>
/// <param name="options">The <see cref="JsonSerializerOptions"/> instance to copy options from.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="options"/> is <see langword="null"/>.
/// </exception>
public JsonSerializerOptions(JsonSerializerOptions options!!)
{
_memberAccessorStrategy = options._memberAccessorStrategy;
_dictionaryKeyPolicy = options._dictionaryKeyPolicy;
_jsonPropertyNamingPolicy = options._jsonPropertyNamingPolicy;
_readCommentHandling = options._readCommentHandling;
_referenceHandler = options._referenceHandler;
_encoder = options._encoder;
_defaultIgnoreCondition = options._defaultIgnoreCondition;
_numberHandling = options._numberHandling;
_unknownTypeHandling = options._unknownTypeHandling;
_defaultBufferSize = options._defaultBufferSize;
_maxDepth = options._maxDepth;
_allowTrailingCommas = options._allowTrailingCommas;
_ignoreNullValues = options._ignoreNullValues;
_ignoreReadOnlyProperties = options._ignoreReadOnlyProperties;
_ignoreReadonlyFields = options._ignoreReadonlyFields;
_includeFields = options._includeFields;
_propertyNameCaseInsensitive = options._propertyNameCaseInsensitive;
_writeIndented = options._writeIndented;
_converters = new ConverterList(this, options._converters);
EffectiveMaxDepth = options.EffectiveMaxDepth;
ReferenceHandlingStrategy = options.ReferenceHandlingStrategy;
// _classes is not copied as sharing the JsonTypeInfo and JsonPropertyInfo caches can result in
// unnecessary references to type metadata, potentially hindering garbage collection on the source options.
// _haveTypesBeenCreated is not copied; it's okay to make changes to this options instance as (de)serialization has not occurred.
TrackOptionsInstance(this);
}
/// <summary>Tracks the options instance to enable all instances to be enumerated.</summary>
private static void TrackOptionsInstance(JsonSerializerOptions options) => TrackedOptionsInstances.All.Add(options, null);
internal static class TrackedOptionsInstances
{
/// <summary>Tracks all live JsonSerializerOptions instances.</summary>
/// <remarks>Instances are added to the table in their constructor.</remarks>
public static ConditionalWeakTable<JsonSerializerOptions, object?> All { get; } =
// TODO https://github.com/dotnet/runtime/issues/51159:
// Look into linking this away / disabling it when hot reload isn't in use.
new ConditionalWeakTable<JsonSerializerOptions, object?>();
}
/// <summary>
/// Constructs a new <see cref="JsonSerializerOptions"/> instance with a predefined set of options determined by the specified <see cref="JsonSerializerDefaults"/>.
/// </summary>
/// <param name="defaults"> The <see cref="JsonSerializerDefaults"/> to reason about.</param>
public JsonSerializerOptions(JsonSerializerDefaults defaults) : this()
{
if (defaults == JsonSerializerDefaults.Web)
{
_propertyNameCaseInsensitive = true;
_jsonPropertyNamingPolicy = JsonNamingPolicy.CamelCase;
_numberHandling = JsonNumberHandling.AllowReadingFromString;
}
else if (defaults != JsonSerializerDefaults.General)
{
throw new ArgumentOutOfRangeException(nameof(defaults));
}
}
/// <summary>
/// Binds current <see cref="JsonSerializerOptions"/> instance with a new instance of the specified <see cref="Serialization.JsonSerializerContext"/> type.
/// </summary>
/// <typeparam name="TContext">The generic definition of the specified context type.</typeparam>
/// <remarks>When serializing and deserializing types using the options
/// instance, metadata for the types will be fetched from the context instance.
/// </remarks>
public void AddContext<TContext>() where TContext : JsonSerializerContext, new()
{
VerifyMutable();
TContext context = new();
_serializerContext = context;
context._options = this;
}
/// <summary>
/// Defines whether an extra comma at the end of a list of JSON values in an object or array
/// is allowed (and ignored) within the JSON payload being deserialized.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <remarks>
/// By default, it's set to false, and <exception cref="JsonException"/> is thrown if a trailing comma is encountered.
/// </remarks>
public bool AllowTrailingCommas
{
get
{
return _allowTrailingCommas;
}
set
{
VerifyMutable();
_allowTrailingCommas = value;
}
}
/// <summary>
/// The default buffer size in bytes used when creating temporary buffers.
/// </summary>
/// <remarks>The default size is 16K.</remarks>
/// <exception cref="System.ArgumentException">Thrown when the buffer size is less than 1.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public int DefaultBufferSize
{
get
{
return _defaultBufferSize;
}
set
{
VerifyMutable();
if (value < 1)
{
throw new ArgumentException(SR.SerializationInvalidBufferSize);
}
_defaultBufferSize = value;
}
}
/// <summary>
/// The encoder to use when escaping strings, or <see langword="null" /> to use the default encoder.
/// </summary>
public JavaScriptEncoder? Encoder
{
get
{
return _encoder;
}
set
{
VerifyMutable();
_encoder = value;
}
}
/// <summary>
/// Specifies the policy used to convert a <see cref="System.Collections.IDictionary"/> key's name to another format, such as camel-casing.
/// </summary>
/// <remarks>
/// This property can be set to <see cref="JsonNamingPolicy.CamelCase"/> to specify a camel-casing policy.
/// It is not used when deserializing.
/// </remarks>
public JsonNamingPolicy? DictionaryKeyPolicy
{
get
{
return _dictionaryKeyPolicy;
}
set
{
VerifyMutable();
_dictionaryKeyPolicy = value;
}
}
/// <summary>
/// Determines whether null values are ignored during serialization and deserialization.
/// The default value is false.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// or <see cref="DefaultIgnoreCondition"/> has been set to a non-default value. These properties cannot be used together.
/// </exception>
[Obsolete(Obsoletions.JsonSerializerOptionsIgnoreNullValuesMessage, DiagnosticId = Obsoletions.JsonSerializerOptionsIgnoreNullValuesDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool IgnoreNullValues
{
get
{
return _ignoreNullValues;
}
set
{
VerifyMutable();
if (value && _defaultIgnoreCondition != JsonIgnoreCondition.Never)
{
throw new InvalidOperationException(SR.DefaultIgnoreConditionAlreadySpecified);
}
_ignoreNullValues = value;
}
}
/// <summary>
/// Specifies a condition to determine when properties with default values are ignored during serialization or deserialization.
/// The default value is <see cref="JsonIgnoreCondition.Never" />.
/// </summary>
/// <exception cref="ArgumentException">
/// Thrown if this property is set to <see cref="JsonIgnoreCondition.Always"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred,
/// or <see cref="IgnoreNullValues"/> has been set to <see langword="true"/>. These properties cannot be used together.
/// </exception>
public JsonIgnoreCondition DefaultIgnoreCondition
{
get
{
return _defaultIgnoreCondition;
}
set
{
VerifyMutable();
if (value == JsonIgnoreCondition.Always)
{
throw new ArgumentException(SR.DefaultIgnoreConditionInvalid);
}
if (value != JsonIgnoreCondition.Never && _ignoreNullValues)
{
throw new InvalidOperationException(SR.DefaultIgnoreConditionAlreadySpecified);
}
_defaultIgnoreCondition = value;
}
}
/// <summary>
/// Specifies how number types should be handled when serializing or deserializing.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public JsonNumberHandling NumberHandling
{
get => _numberHandling;
set
{
VerifyMutable();
if (!JsonSerializer.IsValidNumberHandlingValue(value))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_numberHandling = value;
}
}
/// <summary>
/// Determines whether read-only properties are ignored during serialization.
/// A property is read-only if it contains a public getter but not a public setter.
/// The default value is false.
/// </summary>
/// <remarks>
/// Read-only properties are not deserialized regardless of this setting.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IgnoreReadOnlyProperties
{
get
{
return _ignoreReadOnlyProperties;
}
set
{
VerifyMutable();
_ignoreReadOnlyProperties = value;
}
}
/// <summary>
/// Determines whether read-only fields are ignored during serialization.
/// A field is read-only if it is marked with the <c>readonly</c> keyword.
/// The default value is false.
/// </summary>
/// <remarks>
/// Read-only fields are not deserialized regardless of this setting.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IgnoreReadOnlyFields
{
get
{
return _ignoreReadonlyFields;
}
set
{
VerifyMutable();
_ignoreReadonlyFields = value;
}
}
/// <summary>
/// Determines whether fields are handled on serialization and deserialization.
/// The default value is false.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IncludeFields
{
get
{
return _includeFields;
}
set
{
VerifyMutable();
_includeFields = value;
}
}
/// <summary>
/// Gets or sets the maximum depth allowed when serializing or deserializing JSON, with the default (i.e. 0) indicating a max depth of 64.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the max depth is set to a negative value.
/// </exception>
/// <remarks>
/// Going past this depth will throw a <exception cref="JsonException"/>.
/// </remarks>
public int MaxDepth
{
get => _maxDepth;
set
{
VerifyMutable();
if (value < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException_MaxDepthMustBePositive(nameof(value));
}
_maxDepth = value;
EffectiveMaxDepth = (value == 0 ? DefaultMaxDepth : value);
}
}
internal int EffectiveMaxDepth { get; private set; } = DefaultMaxDepth;
/// <summary>
/// Specifies the policy used to convert a property's name on an object to another format, such as camel-casing.
/// The resulting property name is expected to match the JSON payload during deserialization, and
/// will be used when writing the property name during serialization.
/// </summary>
/// <remarks>
/// The policy is not used for properties that have a <see cref="JsonPropertyNameAttribute"/> applied.
/// This property can be set to <see cref="JsonNamingPolicy.CamelCase"/> to specify a camel-casing policy.
/// </remarks>
public JsonNamingPolicy? PropertyNamingPolicy
{
get
{
return _jsonPropertyNamingPolicy;
}
set
{
VerifyMutable();
_jsonPropertyNamingPolicy = value;
}
}
/// <summary>
/// Determines whether a property's name uses a case-insensitive comparison during deserialization.
/// The default value is false.
/// </summary>
/// <remarks>There is a performance cost associated when the value is true.</remarks>
public bool PropertyNameCaseInsensitive
{
get
{
return _propertyNameCaseInsensitive;
}
set
{
VerifyMutable();
_propertyNameCaseInsensitive = value;
}
}
/// <summary>
/// Defines how the comments are handled during deserialization.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the comment handling enum is set to a value that is not supported (or not within the <see cref="JsonCommentHandling"/> enum range).
/// </exception>
/// <remarks>
/// By default <exception cref="JsonException"/> is thrown if a comment is encountered.
/// </remarks>
public JsonCommentHandling ReadCommentHandling
{
get
{
return _readCommentHandling;
}
set
{
VerifyMutable();
Debug.Assert(value >= 0);
if (value > JsonCommentHandling.Skip)
throw new ArgumentOutOfRangeException(nameof(value), SR.JsonSerializerDoesNotSupportComments);
_readCommentHandling = value;
}
}
/// <summary>
/// Defines how deserializing a type declared as an <see cref="object"/> is handled during deserialization.
/// </summary>
public JsonUnknownTypeHandling UnknownTypeHandling
{
get => _unknownTypeHandling;
set
{
VerifyMutable();
_unknownTypeHandling = value;
}
}
/// <summary>
/// Defines whether JSON should pretty print which includes:
/// indenting nested JSON tokens, adding new lines, and adding white space between property names and values.
/// By default, the JSON is serialized without any extra white space.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool WriteIndented
{
get
{
return _writeIndented;
}
set
{
VerifyMutable();
_writeIndented = value;
}
}
/// <summary>
/// Configures how object references are handled when reading and writing JSON.
/// </summary>
public ReferenceHandler? ReferenceHandler
{
get => _referenceHandler;
set
{
VerifyMutable();
_referenceHandler = value;
ReferenceHandlingStrategy = value?.HandlingStrategy ?? ReferenceHandlingStrategy.None;
}
}
internal JsonSerializerContext? JsonSerializerContext
{
get => _serializerContext;
set
{
VerifyMutable();
_serializerContext = value;
}
}
// The cached value used to determine if ReferenceHandler should use Preserve or IgnoreCycles semanitcs or None of them.
internal ReferenceHandlingStrategy ReferenceHandlingStrategy = ReferenceHandlingStrategy.None;
internal MemberAccessor MemberAccessorStrategy
{
get
{
if (_memberAccessorStrategy == null)
{
#if NETCOREAPP
// if dynamic code isn't supported, fallback to reflection
_memberAccessorStrategy = RuntimeFeature.IsDynamicCodeSupported ?
new ReflectionEmitCachingMemberAccessor() :
new ReflectionMemberAccessor();
#elif NETFRAMEWORK
_memberAccessorStrategy = new ReflectionEmitCachingMemberAccessor();
#else
_memberAccessorStrategy = new ReflectionMemberAccessor();
#endif
}
return _memberAccessorStrategy;
}
}
/// <summary>
/// Whether the options instance has been primed for reflection-based serialization.
/// </summary>
internal bool IsInitializedForReflectionSerializer { get; private set; }
/// <summary>
/// Initializes the converters for the reflection-based serializer.
/// <seealso cref="InitializeForReflectionSerializer"/> must be checked before calling.
/// </summary>
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
internal void InitializeForReflectionSerializer()
{
RootReflectionSerializerDependencies();
IsInitializedForReflectionSerializer = true;
if (_cachingContext != null)
{
_cachingContext.Options.IsInitializedForReflectionSerializer = true;
}
}
private JsonTypeInfo GetJsonTypeInfoFromContextOrCreate(Type type)
{
JsonTypeInfo? info = _serializerContext?.GetTypeInfo(type);
if (info != null)
{
return info;
}
if (!IsInitializedForReflectionSerializer)
{
ThrowHelper.ThrowNotSupportedException_NoMetadataForType(type);
return null!;
}
Debug.Assert(s_typeInfoCreationFunc != null);
return s_typeInfoCreationFunc(type, this);
}
internal JsonDocumentOptions GetDocumentOptions()
{
return new JsonDocumentOptions
{
AllowTrailingCommas = AllowTrailingCommas,
CommentHandling = ReadCommentHandling,
MaxDepth = MaxDepth
};
}
internal JsonNodeOptions GetNodeOptions()
{
return new JsonNodeOptions
{
PropertyNameCaseInsensitive = PropertyNameCaseInsensitive
};
}
internal JsonReaderOptions GetReaderOptions()
{
return new JsonReaderOptions
{
AllowTrailingCommas = AllowTrailingCommas,
CommentHandling = ReadCommentHandling,
MaxDepth = EffectiveMaxDepth
};
}
internal JsonWriterOptions GetWriterOptions()
{
return new JsonWriterOptions
{
Encoder = Encoder,
Indented = WriteIndented,
MaxDepth = EffectiveMaxDepth,
#if !DEBUG
SkipValidation = true
#endif
};
}
internal void VerifyMutable()
{
if (_cachingContext != null || _serializerContext != null)
{
ThrowHelper.ThrowInvalidOperationException_SerializerOptionsImmutable(_serializerContext);
}
}
private static JsonSerializerOptions CreateDefaultImmutableInstance()
{
var options = new JsonSerializerOptions();
options.InitializeCachingContext(); // eagerly initialize caching context to close type for modification.
return options;
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Text.Json.Serialization.Metadata
{
public partial class JsonTypeInfo
{
/// <summary>
/// Cached typeof(object). It is faster to cache this than to call typeof(object) multiple times.
/// </summary>
internal static readonly Type ObjectType = typeof(object);
// The length of the property name embedded in the key (in bytes).
// The key is a ulong (8 bytes) containing the first 7 bytes of the property name
// followed by a byte representing the length.
private const int PropertyNameKeyLength = 7;
// The limit to how many constructor parameter names from the JSON are cached in _parameterRefsSorted before using _parameterCache.
private const int ParameterNameCountCacheThreshold = 32;
// The limit to how many property names from the JSON are cached in _propertyRefsSorted before using PropertyCache.
private const int PropertyNameCountCacheThreshold = 64;
// The number of parameters the deserialization constructor has. If this is not equal to ParameterCache.Count, this means
// that not all parameters are bound to object properties, and an exception will be thrown if deserialization is attempted.
internal int ParameterCount { get; private set; }
// All of the serializable parameters on a POCO constructor keyed on parameter name.
// Only parameters which bind to properties are cached.
internal JsonPropertyDictionary<JsonParameterInfo>? ParameterCache;
// All of the serializable properties on a POCO (except the optional extension property) keyed on property name.
internal JsonPropertyDictionary<JsonPropertyInfo>? PropertyCache;
// Fast cache of constructor parameters by first JSON ordering; may not contain all parameters. Accessed before ParameterCache.
// Use an array (instead of List<T>) for highest performance.
private volatile ParameterRef[]? _parameterRefsSorted;
// Fast cache of properties by first JSON ordering; may not contain all properties. Accessed before PropertyCache.
// Use an array (instead of List<T>) for highest performance.
private volatile PropertyRef[]? _propertyRefsSorted;
internal Func<JsonSerializerContext, JsonPropertyInfo[]>? PropInitFunc;
internal Func<JsonParameterInfoValues[]>? CtorParamInitFunc;
internal static JsonPropertyInfo AddProperty(
MemberInfo memberInfo,
Type memberType,
Type parentClassType,
bool isVirtual,
JsonNumberHandling? parentTypeNumberHandling,
JsonSerializerOptions options)
{
JsonIgnoreCondition? ignoreCondition = JsonPropertyInfo.GetAttribute<JsonIgnoreAttribute>(memberInfo)?.Condition;
if (ignoreCondition == JsonIgnoreCondition.Always)
{
return JsonPropertyInfo.CreateIgnoredPropertyPlaceholder(memberInfo, memberType, isVirtual, options);
}
JsonConverter converter = GetConverter(
memberType,
parentClassType,
memberInfo,
options);
return CreateProperty(
declaredPropertyType: memberType,
memberInfo,
parentClassType,
isVirtual,
converter,
options,
parentTypeNumberHandling,
ignoreCondition);
}
internal static JsonPropertyInfo CreateProperty(
Type declaredPropertyType,
MemberInfo? memberInfo,
Type parentClassType,
bool isVirtual,
JsonConverter converter,
JsonSerializerOptions options,
JsonNumberHandling? parentTypeNumberHandling = null,
JsonIgnoreCondition? ignoreCondition = null)
{
// Create the JsonPropertyInfo instance.
JsonPropertyInfo jsonPropertyInfo = converter.CreateJsonPropertyInfo();
jsonPropertyInfo.Initialize(
parentClassType,
declaredPropertyType,
converterStrategy: converter.ConverterStrategy,
memberInfo,
isVirtual,
converter,
ignoreCondition,
parentTypeNumberHandling,
options);
return jsonPropertyInfo;
}
/// <summary>
/// Create a <see cref="JsonPropertyInfo"/> for a given Type.
/// See <seealso cref="PropertyInfoForTypeInfo"/>.
/// </summary>
internal static JsonPropertyInfo CreatePropertyInfoForTypeInfo(
Type declaredPropertyType,
JsonConverter converter,
JsonNumberHandling? numberHandling,
JsonSerializerOptions options)
{
JsonPropertyInfo jsonPropertyInfo = CreateProperty(
declaredPropertyType: declaredPropertyType,
memberInfo: null, // Not a real property so this is null.
parentClassType: ObjectType, // a dummy value (not used)
isVirtual: false,
converter,
options,
parentTypeNumberHandling: numberHandling);
Debug.Assert(jsonPropertyInfo.IsForTypeInfo);
return jsonPropertyInfo;
}
// AggressiveInlining used although a large method it is only called from one location and is on a hot path.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal JsonPropertyInfo GetProperty(
ReadOnlySpan<byte> propertyName,
ref ReadStackFrame frame,
out byte[] utf8PropertyName)
{
PropertyRef propertyRef;
ulong key = GetKey(propertyName);
// Keep a local copy of the cache in case it changes by another thread.
PropertyRef[]? localPropertyRefsSorted = _propertyRefsSorted;
// If there is an existing cache, then use it.
if (localPropertyRefsSorted != null)
{
// Start with the current property index, and then go forwards\backwards.
int propertyIndex = frame.PropertyIndex;
int count = localPropertyRefsSorted.Length;
int iForward = Math.Min(propertyIndex, count);
int iBackward = iForward - 1;
while (true)
{
if (iForward < count)
{
propertyRef = localPropertyRefsSorted[iForward];
if (IsPropertyRefEqual(propertyRef, propertyName, key))
{
utf8PropertyName = propertyRef.NameFromJson;
return propertyRef.Info;
}
++iForward;
if (iBackward >= 0)
{
propertyRef = localPropertyRefsSorted[iBackward];
if (IsPropertyRefEqual(propertyRef, propertyName, key))
{
utf8PropertyName = propertyRef.NameFromJson;
return propertyRef.Info;
}
--iBackward;
}
}
else if (iBackward >= 0)
{
propertyRef = localPropertyRefsSorted[iBackward];
if (IsPropertyRefEqual(propertyRef, propertyName, key))
{
utf8PropertyName = propertyRef.NameFromJson;
return propertyRef.Info;
}
--iBackward;
}
else
{
// Property was not found.
break;
}
}
}
// No cached item was found. Try the main dictionary which has all of the properties.
Debug.Assert(PropertyCache != null);
if (PropertyCache.TryGetValue(JsonHelpers.Utf8GetString(propertyName), out JsonPropertyInfo? info))
{
Debug.Assert(info != null);
if (Options.PropertyNameCaseInsensitive)
{
if (propertyName.SequenceEqual(info.NameAsUtf8Bytes))
{
Debug.Assert(key == GetKey(info.NameAsUtf8Bytes.AsSpan()));
// Use the existing byte[] reference instead of creating another one.
utf8PropertyName = info.NameAsUtf8Bytes!;
}
else
{
// Make a copy of the original Span.
utf8PropertyName = propertyName.ToArray();
}
}
else
{
Debug.Assert(key == GetKey(info.NameAsUtf8Bytes.AsSpan()));
utf8PropertyName = info.NameAsUtf8Bytes;
}
}
else
{
info = JsonPropertyInfo.s_missingProperty;
// Make a copy of the original Span.
utf8PropertyName = propertyName.ToArray();
}
// Check if we should add this to the cache.
// Only cache up to a threshold length and then just use the dictionary when an item is not found in the cache.
int cacheCount = 0;
if (localPropertyRefsSorted != null)
{
cacheCount = localPropertyRefsSorted.Length;
}
// Do a quick check for the stable (after warm-up) case.
if (cacheCount < PropertyNameCountCacheThreshold)
{
// Do a slower check for the warm-up case.
if (frame.PropertyRefCache != null)
{
cacheCount += frame.PropertyRefCache.Count;
}
// Check again to append the cache up to the threshold.
if (cacheCount < PropertyNameCountCacheThreshold)
{
if (frame.PropertyRefCache == null)
{
frame.PropertyRefCache = new List<PropertyRef>();
}
Debug.Assert(info != null);
propertyRef = new PropertyRef(key, info, utf8PropertyName);
frame.PropertyRefCache.Add(propertyRef);
}
}
return info;
}
// AggressiveInlining used although a large method it is only called from one location and is on a hot path.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal JsonParameterInfo? GetParameter(
ReadOnlySpan<byte> propertyName,
ref ReadStackFrame frame,
out byte[] utf8PropertyName)
{
ParameterRef parameterRef;
ulong key = GetKey(propertyName);
// Keep a local copy of the cache in case it changes by another thread.
ParameterRef[]? localParameterRefsSorted = _parameterRefsSorted;
// If there is an existing cache, then use it.
if (localParameterRefsSorted != null)
{
// Start with the current parameter index, and then go forwards\backwards.
int parameterIndex = frame.CtorArgumentState!.ParameterIndex;
int count = localParameterRefsSorted.Length;
int iForward = Math.Min(parameterIndex, count);
int iBackward = iForward - 1;
while (true)
{
if (iForward < count)
{
parameterRef = localParameterRefsSorted[iForward];
if (IsParameterRefEqual(parameterRef, propertyName, key))
{
utf8PropertyName = parameterRef.NameFromJson;
return parameterRef.Info;
}
++iForward;
if (iBackward >= 0)
{
parameterRef = localParameterRefsSorted[iBackward];
if (IsParameterRefEqual(parameterRef, propertyName, key))
{
utf8PropertyName = parameterRef.NameFromJson;
return parameterRef.Info;
}
--iBackward;
}
}
else if (iBackward >= 0)
{
parameterRef = localParameterRefsSorted[iBackward];
if (IsParameterRefEqual(parameterRef, propertyName, key))
{
utf8PropertyName = parameterRef.NameFromJson;
return parameterRef.Info;
}
--iBackward;
}
else
{
// Property was not found.
break;
}
}
}
// No cached item was found. Try the main dictionary which has all of the parameters.
Debug.Assert(ParameterCache != null);
if (ParameterCache.TryGetValue(JsonHelpers.Utf8GetString(propertyName), out JsonParameterInfo? info))
{
Debug.Assert(info != null);
if (Options.PropertyNameCaseInsensitive)
{
if (propertyName.SequenceEqual(info.NameAsUtf8Bytes))
{
Debug.Assert(key == GetKey(info.NameAsUtf8Bytes.AsSpan()));
// Use the existing byte[] reference instead of creating another one.
utf8PropertyName = info.NameAsUtf8Bytes!;
}
else
{
// Make a copy of the original Span.
utf8PropertyName = propertyName.ToArray();
}
}
else
{
Debug.Assert(key == GetKey(info.NameAsUtf8Bytes!.AsSpan()));
utf8PropertyName = info.NameAsUtf8Bytes!;
}
}
else
{
Debug.Assert(info == null);
// Make a copy of the original Span.
utf8PropertyName = propertyName.ToArray();
}
// Check if we should add this to the cache.
// Only cache up to a threshold length and then just use the dictionary when an item is not found in the cache.
int cacheCount = 0;
if (localParameterRefsSorted != null)
{
cacheCount = localParameterRefsSorted.Length;
}
// Do a quick check for the stable (after warm-up) case.
if (cacheCount < ParameterNameCountCacheThreshold)
{
// Do a slower check for the warm-up case.
if (frame.CtorArgumentState!.ParameterRefCache != null)
{
cacheCount += frame.CtorArgumentState.ParameterRefCache.Count;
}
// Check again to append the cache up to the threshold.
if (cacheCount < ParameterNameCountCacheThreshold)
{
if (frame.CtorArgumentState.ParameterRefCache == null)
{
frame.CtorArgumentState.ParameterRefCache = new List<ParameterRef>();
}
parameterRef = new ParameterRef(key, info!, utf8PropertyName);
frame.CtorArgumentState.ParameterRefCache.Add(parameterRef);
}
}
return info;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsPropertyRefEqual(in PropertyRef propertyRef, ReadOnlySpan<byte> propertyName, ulong key)
{
if (key == propertyRef.Key)
{
// We compare the whole name, although we could skip the first 7 bytes (but it's not any faster)
if (propertyName.Length <= PropertyNameKeyLength ||
propertyName.SequenceEqual(propertyRef.NameFromJson))
{
return true;
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsParameterRefEqual(in ParameterRef parameterRef, ReadOnlySpan<byte> parameterName, ulong key)
{
if (key == parameterRef.Key)
{
// We compare the whole name, although we could skip the first 7 bytes (but it's not any faster)
if (parameterName.Length <= PropertyNameKeyLength ||
parameterName.SequenceEqual(parameterRef.NameFromJson))
{
return true;
}
}
return false;
}
/// <summary>
/// Get a key from the property name.
/// The key consists of the first 7 bytes of the property name and then the length.
/// </summary>
// AggressiveInlining used since this method is only called from two locations and is on a hot path.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static ulong GetKey(ReadOnlySpan<byte> name)
{
ulong key;
ref byte reference = ref MemoryMarshal.GetReference(name);
int length = name.Length;
if (length > 7)
{
key = Unsafe.ReadUnaligned<ulong>(ref reference) & 0x00ffffffffffffffL;
key |= (ulong)Math.Min(length, 0xff) << 56;
}
else
{
key =
length > 5 ? Unsafe.ReadUnaligned<uint>(ref reference) | (ulong)Unsafe.ReadUnaligned<ushort>(ref Unsafe.Add(ref reference, 4)) << 32 :
length > 3 ? Unsafe.ReadUnaligned<uint>(ref reference) :
length > 1 ? Unsafe.ReadUnaligned<ushort>(ref reference) : 0UL;
key |= (ulong)length << 56;
if ((length & 1) != 0)
{
var offset = length - 1;
key |= (ulong)Unsafe.Add(ref reference, offset) << (offset * 8);
}
}
#if DEBUG
// Verify key contains the embedded bytes as expected.
// Note: the expected properties do not hold true on big-endian platforms
if (BitConverter.IsLittleEndian)
{
const int BitsInByte = 8;
Debug.Assert(
// Verify embedded property name.
(name.Length < 1 || name[0] == ((key & ((ulong)0xFF << BitsInByte * 0)) >> BitsInByte * 0)) &&
(name.Length < 2 || name[1] == ((key & ((ulong)0xFF << BitsInByte * 1)) >> BitsInByte * 1)) &&
(name.Length < 3 || name[2] == ((key & ((ulong)0xFF << BitsInByte * 2)) >> BitsInByte * 2)) &&
(name.Length < 4 || name[3] == ((key & ((ulong)0xFF << BitsInByte * 3)) >> BitsInByte * 3)) &&
(name.Length < 5 || name[4] == ((key & ((ulong)0xFF << BitsInByte * 4)) >> BitsInByte * 4)) &&
(name.Length < 6 || name[5] == ((key & ((ulong)0xFF << BitsInByte * 5)) >> BitsInByte * 5)) &&
(name.Length < 7 || name[6] == ((key & ((ulong)0xFF << BitsInByte * 6)) >> BitsInByte * 6)) &&
// Verify embedded length.
(name.Length >= 0xFF || (key & ((ulong)0xFF << BitsInByte * 7)) >> BitsInByte * 7 == (ulong)name.Length) &&
(name.Length < 0xFF || (key & ((ulong)0xFF << BitsInByte * 7)) >> BitsInByte * 7 == 0xFF));
}
#endif
return key;
}
internal void UpdateSortedPropertyCache(ref ReadStackFrame frame)
{
Debug.Assert(frame.PropertyRefCache != null);
// frame.PropertyRefCache is only read\written by a single thread -- the thread performing
// the deserialization for a given object instance.
List<PropertyRef> listToAppend = frame.PropertyRefCache;
// _propertyRefsSorted can be accessed by multiple threads, so replace the reference when
// appending to it. No lock() is necessary.
if (_propertyRefsSorted != null)
{
List<PropertyRef> replacementList = new List<PropertyRef>(_propertyRefsSorted);
Debug.Assert(replacementList.Count <= PropertyNameCountCacheThreshold);
// Verify replacementList will not become too large.
while (replacementList.Count + listToAppend.Count > PropertyNameCountCacheThreshold)
{
// This code path is rare; keep it simple by using RemoveAt() instead of RemoveRange() which requires calculating index\count.
listToAppend.RemoveAt(listToAppend.Count - 1);
}
// Add the new items; duplicates are possible but that is tolerated during property lookup.
replacementList.AddRange(listToAppend);
_propertyRefsSorted = replacementList.ToArray();
}
else
{
_propertyRefsSorted = listToAppend.ToArray();
}
frame.PropertyRefCache = null;
}
internal void UpdateSortedParameterCache(ref ReadStackFrame frame)
{
Debug.Assert(frame.CtorArgumentState!.ParameterRefCache != null);
// frame.PropertyRefCache is only read\written by a single thread -- the thread performing
// the deserialization for a given object instance.
List<ParameterRef> listToAppend = frame.CtorArgumentState.ParameterRefCache;
// _parameterRefsSorted can be accessed by multiple threads, so replace the reference when
// appending to it. No lock() is necessary.
if (_parameterRefsSorted != null)
{
List<ParameterRef> replacementList = new List<ParameterRef>(_parameterRefsSorted);
Debug.Assert(replacementList.Count <= ParameterNameCountCacheThreshold);
// Verify replacementList will not become too large.
while (replacementList.Count + listToAppend.Count > ParameterNameCountCacheThreshold)
{
// This code path is rare; keep it simple by using RemoveAt() instead of RemoveRange() which requires calculating index\count.
listToAppend.RemoveAt(listToAppend.Count - 1);
}
// Add the new items; duplicates are possible but that is tolerated during property lookup.
replacementList.AddRange(listToAppend);
_parameterRefsSorted = replacementList.ToArray();
}
else
{
_parameterRefsSorted = listToAppend.ToArray();
}
frame.CtorArgumentState.ParameterRefCache = null;
}
internal void InitializePropCache()
{
Debug.Assert(PropertyCache == null);
Debug.Assert(PropertyInfoForTypeInfo.ConverterStrategy == ConverterStrategy.Object);
JsonSerializerContext? context = Options._serializerContext;
Debug.Assert(context != null);
JsonPropertyInfo[] array;
if (PropInitFunc == null || (array = PropInitFunc(context)) == null)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(context, Type);
return;
}
Dictionary<string, JsonPropertyInfo>? ignoredMembers = null;
JsonPropertyDictionary<JsonPropertyInfo> propertyCache = new(Options.PropertyNameCaseInsensitive, array.Length);
for (int i = 0; i < array.Length; i++)
{
JsonPropertyInfo jsonPropertyInfo = array[i];
bool hasJsonInclude = jsonPropertyInfo.SrcGen_HasJsonInclude;
if (!jsonPropertyInfo.SrcGen_IsPublic)
{
if (hasJsonInclude)
{
ThrowHelper.ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(jsonPropertyInfo.ClrName!, jsonPropertyInfo.DeclaringType);
}
continue;
}
if (jsonPropertyInfo.MemberType == MemberTypes.Field && !hasJsonInclude && !Options.IncludeFields)
{
continue;
}
if (jsonPropertyInfo.SrcGen_IsExtensionData)
{
// Source generator compile-time type inspection has performed this validation for us.
Debug.Assert(DataExtensionProperty == null);
Debug.Assert(IsValidDataExtensionProperty(jsonPropertyInfo));
DataExtensionProperty = jsonPropertyInfo;
continue;
}
CacheMember(jsonPropertyInfo, propertyCache, ref ignoredMembers);
}
// Avoid threading issues by populating a local cache and assigning it to the global cache after completion.
PropertyCache = propertyCache;
}
internal void InitializeParameterCache()
{
Debug.Assert(ParameterCache == null);
Debug.Assert(PropertyCache != null);
Debug.Assert(PropertyInfoForTypeInfo.ConverterStrategy == ConverterStrategy.Object);
JsonSerializerContext? context = Options._serializerContext;
Debug.Assert(context != null);
JsonParameterInfoValues[] array;
if (CtorParamInitFunc == null || (array = CtorParamInitFunc()) == null)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeCtorParams(context, Type);
return;
}
InitializeConstructorParameters(array, sourceGenMode: true);
Debug.Assert(ParameterCache != null);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Text.Json.Serialization.Metadata
{
public partial class JsonTypeInfo
{
/// <summary>
/// Cached typeof(object). It is faster to cache this than to call typeof(object) multiple times.
/// </summary>
internal static readonly Type ObjectType = typeof(object);
// The length of the property name embedded in the key (in bytes).
// The key is a ulong (8 bytes) containing the first 7 bytes of the property name
// followed by a byte representing the length.
private const int PropertyNameKeyLength = 7;
// The limit to how many constructor parameter names from the JSON are cached in _parameterRefsSorted before using _parameterCache.
private const int ParameterNameCountCacheThreshold = 32;
// The limit to how many property names from the JSON are cached in _propertyRefsSorted before using PropertyCache.
private const int PropertyNameCountCacheThreshold = 64;
// The number of parameters the deserialization constructor has. If this is not equal to ParameterCache.Count, this means
// that not all parameters are bound to object properties, and an exception will be thrown if deserialization is attempted.
internal int ParameterCount { get; private set; }
// All of the serializable parameters on a POCO constructor keyed on parameter name.
// Only parameters which bind to properties are cached.
internal JsonPropertyDictionary<JsonParameterInfo>? ParameterCache;
// All of the serializable properties on a POCO (except the optional extension property) keyed on property name.
internal JsonPropertyDictionary<JsonPropertyInfo>? PropertyCache;
// Fast cache of constructor parameters by first JSON ordering; may not contain all parameters. Accessed before ParameterCache.
// Use an array (instead of List<T>) for highest performance.
private volatile ParameterRef[]? _parameterRefsSorted;
// Fast cache of properties by first JSON ordering; may not contain all properties. Accessed before PropertyCache.
// Use an array (instead of List<T>) for highest performance.
private volatile PropertyRef[]? _propertyRefsSorted;
internal Func<JsonSerializerContext, JsonPropertyInfo[]>? PropInitFunc;
internal Func<JsonParameterInfoValues[]>? CtorParamInitFunc;
internal static JsonPropertyInfo AddProperty(
MemberInfo memberInfo,
Type memberType,
Type parentClassType,
bool isVirtual,
JsonNumberHandling? parentTypeNumberHandling,
JsonSerializerOptions options)
{
JsonIgnoreCondition? ignoreCondition = JsonPropertyInfo.GetAttribute<JsonIgnoreAttribute>(memberInfo)?.Condition;
if (ignoreCondition == JsonIgnoreCondition.Always)
{
return JsonPropertyInfo.CreateIgnoredPropertyPlaceholder(memberInfo, memberType, isVirtual, options);
}
JsonConverter converter = GetConverter(
memberType,
parentClassType,
memberInfo,
options);
return CreateProperty(
declaredPropertyType: memberType,
memberInfo,
parentClassType,
isVirtual,
converter,
options,
parentTypeNumberHandling,
ignoreCondition);
}
internal static JsonPropertyInfo CreateProperty(
Type declaredPropertyType,
MemberInfo? memberInfo,
Type parentClassType,
bool isVirtual,
JsonConverter converter,
JsonSerializerOptions options,
JsonNumberHandling? parentTypeNumberHandling = null,
JsonIgnoreCondition? ignoreCondition = null)
{
// Create the JsonPropertyInfo instance.
JsonPropertyInfo jsonPropertyInfo = converter.CreateJsonPropertyInfo();
jsonPropertyInfo.Initialize(
parentClassType,
declaredPropertyType,
converterStrategy: converter.ConverterStrategy,
memberInfo,
isVirtual,
converter,
ignoreCondition,
parentTypeNumberHandling,
options);
return jsonPropertyInfo;
}
/// <summary>
/// Create a <see cref="JsonPropertyInfo"/> for a given Type.
/// See <seealso cref="PropertyInfoForTypeInfo"/>.
/// </summary>
internal static JsonPropertyInfo CreatePropertyInfoForTypeInfo(
Type declaredPropertyType,
JsonConverter converter,
JsonNumberHandling? numberHandling,
JsonSerializerOptions options)
{
JsonPropertyInfo jsonPropertyInfo = CreateProperty(
declaredPropertyType: declaredPropertyType,
memberInfo: null, // Not a real property so this is null.
parentClassType: ObjectType, // a dummy value (not used)
isVirtual: false,
converter,
options,
parentTypeNumberHandling: numberHandling);
Debug.Assert(jsonPropertyInfo.IsForTypeInfo);
return jsonPropertyInfo;
}
// AggressiveInlining used although a large method it is only called from one location and is on a hot path.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal JsonPropertyInfo GetProperty(
ReadOnlySpan<byte> propertyName,
ref ReadStackFrame frame,
out byte[] utf8PropertyName)
{
PropertyRef propertyRef;
ulong key = GetKey(propertyName);
// Keep a local copy of the cache in case it changes by another thread.
PropertyRef[]? localPropertyRefsSorted = _propertyRefsSorted;
// If there is an existing cache, then use it.
if (localPropertyRefsSorted != null)
{
// Start with the current property index, and then go forwards\backwards.
int propertyIndex = frame.PropertyIndex;
int count = localPropertyRefsSorted.Length;
int iForward = Math.Min(propertyIndex, count);
int iBackward = iForward - 1;
while (true)
{
if (iForward < count)
{
propertyRef = localPropertyRefsSorted[iForward];
if (IsPropertyRefEqual(propertyRef, propertyName, key))
{
utf8PropertyName = propertyRef.NameFromJson;
return propertyRef.Info;
}
++iForward;
if (iBackward >= 0)
{
propertyRef = localPropertyRefsSorted[iBackward];
if (IsPropertyRefEqual(propertyRef, propertyName, key))
{
utf8PropertyName = propertyRef.NameFromJson;
return propertyRef.Info;
}
--iBackward;
}
}
else if (iBackward >= 0)
{
propertyRef = localPropertyRefsSorted[iBackward];
if (IsPropertyRefEqual(propertyRef, propertyName, key))
{
utf8PropertyName = propertyRef.NameFromJson;
return propertyRef.Info;
}
--iBackward;
}
else
{
// Property was not found.
break;
}
}
}
// No cached item was found. Try the main dictionary which has all of the properties.
Debug.Assert(PropertyCache != null);
if (PropertyCache.TryGetValue(JsonHelpers.Utf8GetString(propertyName), out JsonPropertyInfo? info))
{
Debug.Assert(info != null);
if (Options.PropertyNameCaseInsensitive)
{
if (propertyName.SequenceEqual(info.NameAsUtf8Bytes))
{
Debug.Assert(key == GetKey(info.NameAsUtf8Bytes.AsSpan()));
// Use the existing byte[] reference instead of creating another one.
utf8PropertyName = info.NameAsUtf8Bytes!;
}
else
{
// Make a copy of the original Span.
utf8PropertyName = propertyName.ToArray();
}
}
else
{
Debug.Assert(key == GetKey(info.NameAsUtf8Bytes.AsSpan()));
utf8PropertyName = info.NameAsUtf8Bytes;
}
}
else
{
info = JsonPropertyInfo.s_missingProperty;
// Make a copy of the original Span.
utf8PropertyName = propertyName.ToArray();
}
// Check if we should add this to the cache.
// Only cache up to a threshold length and then just use the dictionary when an item is not found in the cache.
int cacheCount = 0;
if (localPropertyRefsSorted != null)
{
cacheCount = localPropertyRefsSorted.Length;
}
// Do a quick check for the stable (after warm-up) case.
if (cacheCount < PropertyNameCountCacheThreshold)
{
// Do a slower check for the warm-up case.
if (frame.PropertyRefCache != null)
{
cacheCount += frame.PropertyRefCache.Count;
}
// Check again to append the cache up to the threshold.
if (cacheCount < PropertyNameCountCacheThreshold)
{
if (frame.PropertyRefCache == null)
{
frame.PropertyRefCache = new List<PropertyRef>();
}
Debug.Assert(info != null);
propertyRef = new PropertyRef(key, info, utf8PropertyName);
frame.PropertyRefCache.Add(propertyRef);
}
}
return info;
}
// AggressiveInlining used although a large method it is only called from one location and is on a hot path.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal JsonParameterInfo? GetParameter(
ReadOnlySpan<byte> propertyName,
ref ReadStackFrame frame,
out byte[] utf8PropertyName)
{
ParameterRef parameterRef;
ulong key = GetKey(propertyName);
// Keep a local copy of the cache in case it changes by another thread.
ParameterRef[]? localParameterRefsSorted = _parameterRefsSorted;
// If there is an existing cache, then use it.
if (localParameterRefsSorted != null)
{
// Start with the current parameter index, and then go forwards\backwards.
int parameterIndex = frame.CtorArgumentState!.ParameterIndex;
int count = localParameterRefsSorted.Length;
int iForward = Math.Min(parameterIndex, count);
int iBackward = iForward - 1;
while (true)
{
if (iForward < count)
{
parameterRef = localParameterRefsSorted[iForward];
if (IsParameterRefEqual(parameterRef, propertyName, key))
{
utf8PropertyName = parameterRef.NameFromJson;
return parameterRef.Info;
}
++iForward;
if (iBackward >= 0)
{
parameterRef = localParameterRefsSorted[iBackward];
if (IsParameterRefEqual(parameterRef, propertyName, key))
{
utf8PropertyName = parameterRef.NameFromJson;
return parameterRef.Info;
}
--iBackward;
}
}
else if (iBackward >= 0)
{
parameterRef = localParameterRefsSorted[iBackward];
if (IsParameterRefEqual(parameterRef, propertyName, key))
{
utf8PropertyName = parameterRef.NameFromJson;
return parameterRef.Info;
}
--iBackward;
}
else
{
// Property was not found.
break;
}
}
}
// No cached item was found. Try the main dictionary which has all of the parameters.
Debug.Assert(ParameterCache != null);
if (ParameterCache.TryGetValue(JsonHelpers.Utf8GetString(propertyName), out JsonParameterInfo? info))
{
Debug.Assert(info != null);
if (Options.PropertyNameCaseInsensitive)
{
if (propertyName.SequenceEqual(info.NameAsUtf8Bytes))
{
Debug.Assert(key == GetKey(info.NameAsUtf8Bytes.AsSpan()));
// Use the existing byte[] reference instead of creating another one.
utf8PropertyName = info.NameAsUtf8Bytes!;
}
else
{
// Make a copy of the original Span.
utf8PropertyName = propertyName.ToArray();
}
}
else
{
Debug.Assert(key == GetKey(info.NameAsUtf8Bytes!.AsSpan()));
utf8PropertyName = info.NameAsUtf8Bytes!;
}
}
else
{
Debug.Assert(info == null);
// Make a copy of the original Span.
utf8PropertyName = propertyName.ToArray();
}
// Check if we should add this to the cache.
// Only cache up to a threshold length and then just use the dictionary when an item is not found in the cache.
int cacheCount = 0;
if (localParameterRefsSorted != null)
{
cacheCount = localParameterRefsSorted.Length;
}
// Do a quick check for the stable (after warm-up) case.
if (cacheCount < ParameterNameCountCacheThreshold)
{
// Do a slower check for the warm-up case.
if (frame.CtorArgumentState!.ParameterRefCache != null)
{
cacheCount += frame.CtorArgumentState.ParameterRefCache.Count;
}
// Check again to append the cache up to the threshold.
if (cacheCount < ParameterNameCountCacheThreshold)
{
if (frame.CtorArgumentState.ParameterRefCache == null)
{
frame.CtorArgumentState.ParameterRefCache = new List<ParameterRef>();
}
parameterRef = new ParameterRef(key, info!, utf8PropertyName);
frame.CtorArgumentState.ParameterRefCache.Add(parameterRef);
}
}
return info;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsPropertyRefEqual(in PropertyRef propertyRef, ReadOnlySpan<byte> propertyName, ulong key)
{
if (key == propertyRef.Key)
{
// We compare the whole name, although we could skip the first 7 bytes (but it's not any faster)
if (propertyName.Length <= PropertyNameKeyLength ||
propertyName.SequenceEqual(propertyRef.NameFromJson))
{
return true;
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsParameterRefEqual(in ParameterRef parameterRef, ReadOnlySpan<byte> parameterName, ulong key)
{
if (key == parameterRef.Key)
{
// We compare the whole name, although we could skip the first 7 bytes (but it's not any faster)
if (parameterName.Length <= PropertyNameKeyLength ||
parameterName.SequenceEqual(parameterRef.NameFromJson))
{
return true;
}
}
return false;
}
/// <summary>
/// Get a key from the property name.
/// The key consists of the first 7 bytes of the property name and then the length.
/// </summary>
// AggressiveInlining used since this method is only called from two locations and is on a hot path.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static ulong GetKey(ReadOnlySpan<byte> name)
{
ulong key;
ref byte reference = ref MemoryMarshal.GetReference(name);
int length = name.Length;
if (length > 7)
{
key = Unsafe.ReadUnaligned<ulong>(ref reference) & 0x00ffffffffffffffL;
key |= (ulong)Math.Min(length, 0xff) << 56;
}
else
{
key =
length > 5 ? Unsafe.ReadUnaligned<uint>(ref reference) | (ulong)Unsafe.ReadUnaligned<ushort>(ref Unsafe.Add(ref reference, 4)) << 32 :
length > 3 ? Unsafe.ReadUnaligned<uint>(ref reference) :
length > 1 ? Unsafe.ReadUnaligned<ushort>(ref reference) : 0UL;
key |= (ulong)length << 56;
if ((length & 1) != 0)
{
var offset = length - 1;
key |= (ulong)Unsafe.Add(ref reference, offset) << (offset * 8);
}
}
#if DEBUG
// Verify key contains the embedded bytes as expected.
// Note: the expected properties do not hold true on big-endian platforms
if (BitConverter.IsLittleEndian)
{
const int BitsInByte = 8;
Debug.Assert(
// Verify embedded property name.
(name.Length < 1 || name[0] == ((key & ((ulong)0xFF << BitsInByte * 0)) >> BitsInByte * 0)) &&
(name.Length < 2 || name[1] == ((key & ((ulong)0xFF << BitsInByte * 1)) >> BitsInByte * 1)) &&
(name.Length < 3 || name[2] == ((key & ((ulong)0xFF << BitsInByte * 2)) >> BitsInByte * 2)) &&
(name.Length < 4 || name[3] == ((key & ((ulong)0xFF << BitsInByte * 3)) >> BitsInByte * 3)) &&
(name.Length < 5 || name[4] == ((key & ((ulong)0xFF << BitsInByte * 4)) >> BitsInByte * 4)) &&
(name.Length < 6 || name[5] == ((key & ((ulong)0xFF << BitsInByte * 5)) >> BitsInByte * 5)) &&
(name.Length < 7 || name[6] == ((key & ((ulong)0xFF << BitsInByte * 6)) >> BitsInByte * 6)) &&
// Verify embedded length.
(name.Length >= 0xFF || (key & ((ulong)0xFF << BitsInByte * 7)) >> BitsInByte * 7 == (ulong)name.Length) &&
(name.Length < 0xFF || (key & ((ulong)0xFF << BitsInByte * 7)) >> BitsInByte * 7 == 0xFF));
}
#endif
return key;
}
internal void UpdateSortedPropertyCache(ref ReadStackFrame frame)
{
Debug.Assert(frame.PropertyRefCache != null);
// frame.PropertyRefCache is only read\written by a single thread -- the thread performing
// the deserialization for a given object instance.
List<PropertyRef> listToAppend = frame.PropertyRefCache;
// _propertyRefsSorted can be accessed by multiple threads, so replace the reference when
// appending to it. No lock() is necessary.
if (_propertyRefsSorted != null)
{
List<PropertyRef> replacementList = new List<PropertyRef>(_propertyRefsSorted);
Debug.Assert(replacementList.Count <= PropertyNameCountCacheThreshold);
// Verify replacementList will not become too large.
while (replacementList.Count + listToAppend.Count > PropertyNameCountCacheThreshold)
{
// This code path is rare; keep it simple by using RemoveAt() instead of RemoveRange() which requires calculating index\count.
listToAppend.RemoveAt(listToAppend.Count - 1);
}
// Add the new items; duplicates are possible but that is tolerated during property lookup.
replacementList.AddRange(listToAppend);
_propertyRefsSorted = replacementList.ToArray();
}
else
{
_propertyRefsSorted = listToAppend.ToArray();
}
frame.PropertyRefCache = null;
}
internal void UpdateSortedParameterCache(ref ReadStackFrame frame)
{
Debug.Assert(frame.CtorArgumentState!.ParameterRefCache != null);
// frame.PropertyRefCache is only read\written by a single thread -- the thread performing
// the deserialization for a given object instance.
List<ParameterRef> listToAppend = frame.CtorArgumentState.ParameterRefCache;
// _parameterRefsSorted can be accessed by multiple threads, so replace the reference when
// appending to it. No lock() is necessary.
if (_parameterRefsSorted != null)
{
List<ParameterRef> replacementList = new List<ParameterRef>(_parameterRefsSorted);
Debug.Assert(replacementList.Count <= ParameterNameCountCacheThreshold);
// Verify replacementList will not become too large.
while (replacementList.Count + listToAppend.Count > ParameterNameCountCacheThreshold)
{
// This code path is rare; keep it simple by using RemoveAt() instead of RemoveRange() which requires calculating index\count.
listToAppend.RemoveAt(listToAppend.Count - 1);
}
// Add the new items; duplicates are possible but that is tolerated during property lookup.
replacementList.AddRange(listToAppend);
_parameterRefsSorted = replacementList.ToArray();
}
else
{
_parameterRefsSorted = listToAppend.ToArray();
}
frame.CtorArgumentState.ParameterRefCache = null;
}
internal void InitializePropCache()
{
Debug.Assert(PropertyCache == null);
Debug.Assert(PropertyInfoForTypeInfo.ConverterStrategy == ConverterStrategy.Object);
JsonSerializerContext? context = Options.JsonSerializerContext;
Debug.Assert(context != null);
JsonPropertyInfo[] array;
if (PropInitFunc == null || (array = PropInitFunc(context)) == null)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(context, Type);
return;
}
Dictionary<string, JsonPropertyInfo>? ignoredMembers = null;
JsonPropertyDictionary<JsonPropertyInfo> propertyCache = new(Options.PropertyNameCaseInsensitive, array.Length);
for (int i = 0; i < array.Length; i++)
{
JsonPropertyInfo jsonPropertyInfo = array[i];
bool hasJsonInclude = jsonPropertyInfo.SrcGen_HasJsonInclude;
if (!jsonPropertyInfo.SrcGen_IsPublic)
{
if (hasJsonInclude)
{
ThrowHelper.ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(jsonPropertyInfo.ClrName!, jsonPropertyInfo.DeclaringType);
}
continue;
}
if (jsonPropertyInfo.MemberType == MemberTypes.Field && !hasJsonInclude && !Options.IncludeFields)
{
continue;
}
if (jsonPropertyInfo.SrcGen_IsExtensionData)
{
// Source generator compile-time type inspection has performed this validation for us.
Debug.Assert(DataExtensionProperty == null);
Debug.Assert(IsValidDataExtensionProperty(jsonPropertyInfo));
DataExtensionProperty = jsonPropertyInfo;
continue;
}
CacheMember(jsonPropertyInfo, propertyCache, ref ignoredMembers);
}
// Avoid threading issues by populating a local cache and assigning it to the global cache after completion.
PropertyCache = propertyCache;
}
internal void InitializeParameterCache()
{
Debug.Assert(ParameterCache == null);
Debug.Assert(PropertyCache != null);
Debug.Assert(PropertyInfoForTypeInfo.ConverterStrategy == ConverterStrategy.Object);
JsonSerializerContext? context = Options.JsonSerializerContext;
Debug.Assert(context != null);
JsonParameterInfoValues[] array;
if (CtorParamInitFunc == null || (array = CtorParamInitFunc()) == null)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeCtorParams(context, Type);
return;
}
InitializeConstructorParameters(array, sourceGenMode: true);
Debug.Assert(ParameterCache != null);
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Serialization.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
internal static partial class ThrowHelper
{
[DoesNotReturn]
public static void ThrowArgumentException_DeserializeWrongType(Type type, object value)
{
throw new ArgumentException(SR.Format(SR.DeserializeWrongType, type, value.GetType()));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType)
{
throw new NotSupportedException(SR.Format(SR.SerializationNotSupportedType, propertyType));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType)
{
throw new NotSupportedException(SR.Format(SR.TypeRequiresAsyncSerialization, propertyType));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_ConstructorMaxOf64Parameters(Type type)
{
throw new NotSupportedException(SR.Format(SR.ConstructorMaxOf64Parameters, type));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter)
{
throw new NotSupportedException(SR.Format(SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType()));
}
[DoesNotReturn]
public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
{
throw new JsonException(SR.Format(SR.DeserializeUnableToConvertValue, propertyType)) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType)
{
throw new InvalidCastException(SR.Format(SR.DeserializeUnableToAssignValue, typeOfValue, declaredType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType)
{
throw new InvalidOperationException(SR.Format(SR.DeserializeUnableToAssignNull, declaredType));
}
[DoesNotReturn]
public static void ThrowJsonException_SerializationConverterRead(JsonConverter? converter)
{
throw new JsonException(SR.Format(SR.SerializationConverterRead, converter)) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowJsonException_SerializationConverterWrite(JsonConverter? converter)
{
throw new JsonException(SR.Format(SR.SerializationConverterWrite, converter)) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowJsonException_SerializerCycleDetected(int maxDepth)
{
throw new JsonException(SR.Format(SR.SerializerCycleDetected, maxDepth)) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowJsonException(string? message = null)
{
throw new JsonException(message) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type type, Type? parentClassType, MemberInfo? memberInfo)
{
if (parentClassType == null)
{
Debug.Assert(memberInfo == null);
throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidType, type));
}
Debug.Assert(memberInfo != null);
throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidMember, type, memberInfo.Name, parentClassType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type)
{
throw new InvalidOperationException(SR.Format(SR.SerializationConverterNotCompatible, converterType, type));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo? memberInfo)
{
string location = classType.ToString();
if (memberInfo != null)
{
location += $".{memberInfo.Name}";
}
throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeInvalid, location));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo? memberInfo, Type typeToConvert)
{
string location = classTypeAttributeIsOn.ToString();
if (memberInfo != null)
{
location += $".{memberInfo.Name}";
}
throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeNotCompatible, location, typeToConvert));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerOptionsImmutable(JsonSerializerContext? context)
{
string message = context == null
? SR.SerializerOptionsImmutable
: SR.SerializerContextOptionsImmutable;
throw new InvalidOperationException(message);
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, JsonPropertyInfo jsonPropertyInfo)
{
throw new InvalidOperationException(SR.Format(SR.SerializerPropertyNameConflict, type, jsonPropertyInfo.ClrName));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerPropertyNameNull(Type parentType, JsonPropertyInfo jsonPropertyInfo)
{
throw new InvalidOperationException(SR.Format(SR.SerializerPropertyNameNull, parentType, jsonPropertyInfo.MemberInfo?.Name));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy)
{
throw new InvalidOperationException(SR.Format(SR.NamingPolicyReturnNull, namingPolicy));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType)
{
throw new InvalidOperationException(SR.Format(SR.SerializerConverterFactoryReturnsNull, converterType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsJsonConverterFactorty(Type converterType)
{
throw new InvalidOperationException(SR.Format(SR.SerializerConverterFactoryReturnsJsonConverterFactory, converterType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters(
Type parentType,
string parameterName,
string firstMatchName,
string secondMatchName)
{
throw new InvalidOperationException(
SR.Format(
SR.MultipleMembersBindWithConstructorParameter,
firstMatchName,
secondMatchName,
parentType,
parameterName));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)
{
throw new InvalidOperationException(SR.Format(SR.ConstructorParamIncompleteBinding, parentType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(JsonPropertyInfo jsonPropertyInfo)
{
throw new InvalidOperationException(SR.Format(SR.ExtensionDataCannotBindToCtorParam, jsonPropertyInfo.ClrName, jsonPropertyInfo.DeclaringType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(string memberName, Type declaringType)
{
throw new InvalidOperationException(SR.Format(SR.JsonIncludeOnNonPublicInvalid, memberName, declaringType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(string clrPropertyName, Type propertyDeclaringType)
{
throw new InvalidOperationException(SR.Format(SR.IgnoreConditionOnValueTypeInvalid, clrPropertyName, propertyDeclaringType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo)
{
MemberInfo? memberInfo = jsonPropertyInfo.MemberInfo;
Debug.Assert(memberInfo != null);
Debug.Assert(!jsonPropertyInfo.IsForTypeInfo);
throw new InvalidOperationException(SR.Format(SR.NumberHandlingOnPropertyInvalid, memberInfo.Name, memberInfo.DeclaringType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(Type runtimePropertyType, JsonConverter jsonConverter)
{
throw new InvalidOperationException(SR.Format(SR.ConverterCanConvertMultipleTypes, jsonConverter.GetType(), jsonConverter.TypeToConvert, runtimePropertyType));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(
ReadOnlySpan<byte> propertyName,
ref Utf8JsonReader reader,
ref ReadStack state)
{
state.Current.JsonPropertyName = propertyName.ToArray();
NotSupportedException ex = new NotSupportedException(
SR.Format(SR.ObjectWithParameterizedCtorRefMetadataNotHonored, state.Current.JsonTypeInfo.Type));
ThrowNotSupportedException(ref state, reader, ex);
}
[DoesNotReturn]
public static void ReThrowWithPath(ref ReadStack state, JsonReaderException ex)
{
Debug.Assert(ex.Path == null);
string path = state.JsonPath();
string message = ex.Message;
// Insert the "Path" portion before "LineNumber" and "BytePositionInLine".
#if BUILDING_INBOX_LIBRARY
int iPos = message.AsSpan().LastIndexOf(" LineNumber: ");
#else
int iPos = message.LastIndexOf(" LineNumber: ", StringComparison.InvariantCulture);
#endif
if (iPos >= 0)
{
message = $"{message.Substring(0, iPos)} Path: {path} |{message.Substring(iPos)}";
}
else
{
message += $" Path: {path}.";
}
throw new JsonException(message, path, ex.LineNumber, ex.BytePositionInLine, ex);
}
[DoesNotReturn]
public static void ReThrowWithPath(ref ReadStack state, in Utf8JsonReader reader, Exception ex)
{
JsonException jsonException = new JsonException(null, ex);
AddJsonExceptionInformation(ref state, reader, jsonException);
throw jsonException;
}
public static void AddJsonExceptionInformation(ref ReadStack state, in Utf8JsonReader reader, JsonException ex)
{
Debug.Assert(ex.Path is null); // do not overwrite existing path information
long lineNumber = reader.CurrentState._lineNumber;
ex.LineNumber = lineNumber;
long bytePositionInLine = reader.CurrentState._bytePositionInLine;
ex.BytePositionInLine = bytePositionInLine;
string path = state.JsonPath();
ex.Path = path;
string? message = ex._message;
if (string.IsNullOrEmpty(message))
{
// Use a default message.
Type propertyType = state.Current.JsonTypeInfo.Type;
message = SR.Format(SR.DeserializeUnableToConvertValue, propertyType);
ex.AppendPathInformation = true;
}
if (ex.AppendPathInformation)
{
message += $" Path: {path} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}.";
ex.SetMessage(message);
}
}
[DoesNotReturn]
public static void ReThrowWithPath(ref WriteStack state, Exception ex)
{
JsonException jsonException = new JsonException(null, ex);
AddJsonExceptionInformation(ref state, jsonException);
throw jsonException;
}
public static void AddJsonExceptionInformation(ref WriteStack state, JsonException ex)
{
Debug.Assert(ex.Path is null); // do not overwrite existing path information
string path = state.PropertyPath();
ex.Path = path;
string? message = ex._message;
if (string.IsNullOrEmpty(message))
{
// Use a default message.
message = SR.Format(SR.SerializeUnableToSerialize);
ex.AppendPathInformation = true;
}
if (ex.AppendPathInformation)
{
message += $" Path: {path}.";
ex.SetMessage(message);
}
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationDuplicateAttribute(Type attribute, Type classType, MemberInfo? memberInfo)
{
string location = classType.ToString();
if (memberInfo != null)
{
location += $".{memberInfo.Name}";
}
throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateAttribute, attribute, location));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType, Type attribute)
{
throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateTypeAttribute, classType, attribute));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute<TAttribute>(Type classType)
{
throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateTypeAttribute, classType, typeof(TAttribute)));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(Type type, JsonPropertyInfo jsonPropertyInfo)
{
throw new InvalidOperationException(SR.Format(SR.SerializationDataExtensionPropertyInvalid, type, jsonPropertyInfo.MemberInfo?.Name));
}
[DoesNotReturn]
public static void ThrowNotSupportedException(ref ReadStack state, in Utf8JsonReader reader, NotSupportedException ex)
{
string message = ex.Message;
// The caller should check to ensure path is not already set.
Debug.Assert(!message.Contains(" Path: "));
// Obtain the type to show in the message.
Type propertyType = state.Current.JsonTypeInfo.Type;
if (!message.Contains(propertyType.ToString()))
{
if (message.Length > 0)
{
message += " ";
}
message += SR.Format(SR.SerializationNotSupportedParentType, propertyType);
}
long lineNumber = reader.CurrentState._lineNumber;
long bytePositionInLine = reader.CurrentState._bytePositionInLine;
message += $" Path: {state.JsonPath()} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}.";
throw new NotSupportedException(message, ex);
}
[DoesNotReturn]
public static void ThrowNotSupportedException(ref WriteStack state, NotSupportedException ex)
{
string message = ex.Message;
// The caller should check to ensure path is not already set.
Debug.Assert(!message.Contains(" Path: "));
// Obtain the type to show in the message.
Type propertyType = state.Current.JsonTypeInfo.Type;
if (!message.Contains(propertyType.ToString()))
{
if (message.Length > 0)
{
message += " ";
}
message += SR.Format(SR.SerializationNotSupportedParentType, propertyType);
}
message += $" Path: {state.PropertyPath()}.";
throw new NotSupportedException(message, ex);
}
[DoesNotReturn]
public static void ThrowNotSupportedException_DeserializeNoConstructor(Type type, ref Utf8JsonReader reader, ref ReadStack state)
{
string message;
if (type.IsInterface)
{
message = SR.Format(SR.DeserializePolymorphicInterface, type);
}
else
{
message = SR.Format(SR.DeserializeNoConstructor, nameof(JsonConstructorAttribute), type);
}
ThrowNotSupportedException(ref state, reader, new NotSupportedException(message));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_CannotPopulateCollection(Type type, ref Utf8JsonReader reader, ref ReadStack state)
{
ThrowNotSupportedException(ref state, reader, new NotSupportedException(SR.Format(SR.CannotPopulateCollection, type)));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataValuesInvalidToken(JsonTokenType tokenType)
{
ThrowJsonException(SR.Format(SR.MetadataInvalidTokenAfterValues, tokenType));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataReferenceNotFound(string id)
{
ThrowJsonException(SR.Format(SR.MetadataReferenceNotFound, id));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataValueWasNotString(JsonTokenType tokenType)
{
ThrowJsonException(SR.Format(SR.MetadataValueWasNotString, tokenType));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataValueWasNotString(JsonValueKind valueKind)
{
ThrowJsonException(SR.Format(SR.MetadataValueWasNotString, valueKind));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(ReadOnlySpan<byte> propertyName, ref ReadStack state)
{
state.Current.JsonPropertyName = propertyName.ToArray();
ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties();
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties()
{
ThrowJsonException(SR.MetadataReferenceCannotContainOtherProperties);
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataIdIsNotFirstProperty(ReadOnlySpan<byte> propertyName, ref ReadStack state)
{
state.Current.JsonPropertyName = propertyName.ToArray();
ThrowJsonException(SR.MetadataIdIsNotFirstProperty);
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataMissingIdBeforeValues(ref ReadStack state, ReadOnlySpan<byte> propertyName)
{
state.Current.JsonPropertyName = propertyName.ToArray();
ThrowJsonException(SR.MetadataPreservedArrayPropertyNotFound);
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(ReadOnlySpan<byte> propertyName, ref ReadStack state, in Utf8JsonReader reader)
{
// Set PropertyInfo or KeyName to write down the conflicting property name in JsonException.Path
if (state.Current.IsProcessingDictionary())
{
state.Current.JsonPropertyNameAsString = reader.GetString();
}
else
{
state.Current.JsonPropertyName = propertyName.ToArray();
}
ThrowJsonException(SR.MetadataInvalidPropertyWithLeadingDollarSign);
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataDuplicateIdFound(string id)
{
ThrowJsonException(SR.Format(SR.MetadataDuplicateIdFound, id));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataInvalidReferenceToValueType(Type propertyType)
{
ThrowJsonException(SR.Format(SR.MetadataInvalidReferenceToValueType, propertyType));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref ReadStack state, Type propertyType, in Utf8JsonReader reader)
{
state.Current.JsonPropertyName = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray();
string propertyNameAsString = reader.GetString()!;
ThrowJsonException(SR.Format(SR.MetadataPreservedArrayFailed,
SR.Format(SR.MetadataPreservedArrayInvalidProperty, propertyNameAsString),
SR.Format(SR.DeserializeUnableToConvertValue, propertyType)));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref ReadStack state, Type propertyType)
{
// Missing $values, JSON path should point to the property's object.
state.Current.JsonPropertyName = null;
ThrowJsonException(SR.Format(SR.MetadataPreservedArrayFailed,
SR.MetadataPreservedArrayPropertyNotFound,
SR.Format(SR.DeserializeUnableToConvertValue, propertyType)));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(Type propertyType)
{
ThrowJsonException(SR.Format(SR.MetadataCannotParsePreservedObjectToImmutable, propertyType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(string referenceId, Type currentType, Type typeToConvert)
{
throw new InvalidOperationException(SR.Format(SR.MetadataReferenceOfTypeCannotBeAssignedToType, referenceId, currentType, typeToConvert));
}
[DoesNotReturn]
internal static void ThrowUnexpectedMetadataException(
ReadOnlySpan<byte> propertyName,
ref Utf8JsonReader reader,
ref ReadStack state)
{
if (state.Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase.ConstructorIsParameterized)
{
ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(propertyName, ref reader, ref state);
}
MetadataPropertyName name = JsonSerializer.GetMetadataPropertyName(propertyName);
if (name == MetadataPropertyName.Id)
{
ThrowJsonException_MetadataIdIsNotFirstProperty(propertyName, ref state);
}
else if (name == MetadataPropertyName.Ref)
{
ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(propertyName, ref state);
}
else
{
ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(propertyName, ref state, reader);
}
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_JsonSerializerOptionsAlreadyBoundToContext()
{
throw new InvalidOperationException(SR.Format(SR.OptionsAlreadyBoundToContext));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_BuiltInConvertersNotRooted(Type type)
{
throw new NotSupportedException(SR.Format(SR.BuiltInConvertersNotRooted, type));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_NoMetadataForType(Type type)
{
throw new NotSupportedException(SR.Format(SR.NoMetadataForType, type));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_NoMetadataForType(Type type)
{
throw new InvalidOperationException(SR.Format(SR.NoMetadataForType, type));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_MetadatInitFuncsNull()
{
throw new InvalidOperationException(SR.Format(SR.MetadataInitFuncsNull));
}
public static void ThrowInvalidOperationException_NoMetadataForTypeProperties(JsonSerializerContext context, Type type)
{
throw new InvalidOperationException(SR.Format(SR.NoMetadataForTypeProperties, context.GetType(), type));
}
public static void ThrowInvalidOperationException_NoMetadataForTypeCtorParams(JsonSerializerContext context, Type type)
{
throw new InvalidOperationException(SR.Format(SR.NoMetadataForTypeCtorParams, context.GetType(), type));
}
public static void ThrowInvalidOperationException_NoDefaultOptionsForContext(JsonSerializerContext context, Type type)
{
throw new InvalidOperationException(SR.Format(SR.NoDefaultOptionsForContext, context.GetType(), type));
}
[DoesNotReturn]
public static void ThrowMissingMemberException_MissingFSharpCoreMember(string missingFsharpCoreMember)
{
throw new MissingMemberException(SR.Format(SR.MissingFSharpCoreMember, missingFsharpCoreMember));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
internal static partial class ThrowHelper
{
[DoesNotReturn]
public static void ThrowArgumentException_DeserializeWrongType(Type type, object value)
{
throw new ArgumentException(SR.Format(SR.DeserializeWrongType, type, value.GetType()));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType)
{
throw new NotSupportedException(SR.Format(SR.SerializationNotSupportedType, propertyType));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType)
{
throw new NotSupportedException(SR.Format(SR.TypeRequiresAsyncSerialization, propertyType));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_ConstructorMaxOf64Parameters(Type type)
{
throw new NotSupportedException(SR.Format(SR.ConstructorMaxOf64Parameters, type));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter)
{
throw new NotSupportedException(SR.Format(SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType()));
}
[DoesNotReturn]
public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
{
throw new JsonException(SR.Format(SR.DeserializeUnableToConvertValue, propertyType)) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType)
{
throw new InvalidCastException(SR.Format(SR.DeserializeUnableToAssignValue, typeOfValue, declaredType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType)
{
throw new InvalidOperationException(SR.Format(SR.DeserializeUnableToAssignNull, declaredType));
}
[DoesNotReturn]
public static void ThrowJsonException_SerializationConverterRead(JsonConverter? converter)
{
throw new JsonException(SR.Format(SR.SerializationConverterRead, converter)) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowJsonException_SerializationConverterWrite(JsonConverter? converter)
{
throw new JsonException(SR.Format(SR.SerializationConverterWrite, converter)) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowJsonException_SerializerCycleDetected(int maxDepth)
{
throw new JsonException(SR.Format(SR.SerializerCycleDetected, maxDepth)) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowJsonException(string? message = null)
{
throw new JsonException(message) { AppendPathInformation = true };
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type type, Type? parentClassType, MemberInfo? memberInfo)
{
if (parentClassType == null)
{
Debug.Assert(memberInfo == null);
throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidType, type));
}
Debug.Assert(memberInfo != null);
throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidMember, type, memberInfo.Name, parentClassType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type)
{
throw new InvalidOperationException(SR.Format(SR.SerializationConverterNotCompatible, converterType, type));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo? memberInfo)
{
string location = classType.ToString();
if (memberInfo != null)
{
location += $".{memberInfo.Name}";
}
throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeInvalid, location));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo? memberInfo, Type typeToConvert)
{
string location = classTypeAttributeIsOn.ToString();
if (memberInfo != null)
{
location += $".{memberInfo.Name}";
}
throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeNotCompatible, location, typeToConvert));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerOptionsImmutable(JsonSerializerContext? context)
{
string message = context == null
? SR.SerializerOptionsImmutable
: SR.SerializerContextOptionsImmutable;
throw new InvalidOperationException(message);
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, JsonPropertyInfo jsonPropertyInfo)
{
throw new InvalidOperationException(SR.Format(SR.SerializerPropertyNameConflict, type, jsonPropertyInfo.ClrName));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerPropertyNameNull(Type parentType, JsonPropertyInfo jsonPropertyInfo)
{
throw new InvalidOperationException(SR.Format(SR.SerializerPropertyNameNull, parentType, jsonPropertyInfo.MemberInfo?.Name));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy)
{
throw new InvalidOperationException(SR.Format(SR.NamingPolicyReturnNull, namingPolicy));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType)
{
throw new InvalidOperationException(SR.Format(SR.SerializerConverterFactoryReturnsNull, converterType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsJsonConverterFactorty(Type converterType)
{
throw new InvalidOperationException(SR.Format(SR.SerializerConverterFactoryReturnsJsonConverterFactory, converterType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters(
Type parentType,
string parameterName,
string firstMatchName,
string secondMatchName)
{
throw new InvalidOperationException(
SR.Format(
SR.MultipleMembersBindWithConstructorParameter,
firstMatchName,
secondMatchName,
parentType,
parameterName));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)
{
throw new InvalidOperationException(SR.Format(SR.ConstructorParamIncompleteBinding, parentType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(JsonPropertyInfo jsonPropertyInfo)
{
throw new InvalidOperationException(SR.Format(SR.ExtensionDataCannotBindToCtorParam, jsonPropertyInfo.ClrName, jsonPropertyInfo.DeclaringType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(string memberName, Type declaringType)
{
throw new InvalidOperationException(SR.Format(SR.JsonIncludeOnNonPublicInvalid, memberName, declaringType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(string clrPropertyName, Type propertyDeclaringType)
{
throw new InvalidOperationException(SR.Format(SR.IgnoreConditionOnValueTypeInvalid, clrPropertyName, propertyDeclaringType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo)
{
MemberInfo? memberInfo = jsonPropertyInfo.MemberInfo;
Debug.Assert(memberInfo != null);
Debug.Assert(!jsonPropertyInfo.IsForTypeInfo);
throw new InvalidOperationException(SR.Format(SR.NumberHandlingOnPropertyInvalid, memberInfo.Name, memberInfo.DeclaringType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(Type runtimePropertyType, JsonConverter jsonConverter)
{
throw new InvalidOperationException(SR.Format(SR.ConverterCanConvertMultipleTypes, jsonConverter.GetType(), jsonConverter.TypeToConvert, runtimePropertyType));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(
ReadOnlySpan<byte> propertyName,
ref Utf8JsonReader reader,
ref ReadStack state)
{
state.Current.JsonPropertyName = propertyName.ToArray();
NotSupportedException ex = new NotSupportedException(
SR.Format(SR.ObjectWithParameterizedCtorRefMetadataNotHonored, state.Current.JsonTypeInfo.Type));
ThrowNotSupportedException(ref state, reader, ex);
}
[DoesNotReturn]
public static void ReThrowWithPath(ref ReadStack state, JsonReaderException ex)
{
Debug.Assert(ex.Path == null);
string path = state.JsonPath();
string message = ex.Message;
// Insert the "Path" portion before "LineNumber" and "BytePositionInLine".
#if BUILDING_INBOX_LIBRARY
int iPos = message.AsSpan().LastIndexOf(" LineNumber: ");
#else
int iPos = message.LastIndexOf(" LineNumber: ", StringComparison.InvariantCulture);
#endif
if (iPos >= 0)
{
message = $"{message.Substring(0, iPos)} Path: {path} |{message.Substring(iPos)}";
}
else
{
message += $" Path: {path}.";
}
throw new JsonException(message, path, ex.LineNumber, ex.BytePositionInLine, ex);
}
[DoesNotReturn]
public static void ReThrowWithPath(ref ReadStack state, in Utf8JsonReader reader, Exception ex)
{
JsonException jsonException = new JsonException(null, ex);
AddJsonExceptionInformation(ref state, reader, jsonException);
throw jsonException;
}
public static void AddJsonExceptionInformation(ref ReadStack state, in Utf8JsonReader reader, JsonException ex)
{
Debug.Assert(ex.Path is null); // do not overwrite existing path information
long lineNumber = reader.CurrentState._lineNumber;
ex.LineNumber = lineNumber;
long bytePositionInLine = reader.CurrentState._bytePositionInLine;
ex.BytePositionInLine = bytePositionInLine;
string path = state.JsonPath();
ex.Path = path;
string? message = ex._message;
if (string.IsNullOrEmpty(message))
{
// Use a default message.
Type propertyType = state.Current.JsonTypeInfo.Type;
message = SR.Format(SR.DeserializeUnableToConvertValue, propertyType);
ex.AppendPathInformation = true;
}
if (ex.AppendPathInformation)
{
message += $" Path: {path} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}.";
ex.SetMessage(message);
}
}
[DoesNotReturn]
public static void ReThrowWithPath(ref WriteStack state, Exception ex)
{
JsonException jsonException = new JsonException(null, ex);
AddJsonExceptionInformation(ref state, jsonException);
throw jsonException;
}
public static void AddJsonExceptionInformation(ref WriteStack state, JsonException ex)
{
Debug.Assert(ex.Path is null); // do not overwrite existing path information
string path = state.PropertyPath();
ex.Path = path;
string? message = ex._message;
if (string.IsNullOrEmpty(message))
{
// Use a default message.
message = SR.Format(SR.SerializeUnableToSerialize);
ex.AppendPathInformation = true;
}
if (ex.AppendPathInformation)
{
message += $" Path: {path}.";
ex.SetMessage(message);
}
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationDuplicateAttribute(Type attribute, Type classType, MemberInfo? memberInfo)
{
string location = classType.ToString();
if (memberInfo != null)
{
location += $".{memberInfo.Name}";
}
throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateAttribute, attribute, location));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType, Type attribute)
{
throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateTypeAttribute, classType, attribute));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute<TAttribute>(Type classType)
{
throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateTypeAttribute, classType, typeof(TAttribute)));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(Type type, JsonPropertyInfo jsonPropertyInfo)
{
throw new InvalidOperationException(SR.Format(SR.SerializationDataExtensionPropertyInvalid, type, jsonPropertyInfo.MemberInfo?.Name));
}
[DoesNotReturn]
public static void ThrowNotSupportedException(ref ReadStack state, in Utf8JsonReader reader, NotSupportedException ex)
{
string message = ex.Message;
// The caller should check to ensure path is not already set.
Debug.Assert(!message.Contains(" Path: "));
// Obtain the type to show in the message.
Type propertyType = state.Current.JsonTypeInfo.Type;
if (!message.Contains(propertyType.ToString()))
{
if (message.Length > 0)
{
message += " ";
}
message += SR.Format(SR.SerializationNotSupportedParentType, propertyType);
}
long lineNumber = reader.CurrentState._lineNumber;
long bytePositionInLine = reader.CurrentState._bytePositionInLine;
message += $" Path: {state.JsonPath()} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}.";
throw new NotSupportedException(message, ex);
}
[DoesNotReturn]
public static void ThrowNotSupportedException(ref WriteStack state, NotSupportedException ex)
{
string message = ex.Message;
// The caller should check to ensure path is not already set.
Debug.Assert(!message.Contains(" Path: "));
// Obtain the type to show in the message.
Type propertyType = state.Current.JsonTypeInfo.Type;
if (!message.Contains(propertyType.ToString()))
{
if (message.Length > 0)
{
message += " ";
}
message += SR.Format(SR.SerializationNotSupportedParentType, propertyType);
}
message += $" Path: {state.PropertyPath()}.";
throw new NotSupportedException(message, ex);
}
[DoesNotReturn]
public static void ThrowNotSupportedException_DeserializeNoConstructor(Type type, ref Utf8JsonReader reader, ref ReadStack state)
{
string message;
if (type.IsInterface)
{
message = SR.Format(SR.DeserializePolymorphicInterface, type);
}
else
{
message = SR.Format(SR.DeserializeNoConstructor, nameof(JsonConstructorAttribute), type);
}
ThrowNotSupportedException(ref state, reader, new NotSupportedException(message));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_CannotPopulateCollection(Type type, ref Utf8JsonReader reader, ref ReadStack state)
{
ThrowNotSupportedException(ref state, reader, new NotSupportedException(SR.Format(SR.CannotPopulateCollection, type)));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataValuesInvalidToken(JsonTokenType tokenType)
{
ThrowJsonException(SR.Format(SR.MetadataInvalidTokenAfterValues, tokenType));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataReferenceNotFound(string id)
{
ThrowJsonException(SR.Format(SR.MetadataReferenceNotFound, id));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataValueWasNotString(JsonTokenType tokenType)
{
ThrowJsonException(SR.Format(SR.MetadataValueWasNotString, tokenType));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataValueWasNotString(JsonValueKind valueKind)
{
ThrowJsonException(SR.Format(SR.MetadataValueWasNotString, valueKind));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(ReadOnlySpan<byte> propertyName, ref ReadStack state)
{
state.Current.JsonPropertyName = propertyName.ToArray();
ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties();
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties()
{
ThrowJsonException(SR.MetadataReferenceCannotContainOtherProperties);
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataIdIsNotFirstProperty(ReadOnlySpan<byte> propertyName, ref ReadStack state)
{
state.Current.JsonPropertyName = propertyName.ToArray();
ThrowJsonException(SR.MetadataIdIsNotFirstProperty);
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataMissingIdBeforeValues(ref ReadStack state, ReadOnlySpan<byte> propertyName)
{
state.Current.JsonPropertyName = propertyName.ToArray();
ThrowJsonException(SR.MetadataPreservedArrayPropertyNotFound);
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(ReadOnlySpan<byte> propertyName, ref ReadStack state, in Utf8JsonReader reader)
{
// Set PropertyInfo or KeyName to write down the conflicting property name in JsonException.Path
if (state.Current.IsProcessingDictionary())
{
state.Current.JsonPropertyNameAsString = reader.GetString();
}
else
{
state.Current.JsonPropertyName = propertyName.ToArray();
}
ThrowJsonException(SR.MetadataInvalidPropertyWithLeadingDollarSign);
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataDuplicateIdFound(string id)
{
ThrowJsonException(SR.Format(SR.MetadataDuplicateIdFound, id));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataInvalidReferenceToValueType(Type propertyType)
{
ThrowJsonException(SR.Format(SR.MetadataInvalidReferenceToValueType, propertyType));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref ReadStack state, Type propertyType, in Utf8JsonReader reader)
{
state.Current.JsonPropertyName = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray();
string propertyNameAsString = reader.GetString()!;
ThrowJsonException(SR.Format(SR.MetadataPreservedArrayFailed,
SR.Format(SR.MetadataPreservedArrayInvalidProperty, propertyNameAsString),
SR.Format(SR.DeserializeUnableToConvertValue, propertyType)));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref ReadStack state, Type propertyType)
{
// Missing $values, JSON path should point to the property's object.
state.Current.JsonPropertyName = null;
ThrowJsonException(SR.Format(SR.MetadataPreservedArrayFailed,
SR.MetadataPreservedArrayPropertyNotFound,
SR.Format(SR.DeserializeUnableToConvertValue, propertyType)));
}
[DoesNotReturn]
public static void ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(Type propertyType)
{
ThrowJsonException(SR.Format(SR.MetadataCannotParsePreservedObjectToImmutable, propertyType));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(string referenceId, Type currentType, Type typeToConvert)
{
throw new InvalidOperationException(SR.Format(SR.MetadataReferenceOfTypeCannotBeAssignedToType, referenceId, currentType, typeToConvert));
}
[DoesNotReturn]
internal static void ThrowUnexpectedMetadataException(
ReadOnlySpan<byte> propertyName,
ref Utf8JsonReader reader,
ref ReadStack state)
{
if (state.Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase.ConstructorIsParameterized)
{
ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(propertyName, ref reader, ref state);
}
MetadataPropertyName name = JsonSerializer.GetMetadataPropertyName(propertyName);
if (name == MetadataPropertyName.Id)
{
ThrowJsonException_MetadataIdIsNotFirstProperty(propertyName, ref state);
}
else if (name == MetadataPropertyName.Ref)
{
ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(propertyName, ref state);
}
else
{
ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(propertyName, ref state, reader);
}
}
[DoesNotReturn]
public static void ThrowNotSupportedException_BuiltInConvertersNotRooted(Type type)
{
throw new NotSupportedException(SR.Format(SR.BuiltInConvertersNotRooted, type));
}
[DoesNotReturn]
public static void ThrowNotSupportedException_NoMetadataForType(Type type)
{
throw new NotSupportedException(SR.Format(SR.NoMetadataForType, type));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_NoMetadataForType(Type type)
{
throw new InvalidOperationException(SR.Format(SR.NoMetadataForType, type));
}
[DoesNotReturn]
public static void ThrowInvalidOperationException_MetadatInitFuncsNull()
{
throw new InvalidOperationException(SR.Format(SR.MetadataInitFuncsNull));
}
public static void ThrowInvalidOperationException_NoMetadataForTypeProperties(JsonSerializerContext context, Type type)
{
throw new InvalidOperationException(SR.Format(SR.NoMetadataForTypeProperties, context.GetType(), type));
}
public static void ThrowInvalidOperationException_NoMetadataForTypeCtorParams(JsonSerializerContext context, Type type)
{
throw new InvalidOperationException(SR.Format(SR.NoMetadataForTypeCtorParams, context.GetType(), type));
}
public static void ThrowInvalidOperationException_NoDefaultOptionsForContext(JsonSerializerContext context, Type type)
{
throw new InvalidOperationException(SR.Format(SR.NoDefaultOptionsForContext, context.GetType(), type));
}
[DoesNotReturn]
public static void ThrowMissingMemberException_MissingFSharpCoreMember(string missingFsharpCoreMember)
{
throw new MissingMemberException(SR.Format(SR.MissingFSharpCoreMember, missingFsharpCoreMember));
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Reflection;
using System.Text.Json.Serialization;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Text.Json.SourceGeneration.Tests
{
public static partial class JsonSerializerContextTests
{
[Fact]
public static void VariousNestingAndVisibilityLevelsAreSupported()
{
Assert.NotNull(PublicContext.Default);
Assert.NotNull(NestedContext.Default);
Assert.NotNull(NestedPublicContext.Default);
Assert.NotNull(NestedPublicContext.NestedProtectedInternalClass.Default);
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void Converters_AndTypeInfoCreator_NotRooted_WhenMetadataNotPresent()
{
RemoteExecutor.Invoke(
() =>
{
object[] objArr = new object[] { new MyStruct() };
// Metadata not generated for MyStruct without JsonSerializableAttribute.
NotSupportedException ex = Assert.Throws<NotSupportedException>(
() => JsonSerializer.Serialize(objArr, MetadataContext.Default.ObjectArray));
string exAsStr = ex.ToString();
Assert.Contains(typeof(MyStruct).ToString(), exAsStr);
Assert.Contains("JsonSerializerOptions", exAsStr);
// This test uses reflection to:
// - Access JsonSerializerOptions.s_defaultSimpleConverters
// - Access JsonSerializerOptions.s_defaultFactoryConverters
//
// If any of them changes, this test will need to be kept in sync.
// Confirm built-in converters not set.
AssertFieldNull("s_defaultSimpleConverters", optionsInstance: null);
AssertFieldNull("s_defaultFactoryConverters", optionsInstance: null);
// Confirm type info dynamic creator not set.
AssertFieldNull("s_typeInfoCreationFunc", optionsInstance: null);
static void AssertFieldNull(string fieldName, JsonSerializerOptions? optionsInstance)
{
BindingFlags bindingFlags = BindingFlags.NonPublic | (optionsInstance == null ? BindingFlags.Static : BindingFlags.Instance);
FieldInfo fieldInfo = typeof(JsonSerializerOptions).GetField(fieldName, bindingFlags);
Assert.NotNull(fieldInfo);
Assert.Null(fieldInfo.GetValue(optionsInstance));
}
}).Dispose();
}
[Fact]
public static void SupportsPositionalRecords()
{
Person person = new(FirstName: "Jane", LastName: "Doe");
byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes(person, PersonJsonContext.Default.Person);
person = JsonSerializer.Deserialize<Person>(utf8Json, PersonJsonContext.Default.Person);
Assert.Equal("Jane", person.FirstName);
Assert.Equal("Doe", person.LastName);
}
[JsonSerializable(typeof(JsonMessage))]
internal partial class NestedContext : JsonSerializerContext { }
[JsonSerializable(typeof(JsonMessage))]
public partial class NestedPublicContext : JsonSerializerContext
{
[JsonSerializable(typeof(JsonMessage))]
protected internal partial class NestedProtectedInternalClass : JsonSerializerContext { }
}
internal record Person(string FirstName, string LastName);
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Person))]
internal partial class PersonJsonContext : JsonSerializerContext
{
}
// Regression test for https://github.com/dotnet/runtime/issues/62079
[Fact]
public static void SupportsPropertiesWithCustomConverterFactory()
{
var value = new ClassWithCustomConverterFactoryProperty { MyEnum = Serialization.Tests.SampleEnum.MinZero };
string json = JsonSerializer.Serialize(value, SingleClassWithCustomConverterFactoryPropertyContext.Default.ClassWithCustomConverterFactoryProperty);
Assert.Equal(@"{""MyEnum"":""MinZero""}", json);
}
public class ParentClass
{
public ClassWithCustomConverterFactoryProperty? Child { get; set; }
}
[JsonSerializable(typeof(ParentClass))]
internal partial class SingleClassWithCustomConverterFactoryPropertyContext : JsonSerializerContext
{
}
// Regression test for https://github.com/dotnet/runtime/issues/61860
[Fact]
public static void SupportsGenericParameterWithCustomConverterFactory()
{
var value = new List<TestEnum> { TestEnum.Cee };
string json = JsonSerializer.Serialize(value, GenericParameterWithCustomConverterFactoryContext.Default.ListTestEnum);
Assert.Equal(@"[""Cee""]", json);
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum TestEnum
{
Aye, Bee, Cee
}
[JsonSerializable(typeof(List<TestEnum>))]
internal partial class GenericParameterWithCustomConverterFactoryContext : JsonSerializerContext
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Reflection;
using System.Text.Json.Serialization;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Text.Json.SourceGeneration.Tests
{
public static partial class JsonSerializerContextTests
{
[Fact]
public static void VariousNestingAndVisibilityLevelsAreSupported()
{
Assert.NotNull(PublicContext.Default);
Assert.NotNull(NestedContext.Default);
Assert.NotNull(NestedPublicContext.Default);
Assert.NotNull(NestedPublicContext.NestedProtectedInternalClass.Default);
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void Converters_AndTypeInfoCreator_NotRooted_WhenMetadataNotPresent()
{
RemoteExecutor.Invoke(
() =>
{
object[] objArr = new object[] { new MyStruct() };
// Metadata not generated for MyStruct without JsonSerializableAttribute.
NotSupportedException ex = Assert.Throws<NotSupportedException>(
() => JsonSerializer.Serialize(objArr, MetadataContext.Default.ObjectArray));
string exAsStr = ex.ToString();
Assert.Contains(typeof(MyStruct).ToString(), exAsStr);
Assert.Contains("JsonSerializerOptions", exAsStr);
// This test uses reflection to:
// - Access JsonSerializerOptions.s_defaultSimpleConverters
// - Access JsonSerializerOptions.s_defaultFactoryConverters
// - Access JsonSerializerOptions.s_typeInfoCreationFunc
//
// If any of them changes, this test will need to be kept in sync.
// Confirm built-in converters not set.
AssertFieldNull("s_defaultSimpleConverters", optionsInstance: null);
AssertFieldNull("s_defaultFactoryConverters", optionsInstance: null);
// Confirm type info dynamic creator not set.
AssertFieldNull("s_typeInfoCreationFunc", optionsInstance: null);
static void AssertFieldNull(string fieldName, JsonSerializerOptions? optionsInstance)
{
BindingFlags bindingFlags = BindingFlags.NonPublic | (optionsInstance == null ? BindingFlags.Static : BindingFlags.Instance);
FieldInfo fieldInfo = typeof(JsonSerializerOptions).GetField(fieldName, bindingFlags);
Assert.NotNull(fieldInfo);
Assert.Null(fieldInfo.GetValue(optionsInstance));
}
}).Dispose();
}
[Fact]
public static void SupportsPositionalRecords()
{
Person person = new(FirstName: "Jane", LastName: "Doe");
byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes(person, PersonJsonContext.Default.Person);
person = JsonSerializer.Deserialize<Person>(utf8Json, PersonJsonContext.Default.Person);
Assert.Equal("Jane", person.FirstName);
Assert.Equal("Doe", person.LastName);
}
[JsonSerializable(typeof(JsonMessage))]
internal partial class NestedContext : JsonSerializerContext { }
[JsonSerializable(typeof(JsonMessage))]
public partial class NestedPublicContext : JsonSerializerContext
{
[JsonSerializable(typeof(JsonMessage))]
protected internal partial class NestedProtectedInternalClass : JsonSerializerContext { }
}
internal record Person(string FirstName, string LastName);
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Person))]
internal partial class PersonJsonContext : JsonSerializerContext
{
}
// Regression test for https://github.com/dotnet/runtime/issues/62079
[Fact]
public static void SupportsPropertiesWithCustomConverterFactory()
{
var value = new ClassWithCustomConverterFactoryProperty { MyEnum = Serialization.Tests.SampleEnum.MinZero };
string json = JsonSerializer.Serialize(value, SingleClassWithCustomConverterFactoryPropertyContext.Default.ClassWithCustomConverterFactoryProperty);
Assert.Equal(@"{""MyEnum"":""MinZero""}", json);
}
public class ParentClass
{
public ClassWithCustomConverterFactoryProperty? Child { get; set; }
}
[JsonSerializable(typeof(ParentClass))]
internal partial class SingleClassWithCustomConverterFactoryPropertyContext : JsonSerializerContext
{
}
// Regression test for https://github.com/dotnet/runtime/issues/61860
[Fact]
public static void SupportsGenericParameterWithCustomConverterFactory()
{
var value = new List<TestEnum> { TestEnum.Cee };
string json = JsonSerializer.Serialize(value, GenericParameterWithCustomConverterFactoryContext.Default.ListTestEnum);
Assert.Equal(@"[""Cee""]", json);
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum TestEnum
{
Aye, Bee, Cee
}
[JsonSerializable(typeof(List<TestEnum>))]
internal partial class GenericParameterWithCustomConverterFactoryContext : JsonSerializerContext
{
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
using Xunit;
using Microsoft.DotNet.RemoteExecutor;
namespace System.Text.Json.Serialization.Tests
{
public static class CacheTests
{
[Fact, OuterLoop]
public static async Task MultipleThreads_SameType_DifferentJson_Looping()
{
const int Iterations = 100;
for (int i = 0; i < Iterations; i++)
{
await MultipleThreads_SameType_DifferentJson();
}
}
[Fact]
public static async Task MultipleThreads_SameType_DifferentJson()
{
// Use local options to avoid obtaining already cached metadata from the default options.
var options = new JsonSerializerOptions();
// Verify the test class has >64 properties since that is a threshold for using the fallback dictionary.
Assert.True(typeof(SimpleTestClass).GetProperties(BindingFlags.Instance | BindingFlags.Public).Length > 64);
void DeserializeObjectMinimal()
{
SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(@"{""MyDecimal"" : 3.3}", options);
};
void DeserializeObjectFlipped()
{
SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(SimpleTestClass.s_json_flipped, options);
obj.Verify();
};
void DeserializeObjectNormal()
{
SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(SimpleTestClass.s_json, options);
obj.Verify();
};
void SerializeObject()
{
var obj = new SimpleTestClass();
obj.Initialize();
JsonSerializer.Serialize(obj, options);
};
const int ThreadCount = 8;
const int ConcurrentTestsCount = 4;
Task[] tasks = new Task[ThreadCount * ConcurrentTestsCount];
for (int i = 0; i < tasks.Length; i += ConcurrentTestsCount)
{
// Create race condition to populate the sorted property cache with different json ordering.
tasks[i + 0] = Task.Run(() => DeserializeObjectMinimal());
tasks[i + 1] = Task.Run(() => DeserializeObjectFlipped());
tasks[i + 2] = Task.Run(() => DeserializeObjectNormal());
// Ensure no exceptions on serialization
tasks[i + 3] = Task.Run(() => SerializeObject());
};
await Task.WhenAll(tasks);
}
[Fact, OuterLoop]
public static async Task MultipleThreads_DifferentTypes_Looping()
{
const int Iterations = 100;
for (int i = 0; i < Iterations; i++)
{
await MultipleThreads_DifferentTypes();
}
}
[Fact]
public static async Task MultipleThreads_DifferentTypes()
{
// Use local options to avoid obtaining already cached metadata from the default options.
var options = new JsonSerializerOptions();
const int TestClassCount = 2;
var testObjects = new ITestClass[TestClassCount]
{
new SimpleTestClassWithNulls(),
new SimpleTestClass(),
};
foreach (ITestClass obj in testObjects)
{
obj.Initialize();
}
void Test(int i)
{
Type testClassType = testObjects[i].GetType();
string json = JsonSerializer.Serialize(testObjects[i], testClassType, options);
ITestClass obj = (ITestClass)JsonSerializer.Deserialize(json, testClassType, options);
obj.Verify();
};
const int OuterCount = 12;
Task[] tasks = new Task[OuterCount * TestClassCount];
for (int i = 0; i < tasks.Length; i += TestClassCount)
{
tasks[i + 0] = Task.Run(() => Test(TestClassCount - 1));
tasks[i + 1] = Task.Run(() => Test(TestClassCount - 2));
}
await Task.WhenAll(tasks);
}
[Fact]
public static void PropertyCacheWithMinInputsFirst()
{
// Use local options to avoid obtaining already cached metadata from the default options.
var options = new JsonSerializerOptions();
string json = "{}";
JsonSerializer.Deserialize<SimpleTestClass>(json, options);
SimpleTestClass testObj = new SimpleTestClass();
testObj.Initialize();
testObj.Verify();
json = JsonSerializer.Serialize(testObj, options);
testObj = JsonSerializer.Deserialize<SimpleTestClass>(json, options);
testObj.Verify();
}
[Fact]
public static void PropertyCacheWithMinInputsLast()
{
// Use local options to avoid obtaining already cached metadata from the default options.
var options = new JsonSerializerOptions();
SimpleTestClass testObj = new SimpleTestClass();
testObj.Initialize();
testObj.Verify();
string json = JsonSerializer.Serialize(testObj, options);
testObj = JsonSerializer.Deserialize<SimpleTestClass>(json, options);
testObj.Verify();
json = "{}";
JsonSerializer.Deserialize<SimpleTestClass>(json, options);
}
// Use a common options instance to encourage additional metadata collisions across types. Also since
// this options is not the default options instance the tests will not use previously cached metadata.
private static JsonSerializerOptions s_options = new JsonSerializerOptions { IncludeFields = true };
[Theory]
[MemberData(nameof(WriteSuccessCases))]
public static async Task MultipleTypes(ITestClass testObj)
{
Type type = testObj.GetType();
// Get the test json with the default options to avoid cache pollution of Deserialize() below.
testObj.Initialize();
testObj.Verify();
var options = new JsonSerializerOptions { IncludeFields = true };
string json = JsonSerializer.Serialize(testObj, type, options);
void Serialize()
{
ITestClass localTestObj = (ITestClass)Activator.CreateInstance(type);
localTestObj.Initialize();
localTestObj.Verify();
string json = JsonSerializer.Serialize(localTestObj, type, s_options);
};
void Deserialize()
{
ITestClass obj = (ITestClass)JsonSerializer.Deserialize(json, type, s_options);
obj.Verify();
};
const int ThreadCount = 12;
const int ConcurrentTestsCount = 2;
Task[] tasks = new Task[ThreadCount * ConcurrentTestsCount];
for (int i = 0; i < tasks.Length; i += ConcurrentTestsCount)
{
tasks[i + 0] = Task.Run(() => Deserialize());
tasks[i + 1] = Task.Run(() => Serialize());
};
await Task.WhenAll(tasks);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void JsonSerializerOptionsUpdateHandler_ClearingDoesntPreventSerialization()
{
// This test uses reflection to:
// - Access JsonSerializerOptions._cachingContext.Count
// - Access JsonSerializerOptionsUpdateHandler.ClearCache
//
// If either of them changes, this test will need to be kept in sync.
RemoteExecutor.Invoke(() =>
{
var options = new JsonSerializerOptions();
Func<JsonSerializerOptions, int> getCount = CreateCacheCountAccessor();
Assert.Equal(0, getCount(options));
SimpleTestClass testObj = new SimpleTestClass();
testObj.Initialize();
JsonSerializer.Serialize<SimpleTestClass>(testObj, options);
Assert.NotEqual(0, getCount(options));
Type updateHandler = typeof(JsonSerializerOptions).Assembly.GetType("System.Text.Json.JsonSerializerOptionsUpdateHandler", throwOnError: true, ignoreCase: false);
MethodInfo clearCache = updateHandler.GetMethod("ClearCache");
Assert.NotNull(clearCache);
clearCache.Invoke(null, new object[] { null });
Assert.Equal(0, getCount(options));
JsonSerializer.Serialize<SimpleTestClass>(testObj, options);
Assert.NotEqual(0, getCount(options));
}).Dispose();
static Func<JsonSerializerOptions, int> CreateCacheCountAccessor()
{
FieldInfo cacheField = typeof(JsonSerializerOptions).GetField("_cachingContext", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(cacheField);
PropertyInfo countProperty = cacheField.FieldType.GetProperty("Count", BindingFlags.Public | BindingFlags.Instance);
Assert.NotNull(countProperty);
return options =>
{
object? cache = cacheField.GetValue(options);
return cache is null ? 0 : (int)countProperty.GetValue(cache);
};
}
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[MemberData(nameof(GetJsonSerializerOptions))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void JsonSerializerOptions_ReuseConverterCaches()
{
// This test uses reflection to:
// - Access JsonSerializerOptions._cachingContext._options
// - Access JsonSerializerOptions.EqualityComparer.AreEquivalent
//
// If either of them changes, this test will need to be kept in sync.
RemoteExecutor.Invoke(static () =>
{
Func<JsonSerializerOptions, JsonSerializerOptions?> getCacheOptions = CreateCacheOptionsAccessor();
IEqualityComparer<JsonSerializerOptions> equalityComparer = CreateEqualityComparerAccessor();
foreach (var args in GetJsonSerializerOptions())
{
var options = (JsonSerializerOptions)args[0];
Assert.Null(getCacheOptions(options));
JsonSerializer.Serialize(42, options);
JsonSerializerOptions originalCacheOptions = getCacheOptions(options);
Assert.NotNull(originalCacheOptions);
Assert.True(equalityComparer.Equals(options, originalCacheOptions));
Assert.Equal(equalityComparer.GetHashCode(options), equalityComparer.GetHashCode(originalCacheOptions));
for (int i = 0; i < 5; i++)
{
var options2 = new JsonSerializerOptions(options);
Assert.True(equalityComparer.Equals(options2, originalCacheOptions));
Assert.Equal(equalityComparer.GetHashCode(options2), equalityComparer.GetHashCode(originalCacheOptions));
Assert.Null(getCacheOptions(options2));
JsonSerializer.Serialize(42, options2);
Assert.Same(originalCacheOptions, getCacheOptions(options2));
}
}
}).Dispose();
static Func<JsonSerializerOptions, JsonSerializerOptions?> CreateCacheOptionsAccessor()
{
FieldInfo cacheField = typeof(JsonSerializerOptions).GetField("_cachingContext", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(cacheField);
PropertyInfo optionsField = cacheField.FieldType.GetProperty("Options", BindingFlags.Public | BindingFlags.Instance);
Assert.NotNull(optionsField);
return options =>
{
object? cache = cacheField.GetValue(options);
return cache is null ? null : (JsonSerializerOptions)optionsField.GetValue(cache);
};
}
}
public static IEnumerable<object[]> GetJsonSerializerOptions()
{
yield return new[] { new JsonSerializerOptions() };
yield return new[] { new JsonSerializerOptions(JsonSerializerDefaults.Web) };
yield return new[] { new JsonSerializerOptions { WriteIndented = true } };
yield return new[] { new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } } };
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void JsonSerializerOptions_EqualityComparer_ChangingAnySettingShouldReturnFalse()
{
// This test uses reflection to:
// - Access JsonSerializerOptions.EqualityComparer.AreEquivalent
// - All public setters in JsonSerializerOptions
//
// If either of them changes, this test will need to be kept in sync.
IEqualityComparer<JsonSerializerOptions> equalityComparer = CreateEqualityComparerAccessor();
(PropertyInfo prop, object value)[] propertySettersAndValues = GetPropertiesWithSettersAndNonDefaultValues().ToArray();
// Ensure we're testing equality for all JsonSerializerOptions settings
foreach (PropertyInfo prop in GetAllPublicPropertiesWithSetters().Except(propertySettersAndValues.Select(x => x.prop)))
{
Assert.Fail($"{nameof(GetPropertiesWithSettersAndNonDefaultValues)} missing property declaration for {prop.Name}, please update the method.");
}
Assert.True(equalityComparer.Equals(JsonSerializerOptions.Default, JsonSerializerOptions.Default));
Assert.Equal(equalityComparer.GetHashCode(JsonSerializerOptions.Default), equalityComparer.GetHashCode(JsonSerializerOptions.Default));
foreach ((PropertyInfo prop, object? value) in propertySettersAndValues)
{
var options = new JsonSerializerOptions();
prop.SetValue(options, value);
Assert.True(equalityComparer.Equals(options, options));
Assert.Equal(equalityComparer.GetHashCode(options), equalityComparer.GetHashCode(options));
Assert.False(equalityComparer.Equals(JsonSerializerOptions.Default, options));
Assert.NotEqual(equalityComparer.GetHashCode(JsonSerializerOptions.Default), equalityComparer.GetHashCode(options));
}
static IEnumerable<(PropertyInfo, object)> GetPropertiesWithSettersAndNonDefaultValues()
{
yield return (GetProp(nameof(JsonSerializerOptions.AllowTrailingCommas)), true);
yield return (GetProp(nameof(JsonSerializerOptions.DefaultBufferSize)), 42);
yield return (GetProp(nameof(JsonSerializerOptions.Encoder)), JavaScriptEncoder.UnsafeRelaxedJsonEscaping);
yield return (GetProp(nameof(JsonSerializerOptions.DictionaryKeyPolicy)), JsonNamingPolicy.CamelCase);
yield return (GetProp(nameof(JsonSerializerOptions.IgnoreNullValues)), true);
yield return (GetProp(nameof(JsonSerializerOptions.DefaultIgnoreCondition)), JsonIgnoreCondition.WhenWritingDefault);
yield return (GetProp(nameof(JsonSerializerOptions.NumberHandling)), JsonNumberHandling.AllowReadingFromString);
yield return (GetProp(nameof(JsonSerializerOptions.IgnoreReadOnlyProperties)), true);
yield return (GetProp(nameof(JsonSerializerOptions.IgnoreReadOnlyFields)), true);
yield return (GetProp(nameof(JsonSerializerOptions.IncludeFields)), true);
yield return (GetProp(nameof(JsonSerializerOptions.MaxDepth)), 11);
yield return (GetProp(nameof(JsonSerializerOptions.PropertyNamingPolicy)), JsonNamingPolicy.CamelCase);
yield return (GetProp(nameof(JsonSerializerOptions.PropertyNameCaseInsensitive)), true);
yield return (GetProp(nameof(JsonSerializerOptions.ReadCommentHandling)), JsonCommentHandling.Skip);
yield return (GetProp(nameof(JsonSerializerOptions.UnknownTypeHandling)), JsonUnknownTypeHandling.JsonNode);
yield return (GetProp(nameof(JsonSerializerOptions.WriteIndented)), true);
yield return (GetProp(nameof(JsonSerializerOptions.ReferenceHandler)), ReferenceHandler.Preserve);
static PropertyInfo GetProp(string name)
{
PropertyInfo property = typeof(JsonSerializerOptions).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
Assert.True(property.CanWrite);
return property;
}
}
static IEnumerable<PropertyInfo> GetAllPublicPropertiesWithSetters()
=> typeof(JsonSerializerOptions)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void JsonSerializerOptions_EqualityComparer_ApplyingJsonSerializerContextShouldReturnFalse()
{
// This test uses reflection to:
// - Access JsonSerializerOptions.EqualityComparer
//
// If either of them changes, this test will need to be kept in sync.
IEqualityComparer<JsonSerializerOptions> equalityComparer = CreateEqualityComparerAccessor();
var options1 = new JsonSerializerOptions { WriteIndented = true };
var options2 = new JsonSerializerOptions { WriteIndented = true };
Assert.True(equalityComparer.Equals(options1, options2));
Assert.Equal(equalityComparer.GetHashCode(options1), equalityComparer.GetHashCode(options2));
_ = new MyJsonContext(options1); // Associate copy with a JsonSerializerContext
Assert.False(equalityComparer.Equals(options1, options2));
Assert.NotEqual(equalityComparer.GetHashCode(options1), equalityComparer.GetHashCode(options2));
}
private class MyJsonContext : JsonSerializerContext
{
public MyJsonContext(JsonSerializerOptions options) : base(options) { }
public override JsonTypeInfo? GetTypeInfo(Type _) => null;
protected override JsonSerializerOptions? GeneratedSerializerOptions => Options;
}
public static IEqualityComparer<JsonSerializerOptions> CreateEqualityComparerAccessor()
{
Type equalityComparerType = typeof(JsonSerializerOptions).GetNestedType("EqualityComparer", BindingFlags.NonPublic);
Assert.NotNull(equalityComparerType);
return (IEqualityComparer<JsonSerializerOptions>)Activator.CreateInstance(equalityComparerType, nonPublic: true);
}
public static IEnumerable<object[]> WriteSuccessCases
{
get
{
return TestData.WriteSuccessCases;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
using Xunit;
using Microsoft.DotNet.RemoteExecutor;
namespace System.Text.Json.Serialization.Tests
{
public static class CacheTests
{
[Fact, OuterLoop]
public static async Task MultipleThreads_SameType_DifferentJson_Looping()
{
const int Iterations = 100;
for (int i = 0; i < Iterations; i++)
{
await MultipleThreads_SameType_DifferentJson();
}
}
[Fact]
public static async Task MultipleThreads_SameType_DifferentJson()
{
// Use local options to avoid obtaining already cached metadata from the default options.
var options = new JsonSerializerOptions();
// Verify the test class has >64 properties since that is a threshold for using the fallback dictionary.
Assert.True(typeof(SimpleTestClass).GetProperties(BindingFlags.Instance | BindingFlags.Public).Length > 64);
void DeserializeObjectMinimal()
{
SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(@"{""MyDecimal"" : 3.3}", options);
};
void DeserializeObjectFlipped()
{
SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(SimpleTestClass.s_json_flipped, options);
obj.Verify();
};
void DeserializeObjectNormal()
{
SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(SimpleTestClass.s_json, options);
obj.Verify();
};
void SerializeObject()
{
var obj = new SimpleTestClass();
obj.Initialize();
JsonSerializer.Serialize(obj, options);
};
const int ThreadCount = 8;
const int ConcurrentTestsCount = 4;
Task[] tasks = new Task[ThreadCount * ConcurrentTestsCount];
for (int i = 0; i < tasks.Length; i += ConcurrentTestsCount)
{
// Create race condition to populate the sorted property cache with different json ordering.
tasks[i + 0] = Task.Run(() => DeserializeObjectMinimal());
tasks[i + 1] = Task.Run(() => DeserializeObjectFlipped());
tasks[i + 2] = Task.Run(() => DeserializeObjectNormal());
// Ensure no exceptions on serialization
tasks[i + 3] = Task.Run(() => SerializeObject());
};
await Task.WhenAll(tasks);
}
[Fact, OuterLoop]
public static async Task MultipleThreads_DifferentTypes_Looping()
{
const int Iterations = 100;
for (int i = 0; i < Iterations; i++)
{
await MultipleThreads_DifferentTypes();
}
}
[Fact]
public static async Task MultipleThreads_DifferentTypes()
{
// Use local options to avoid obtaining already cached metadata from the default options.
var options = new JsonSerializerOptions();
const int TestClassCount = 2;
var testObjects = new ITestClass[TestClassCount]
{
new SimpleTestClassWithNulls(),
new SimpleTestClass(),
};
foreach (ITestClass obj in testObjects)
{
obj.Initialize();
}
void Test(int i)
{
Type testClassType = testObjects[i].GetType();
string json = JsonSerializer.Serialize(testObjects[i], testClassType, options);
ITestClass obj = (ITestClass)JsonSerializer.Deserialize(json, testClassType, options);
obj.Verify();
};
const int OuterCount = 12;
Task[] tasks = new Task[OuterCount * TestClassCount];
for (int i = 0; i < tasks.Length; i += TestClassCount)
{
tasks[i + 0] = Task.Run(() => Test(TestClassCount - 1));
tasks[i + 1] = Task.Run(() => Test(TestClassCount - 2));
}
await Task.WhenAll(tasks);
}
[Fact]
public static void PropertyCacheWithMinInputsFirst()
{
// Use local options to avoid obtaining already cached metadata from the default options.
var options = new JsonSerializerOptions();
string json = "{}";
JsonSerializer.Deserialize<SimpleTestClass>(json, options);
SimpleTestClass testObj = new SimpleTestClass();
testObj.Initialize();
testObj.Verify();
json = JsonSerializer.Serialize(testObj, options);
testObj = JsonSerializer.Deserialize<SimpleTestClass>(json, options);
testObj.Verify();
}
[Fact]
public static void PropertyCacheWithMinInputsLast()
{
// Use local options to avoid obtaining already cached metadata from the default options.
var options = new JsonSerializerOptions();
SimpleTestClass testObj = new SimpleTestClass();
testObj.Initialize();
testObj.Verify();
string json = JsonSerializer.Serialize(testObj, options);
testObj = JsonSerializer.Deserialize<SimpleTestClass>(json, options);
testObj.Verify();
json = "{}";
JsonSerializer.Deserialize<SimpleTestClass>(json, options);
}
// Use a common options instance to encourage additional metadata collisions across types. Also since
// this options is not the default options instance the tests will not use previously cached metadata.
private static JsonSerializerOptions s_options = new JsonSerializerOptions { IncludeFields = true };
[Theory]
[MemberData(nameof(WriteSuccessCases))]
public static async Task MultipleTypes(ITestClass testObj)
{
Type type = testObj.GetType();
// Get the test json with the default options to avoid cache pollution of Deserialize() below.
testObj.Initialize();
testObj.Verify();
var options = new JsonSerializerOptions { IncludeFields = true };
string json = JsonSerializer.Serialize(testObj, type, options);
void Serialize()
{
ITestClass localTestObj = (ITestClass)Activator.CreateInstance(type);
localTestObj.Initialize();
localTestObj.Verify();
string json = JsonSerializer.Serialize(localTestObj, type, s_options);
};
void Deserialize()
{
ITestClass obj = (ITestClass)JsonSerializer.Deserialize(json, type, s_options);
obj.Verify();
};
const int ThreadCount = 12;
const int ConcurrentTestsCount = 2;
Task[] tasks = new Task[ThreadCount * ConcurrentTestsCount];
for (int i = 0; i < tasks.Length; i += ConcurrentTestsCount)
{
tasks[i + 0] = Task.Run(() => Deserialize());
tasks[i + 1] = Task.Run(() => Serialize());
};
await Task.WhenAll(tasks);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void JsonSerializerOptionsUpdateHandler_ClearingDoesntPreventSerialization()
{
// This test uses reflection to:
// - Access JsonSerializerOptions._cachingContext.Count
// - Access JsonSerializerOptionsUpdateHandler.ClearCache
//
// If either of them changes, this test will need to be kept in sync.
RemoteExecutor.Invoke(() =>
{
var options = new JsonSerializerOptions();
Func<JsonSerializerOptions, int> getCount = CreateCacheCountAccessor();
Assert.Equal(0, getCount(options));
SimpleTestClass testObj = new SimpleTestClass();
testObj.Initialize();
JsonSerializer.Serialize<SimpleTestClass>(testObj, options);
Assert.NotEqual(0, getCount(options));
Type updateHandler = typeof(JsonSerializerOptions).Assembly.GetType("System.Text.Json.JsonSerializerOptionsUpdateHandler", throwOnError: true, ignoreCase: false);
MethodInfo clearCache = updateHandler.GetMethod("ClearCache");
Assert.NotNull(clearCache);
clearCache.Invoke(null, new object[] { null });
Assert.Equal(0, getCount(options));
JsonSerializer.Serialize<SimpleTestClass>(testObj, options);
Assert.NotEqual(0, getCount(options));
}).Dispose();
static Func<JsonSerializerOptions, int> CreateCacheCountAccessor()
{
FieldInfo cacheField = typeof(JsonSerializerOptions).GetField("_cachingContext", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(cacheField);
PropertyInfo countProperty = cacheField.FieldType.GetProperty("Count", BindingFlags.Public | BindingFlags.Instance);
Assert.NotNull(countProperty);
return options =>
{
object? cache = cacheField.GetValue(options);
return cache is null ? 0 : (int)countProperty.GetValue(cache);
};
}
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/66232", TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[MemberData(nameof(GetJsonSerializerOptions))]
public static void JsonSerializerOptions_ReuseConverterCaches()
{
// This test uses reflection to:
// - Access JsonSerializerOptions._cachingContext._options
// - Access JsonSerializerOptions.EqualityComparer.AreEquivalent
//
// If either of them changes, this test will need to be kept in sync.
RemoteExecutor.Invoke(static () =>
{
Func<JsonSerializerOptions, JsonSerializerOptions?> getCacheOptions = CreateCacheOptionsAccessor();
IEqualityComparer<JsonSerializerOptions> equalityComparer = CreateEqualityComparerAccessor();
foreach (var args in GetJsonSerializerOptions())
{
var options = (JsonSerializerOptions)args[0];
Assert.Null(getCacheOptions(options));
JsonSerializer.Serialize(42, options);
JsonSerializerOptions originalCacheOptions = getCacheOptions(options);
Assert.NotNull(originalCacheOptions);
Assert.True(equalityComparer.Equals(options, originalCacheOptions));
Assert.Equal(equalityComparer.GetHashCode(options), equalityComparer.GetHashCode(originalCacheOptions));
for (int i = 0; i < 5; i++)
{
var options2 = new JsonSerializerOptions(options);
Assert.Null(getCacheOptions(options2));
JsonSerializer.Serialize(42, options2);
Assert.True(equalityComparer.Equals(options2, originalCacheOptions));
Assert.Equal(equalityComparer.GetHashCode(options2), equalityComparer.GetHashCode(originalCacheOptions));
Assert.Same(originalCacheOptions, getCacheOptions(options2));
}
}
}).Dispose();
static Func<JsonSerializerOptions, JsonSerializerOptions?> CreateCacheOptionsAccessor()
{
FieldInfo cacheField = typeof(JsonSerializerOptions).GetField("_cachingContext", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(cacheField);
PropertyInfo optionsField = cacheField.FieldType.GetProperty("Options", BindingFlags.Public | BindingFlags.Instance);
Assert.NotNull(optionsField);
return options =>
{
object? cache = cacheField.GetValue(options);
return cache is null ? null : (JsonSerializerOptions)optionsField.GetValue(cache);
};
}
}
public static IEnumerable<object[]> GetJsonSerializerOptions()
{
yield return new[] { new JsonSerializerOptions() };
yield return new[] { new JsonSerializerOptions(JsonSerializerDefaults.Web) };
yield return new[] { new JsonSerializerOptions { WriteIndented = true } };
yield return new[] { new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } } };
}
[Fact]
public static void JsonSerializerOptions_EqualityComparer_ChangingAnySettingShouldReturnFalse()
{
// This test uses reflection to:
// - Access JsonSerializerOptions.EqualityComparer.AreEquivalent
// - All public setters in JsonSerializerOptions
//
// If either of them changes, this test will need to be kept in sync.
IEqualityComparer<JsonSerializerOptions> equalityComparer = CreateEqualityComparerAccessor();
(PropertyInfo prop, object value)[] propertySettersAndValues = GetPropertiesWithSettersAndNonDefaultValues().ToArray();
// Ensure we're testing equality for all JsonSerializerOptions settings
foreach (PropertyInfo prop in GetAllPublicPropertiesWithSetters().Except(propertySettersAndValues.Select(x => x.prop)))
{
Assert.Fail($"{nameof(GetPropertiesWithSettersAndNonDefaultValues)} missing property declaration for {prop.Name}, please update the method.");
}
Assert.True(equalityComparer.Equals(JsonSerializerOptions.Default, JsonSerializerOptions.Default));
Assert.Equal(equalityComparer.GetHashCode(JsonSerializerOptions.Default), equalityComparer.GetHashCode(JsonSerializerOptions.Default));
foreach ((PropertyInfo prop, object? value) in propertySettersAndValues)
{
var options = new JsonSerializerOptions();
prop.SetValue(options, value);
Assert.True(equalityComparer.Equals(options, options));
Assert.Equal(equalityComparer.GetHashCode(options), equalityComparer.GetHashCode(options));
Assert.False(equalityComparer.Equals(JsonSerializerOptions.Default, options));
Assert.NotEqual(equalityComparer.GetHashCode(JsonSerializerOptions.Default), equalityComparer.GetHashCode(options));
}
static IEnumerable<(PropertyInfo, object)> GetPropertiesWithSettersAndNonDefaultValues()
{
yield return (GetProp(nameof(JsonSerializerOptions.AllowTrailingCommas)), true);
yield return (GetProp(nameof(JsonSerializerOptions.DefaultBufferSize)), 42);
yield return (GetProp(nameof(JsonSerializerOptions.Encoder)), JavaScriptEncoder.UnsafeRelaxedJsonEscaping);
yield return (GetProp(nameof(JsonSerializerOptions.DictionaryKeyPolicy)), JsonNamingPolicy.CamelCase);
yield return (GetProp(nameof(JsonSerializerOptions.IgnoreNullValues)), true);
yield return (GetProp(nameof(JsonSerializerOptions.DefaultIgnoreCondition)), JsonIgnoreCondition.WhenWritingDefault);
yield return (GetProp(nameof(JsonSerializerOptions.NumberHandling)), JsonNumberHandling.AllowReadingFromString);
yield return (GetProp(nameof(JsonSerializerOptions.IgnoreReadOnlyProperties)), true);
yield return (GetProp(nameof(JsonSerializerOptions.IgnoreReadOnlyFields)), true);
yield return (GetProp(nameof(JsonSerializerOptions.IncludeFields)), true);
yield return (GetProp(nameof(JsonSerializerOptions.MaxDepth)), 11);
yield return (GetProp(nameof(JsonSerializerOptions.PropertyNamingPolicy)), JsonNamingPolicy.CamelCase);
yield return (GetProp(nameof(JsonSerializerOptions.PropertyNameCaseInsensitive)), true);
yield return (GetProp(nameof(JsonSerializerOptions.ReadCommentHandling)), JsonCommentHandling.Skip);
yield return (GetProp(nameof(JsonSerializerOptions.UnknownTypeHandling)), JsonUnknownTypeHandling.JsonNode);
yield return (GetProp(nameof(JsonSerializerOptions.WriteIndented)), true);
yield return (GetProp(nameof(JsonSerializerOptions.ReferenceHandler)), ReferenceHandler.Preserve);
static PropertyInfo GetProp(string name)
{
PropertyInfo property = typeof(JsonSerializerOptions).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
Assert.True(property.CanWrite);
return property;
}
}
static IEnumerable<PropertyInfo> GetAllPublicPropertiesWithSetters()
=> typeof(JsonSerializerOptions)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite);
}
[Fact]
public static void JsonSerializerOptions_EqualityComparer_ApplyingJsonSerializerContextShouldReturnFalse()
{
// This test uses reflection to:
// - Access JsonSerializerOptions.EqualityComparer
//
// If either of them changes, this test will need to be kept in sync.
IEqualityComparer<JsonSerializerOptions> equalityComparer = CreateEqualityComparerAccessor();
var options1 = new JsonSerializerOptions { WriteIndented = true };
var options2 = new JsonSerializerOptions { WriteIndented = true };
Assert.True(equalityComparer.Equals(options1, options2));
Assert.Equal(equalityComparer.GetHashCode(options1), equalityComparer.GetHashCode(options2));
_ = new MyJsonContext(options1); // Associate copy with a JsonSerializerContext
Assert.False(equalityComparer.Equals(options1, options2));
Assert.NotEqual(equalityComparer.GetHashCode(options1), equalityComparer.GetHashCode(options2));
}
private class MyJsonContext : JsonSerializerContext
{
public MyJsonContext(JsonSerializerOptions options) : base(options) { }
public override JsonTypeInfo? GetTypeInfo(Type _) => null;
protected override JsonSerializerOptions? GeneratedSerializerOptions => Options;
}
public static IEqualityComparer<JsonSerializerOptions> CreateEqualityComparerAccessor()
{
Type equalityComparerType = typeof(JsonSerializerOptions).GetNestedType("EqualityComparer", BindingFlags.NonPublic);
Assert.NotNull(equalityComparerType);
return (IEqualityComparer<JsonSerializerOptions>)Activator.CreateInstance(equalityComparerType, nonPublic: true);
}
public static IEnumerable<object[]> WriteSuccessCases
{
get
{
return TestData.WriteSuccessCases;
}
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.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.Text.Json.Serialization.Tests
{
public static partial class CustomConverterTests
{
[Fact]
public static void MultipleConvertersInObjectArray()
{
const string expectedJson = @"[""?"",{""TypeDiscriminator"":1,""CreditLimit"":100,""Name"":""C""},null]";
var options = new JsonSerializerOptions();
options.Converters.Add(new MyBoolEnumConverter());
options.Converters.Add(new PersonConverterWithTypeDiscriminator());
Customer customer = new Customer();
customer.CreditLimit = 100;
customer.Name = "C";
MyBoolEnum myBoolEnum = MyBoolEnum.Unknown;
MyBoolEnum? myNullBoolEnum = null;
string json = JsonSerializer.Serialize(new object[] { myBoolEnum, customer, myNullBoolEnum }, options);
Assert.Equal(expectedJson, json);
JsonElement jsonElement = JsonSerializer.Deserialize<JsonElement>(json, options);
string jsonElementString = jsonElement.ToString();
Assert.Equal(expectedJson, jsonElementString);
}
[Fact]
public static void OptionsArePassedToCreateConverter()
{
TestFactory factory = new TestFactory();
JsonSerializerOptions options = new JsonSerializerOptions { Converters = { factory } };
string json = JsonSerializer.Serialize("Test", options);
Assert.Equal(@"""Test""", json);
Assert.Same(options, factory.Options);
}
public class TestFactory : JsonConverterFactory
{
public JsonSerializerOptions Options { get; private set; }
public override bool CanConvert(Type typeToConvert) => true;
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
Options = options;
return new SimpleConverter();
}
public class SimpleConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
=> writer.WriteStringValue(value);
}
}
private class ConverterReturningNull : JsonConverter<Customer>
{
public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Assert.Equal(JsonTokenType.StartObject, reader.TokenType);
bool rc = reader.Read();
Assert.True(rc);
Assert.Equal(JsonTokenType.EndObject, reader.TokenType);
return null;
}
public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options)
{
throw new NotSupportedException();
}
}
[Fact]
public static void VerifyConverterWithTrailingWhitespace()
{
string json = "{} ";
var options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
byte[] utf8 = Encoding.UTF8.GetBytes(json);
// The serializer will finish reading the whitespace and no exception will be thrown.
Customer c = JsonSerializer.Deserialize<Customer>(utf8, options);
Assert.Null(c);
}
[Fact]
public static void VerifyConverterWithTrailingComments()
{
string json = "{} //";
byte[] utf8 = Encoding.UTF8.GetBytes(json);
// Disallow comments
var options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Customer>(utf8, options));
// Skip comments
options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
options.ReadCommentHandling = JsonCommentHandling.Skip;
Customer c = JsonSerializer.Deserialize<Customer>(utf8, options);
Assert.Null(c);
}
public class ObjectBoolConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.True)
{
return true;
}
if (reader.TokenType == JsonTokenType.False)
{
return false;
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
[Fact]
public static void VerifyObjectConverterWithPreservedReferences()
{
var json = "true";
byte[] utf8 = Encoding.UTF8.GetBytes(json);
var options = new JsonSerializerOptions()
{
ReferenceHandler = ReferenceHandler.Preserve,
};
options.Converters.Add(new ObjectBoolConverter());
object obj = (JsonSerializer.Deserialize<object>(utf8, options));
Assert.IsType<bool>(obj);
Assert.Equal(true, obj);
}
[Fact]
public static void GetConverterRootsBuiltInConverters()
{
JsonSerializerOptions options = new();
RunTest<DateTime>();
RunTest<Point_2D>();
void RunTest<TConverterReturn>()
{
JsonConverter converter = options.GetConverter(typeof(TConverterReturn));
Assert.NotNull(converter);
Assert.True(converter is JsonConverter<TConverterReturn>);
}
}
[Fact]
public static void GetConverterTypeToConvertNull()
{
Assert.Throws<ArgumentNullException>(() => (new JsonSerializerOptions()).GetConverter(typeToConvert: 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.Diagnostics;
using System.IO;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class CustomConverterTests
{
[Fact]
public static void MultipleConvertersInObjectArray()
{
const string expectedJson = @"[""?"",{""TypeDiscriminator"":1,""CreditLimit"":100,""Name"":""C""},null]";
var options = new JsonSerializerOptions();
options.Converters.Add(new MyBoolEnumConverter());
options.Converters.Add(new PersonConverterWithTypeDiscriminator());
Customer customer = new Customer();
customer.CreditLimit = 100;
customer.Name = "C";
MyBoolEnum myBoolEnum = MyBoolEnum.Unknown;
MyBoolEnum? myNullBoolEnum = null;
string json = JsonSerializer.Serialize(new object[] { myBoolEnum, customer, myNullBoolEnum }, options);
Assert.Equal(expectedJson, json);
JsonElement jsonElement = JsonSerializer.Deserialize<JsonElement>(json, options);
string jsonElementString = jsonElement.ToString();
Assert.Equal(expectedJson, jsonElementString);
}
[Fact]
public static void OptionsArePassedToCreateConverter()
{
TestFactory factory = new TestFactory();
JsonSerializerOptions options = new JsonSerializerOptions { Converters = { factory } };
string json = JsonSerializer.Serialize("Test", options);
Assert.Equal(@"""Test""", json);
Assert.Same(options, factory.Options);
}
public class TestFactory : JsonConverterFactory
{
public JsonSerializerOptions Options { get; private set; }
public override bool CanConvert(Type typeToConvert) => true;
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
Options = options;
return new SimpleConverter();
}
public class SimpleConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
=> writer.WriteStringValue(value);
}
}
private class ConverterReturningNull : JsonConverter<Customer>
{
public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Assert.Equal(JsonTokenType.StartObject, reader.TokenType);
bool rc = reader.Read();
Assert.True(rc);
Assert.Equal(JsonTokenType.EndObject, reader.TokenType);
return null;
}
public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options)
{
throw new NotSupportedException();
}
}
[Fact]
public static void VerifyConverterWithTrailingWhitespace()
{
string json = "{} ";
var options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
byte[] utf8 = Encoding.UTF8.GetBytes(json);
// The serializer will finish reading the whitespace and no exception will be thrown.
Customer c = JsonSerializer.Deserialize<Customer>(utf8, options);
Assert.Null(c);
}
[Fact]
public static void VerifyConverterWithTrailingComments()
{
string json = "{} //";
byte[] utf8 = Encoding.UTF8.GetBytes(json);
// Disallow comments
var options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Customer>(utf8, options));
// Skip comments
options = new JsonSerializerOptions();
options.Converters.Add(new ConverterReturningNull());
options.ReadCommentHandling = JsonCommentHandling.Skip;
Customer c = JsonSerializer.Deserialize<Customer>(utf8, options);
Assert.Null(c);
}
public class ObjectBoolConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.True)
{
return true;
}
if (reader.TokenType == JsonTokenType.False)
{
return false;
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
[Fact]
public static void VerifyObjectConverterWithPreservedReferences()
{
var json = "true";
byte[] utf8 = Encoding.UTF8.GetBytes(json);
var options = new JsonSerializerOptions()
{
ReferenceHandler = ReferenceHandler.Preserve,
};
options.Converters.Add(new ObjectBoolConverter());
object obj = (JsonSerializer.Deserialize<object>(utf8, options));
Assert.IsType<bool>(obj);
Assert.Equal(true, obj);
}
[Fact]
public static void GetConverterRootsBuiltInConverters()
{
JsonSerializerOptions options = new();
RunTest<DateTime>();
RunTest<Point_2D>();
void RunTest<TConverterReturn>()
{
JsonConverter converter = options.GetConverter(typeof(TConverterReturn));
Assert.NotNull(converter);
Assert.True(converter is JsonConverter<TConverterReturn>);
}
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/66232", TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void GetConverter_Poco_WriteThrowsNotSupportedException()
{
RemoteExecutor.Invoke(() =>
{
JsonSerializerOptions options = new();
JsonConverter<Point_2D> converter = (JsonConverter<Point_2D>)options.GetConverter(typeof(Point_2D));
using var writer = new Utf8JsonWriter(new MemoryStream());
var value = new Point_2D(0, 0);
// Running the converter without priming the options instance
// for reflection-based serialization should throw NotSupportedException
// since it can't resolve reflection-based metadata.
Assert.Throws<NotSupportedException>(() => converter.Write(writer, value, options));
Debug.Assert(writer.BytesCommitted + writer.BytesPending == 0);
JsonSerializer.Serialize(42, options);
// Same operation should succeed when instance has been primed.
converter.Write(writer, value, options);
Debug.Assert(writer.BytesCommitted + writer.BytesPending > 0);
writer.Reset();
// State change should not leak into unrelated options instances.
var options2 = new JsonSerializerOptions();
options2.AddContext<JsonContext>();
Assert.Throws<NotSupportedException>(() => converter.Write(writer, value, options2));
Debug.Assert(writer.BytesCommitted + writer.BytesPending == 0);
}).Dispose();
}
[Fact]
public static void GetConverterTypeToConvertNull()
{
Assert.Throws<ArgumentNullException>(() => (new JsonSerializerOptions()).GetConverter(typeToConvert: null!));
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class OptionsTests
{
private class TestConverter : JsonConverter<bool>
{
public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
[Fact]
public static void SetOptionsFail()
{
var options = new JsonSerializerOptions();
// Verify these do not throw.
options.Converters.Clear();
TestConverter tc = new TestConverter();
options.Converters.Add(tc);
options.Converters.Insert(0, new TestConverter());
options.Converters.Remove(tc);
options.Converters.RemoveAt(0);
// Add one item for later.
options.Converters.Add(tc);
// Verify converter collection throws on null adds.
Assert.Throws<ArgumentNullException>(() => options.Converters.Add(null));
Assert.Throws<ArgumentNullException>(() => options.Converters.Insert(0, null));
Assert.Throws<ArgumentNullException>(() => options.Converters[0] = null);
// Perform serialization.
JsonSerializer.Deserialize<int>("1", options);
// Verify defaults and ensure getters do not throw.
Assert.False(options.AllowTrailingCommas);
Assert.Equal(16 * 1024, options.DefaultBufferSize);
Assert.Null(options.DictionaryKeyPolicy);
Assert.Null(options.Encoder);
Assert.False(options.IgnoreNullValues);
Assert.Equal(0, options.MaxDepth);
Assert.False(options.PropertyNameCaseInsensitive);
Assert.Null(options.PropertyNamingPolicy);
Assert.Equal(JsonCommentHandling.Disallow, options.ReadCommentHandling);
Assert.False(options.WriteIndented);
Assert.Equal(tc, options.Converters[0]);
Assert.True(options.Converters.Contains(tc));
options.Converters.CopyTo(new JsonConverter[1] { null }, 0);
Assert.Equal(1, options.Converters.Count);
Assert.False(options.Converters.Equals(tc));
Assert.NotNull(options.Converters.GetEnumerator());
Assert.Equal(0, options.Converters.IndexOf(tc));
Assert.False(options.Converters.IsReadOnly);
// Setters should always throw; we don't check to see if the value is the same or not.
Assert.Throws<InvalidOperationException>(() => options.AllowTrailingCommas = options.AllowTrailingCommas);
Assert.Throws<InvalidOperationException>(() => options.DefaultBufferSize = options.DefaultBufferSize);
Assert.Throws<InvalidOperationException>(() => options.DictionaryKeyPolicy = options.DictionaryKeyPolicy);
Assert.Throws<InvalidOperationException>(() => options.Encoder = JavaScriptEncoder.Default);
Assert.Throws<InvalidOperationException>(() => options.IgnoreNullValues = options.IgnoreNullValues);
Assert.Throws<InvalidOperationException>(() => options.MaxDepth = options.MaxDepth);
Assert.Throws<InvalidOperationException>(() => options.PropertyNameCaseInsensitive = options.PropertyNameCaseInsensitive);
Assert.Throws<InvalidOperationException>(() => options.PropertyNamingPolicy = options.PropertyNamingPolicy);
Assert.Throws<InvalidOperationException>(() => options.ReadCommentHandling = options.ReadCommentHandling);
Assert.Throws<InvalidOperationException>(() => options.WriteIndented = options.WriteIndented);
Assert.Throws<InvalidOperationException>(() => options.Converters[0] = tc);
Assert.Throws<InvalidOperationException>(() => options.Converters.Clear());
Assert.Throws<InvalidOperationException>(() => options.Converters.Add(tc));
Assert.Throws<InvalidOperationException>(() => options.Converters.Insert(0, new TestConverter()));
Assert.Throws<InvalidOperationException>(() => options.Converters.Remove(tc));
Assert.Throws<InvalidOperationException>(() => options.Converters.RemoveAt(0));
}
[Fact]
public static void DefaultBufferSizeFail()
{
Assert.Throws<ArgumentException>(() => new JsonSerializerOptions().DefaultBufferSize = 0);
Assert.Throws<ArgumentException>(() => new JsonSerializerOptions().DefaultBufferSize = -1);
}
[Fact]
public static void DefaultBufferSize()
{
var options = new JsonSerializerOptions();
Assert.Equal(16 * 1024, options.DefaultBufferSize);
options.DefaultBufferSize = 1;
Assert.Equal(1, options.DefaultBufferSize);
}
[Fact]
public static void AllowTrailingCommas()
{
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<int[]>("[1,]"));
var options = new JsonSerializerOptions();
options.AllowTrailingCommas = true;
int[] value = JsonSerializer.Deserialize<int[]>("[1,]", options);
Assert.Equal(1, value[0]);
}
[Fact]
public static void WriteIndented()
{
var obj = new BasicCompany();
obj.Initialize();
// Verify default value.
string json = JsonSerializer.Serialize(obj);
Assert.DoesNotContain(Environment.NewLine, json);
// Verify default value on options.
var options = new JsonSerializerOptions();
json = JsonSerializer.Serialize(obj, options);
Assert.DoesNotContain(Environment.NewLine, json);
// Change the value on options.
options = new JsonSerializerOptions();
options.WriteIndented = true;
json = JsonSerializer.Serialize(obj, options);
Assert.Contains(Environment.NewLine, json);
}
[Fact]
public static void ExtensionDataUsesReaderOptions()
{
// We just verify trailing commas.
const string json = @"{""MyIntMissing"":2,}";
// Verify baseline without options.
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithExtensionProperty>(json));
// Verify baseline with options.
var options = new JsonSerializerOptions();
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithExtensionProperty>(json, options));
// Set AllowTrailingCommas to true.
options = new JsonSerializerOptions();
options.AllowTrailingCommas = true;
JsonSerializer.Deserialize<ClassWithExtensionProperty>(json, options);
}
[Fact]
public static void ExtensionDataUsesWriterOptions()
{
// We just verify whitespace.
ClassWithExtensionProperty obj = JsonSerializer.Deserialize<ClassWithExtensionProperty>(@"{""MyIntMissing"":2}");
// Verify baseline without options.
string json = JsonSerializer.Serialize(obj);
Assert.False(HasNewLine());
// Verify baseline with options.
var options = new JsonSerializerOptions();
json = JsonSerializer.Serialize(obj, options);
Assert.False(HasNewLine());
// Set AllowTrailingCommas to true.
options = new JsonSerializerOptions();
options.WriteIndented = true;
json = JsonSerializer.Serialize(obj, options);
Assert.True(HasNewLine());
bool HasNewLine()
{
int iEnd = json.IndexOf("2", json.IndexOf("MyIntMissing"));
return json.Substring(iEnd + 1).StartsWith(Environment.NewLine);
}
}
[Fact]
public static void ReadCommentHandling()
{
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<object>("/* commment */"));
var options = new JsonSerializerOptions();
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<object>("/* commment */", options));
options = new JsonSerializerOptions();
options.ReadCommentHandling = JsonCommentHandling.Skip;
int value = JsonSerializer.Deserialize<int>("1 /* commment */", options);
Assert.Equal(1, value);
}
[Theory]
[InlineData(-1)]
[InlineData((int)JsonCommentHandling.Allow)]
[InlineData(3)]
[InlineData(byte.MaxValue)]
[InlineData(byte.MaxValue + 3)] // Other values, like byte.MaxValue + 1 overflows to 0 (i.e. JsonCommentHandling.Disallow), which is valid.
[InlineData(byte.MaxValue + 4)]
public static void ReadCommentHandlingDoesNotSupportAllow(int enumValue)
{
var options = new JsonSerializerOptions();
Assert.Throws<ArgumentOutOfRangeException>("value", () => options.ReadCommentHandling = (JsonCommentHandling)enumValue);
}
[Theory]
[InlineData(-1)]
public static void TestDepthInvalid(int depth)
{
var options = new JsonSerializerOptions();
Assert.Throws<ArgumentOutOfRangeException>("value", () => options.MaxDepth = depth);
}
[Fact]
public static void MaxDepthRead()
{
JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data);
var options = new JsonSerializerOptions();
JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data, options);
options = new JsonSerializerOptions();
options.MaxDepth = 1;
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data, options));
}
private class TestClassForEncoding
{
public string MyString { get; set; }
}
// This is a copy of the test data in System.Text.Json.Tests.JsonEncodedTextTests.JsonEncodedTextStringsCustom
public static IEnumerable<object[]> JsonEncodedTextStringsCustom
{
get
{
return new List<object[]>
{
new object[] { "age", "\\u0061\\u0067\\u0065" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\"\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\u0022\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u0022\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0032\\u0032\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9>>>>>\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003E\\u003E\\u003E\\u003E\\u003E\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003e\\u003e\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0033\\u0065\\\\\\u0075\\u0030\\u0030\\u0033\\u0065\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003E\\u003E\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0033\\u0045\\\\\\u0075\\u0030\\u0030\\u0033\\u0045\u00EA\u00EA\u00EA\u00EA\u00EA" },
};
}
}
[Theory]
[MemberData(nameof(JsonEncodedTextStringsCustom))]
public static void CustomEncoderAllowLatin1Supplement(string message, string expectedMessage)
{
// Latin-1 Supplement block starts from U+0080 and ends at U+00FF
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.Latin1Supplement);
var options = new JsonSerializerOptions();
options.Encoder = encoder;
var obj = new TestClassForEncoding();
obj.MyString = message;
string baselineJson = JsonSerializer.Serialize(obj);
Assert.DoesNotContain(expectedMessage, baselineJson);
string json = JsonSerializer.Serialize(obj, options);
Assert.Contains(expectedMessage, json);
obj = JsonSerializer.Deserialize<TestClassForEncoding>(json);
Assert.Equal(obj.MyString, message);
}
public static IEnumerable<object[]> JsonEncodedTextStringsCustomAll
{
get
{
return new List<object[]>
{
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "a\u0467\u0466a", "a\u0467\u0466a" },
};
}
}
[Theory]
[MemberData(nameof(JsonEncodedTextStringsCustomAll))]
public static void JsonEncodedTextStringsCustomAllowAll(string message, string expectedMessage)
{
// Allow all unicode values (except forbidden characters which we don't have in test data here)
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
var options = new JsonSerializerOptions();
options.Encoder = encoder;
var obj = new TestClassForEncoding();
obj.MyString = message;
string baselineJson = JsonSerializer.Serialize(obj);
Assert.DoesNotContain(expectedMessage, baselineJson);
string json = JsonSerializer.Serialize(obj, options);
Assert.Contains(expectedMessage, json);
obj = JsonSerializer.Deserialize<TestClassForEncoding>(json);
Assert.Equal(obj.MyString, message);
}
[Fact]
public static void Options_GetConverterForObjectJsonElement_GivesCorrectConverter()
{
GenericObjectOrJsonElementConverterTestHelper<object>("ObjectConverter", new object(), "{}");
JsonElement element = JsonDocument.Parse("[3]").RootElement;
GenericObjectOrJsonElementConverterTestHelper<JsonElement>("JsonElementConverter", element, "[3]");
}
private static void GenericObjectOrJsonElementConverterTestHelper<T>(string converterName, object objectValue, string stringValue)
{
var options = new JsonSerializerOptions();
JsonConverter<T> converter = (JsonConverter<T>)options.GetConverter(typeof(T));
Assert.Equal(converterName, converter.GetType().Name);
ReadOnlySpan<byte> data = Encoding.UTF8.GetBytes(stringValue);
Utf8JsonReader reader = new Utf8JsonReader(data);
reader.Read();
T readValue = converter.Read(ref reader, typeof(T), options);
if (readValue is JsonElement element)
{
JsonTestHelper.AssertJsonEqual(stringValue, element.ToString());
}
else
{
Assert.True(false, "Must be JsonElement");
}
using (var stream = new MemoryStream())
using (var writer = new Utf8JsonWriter(stream))
{
converter.Write(writer, (T)objectValue, options);
writer.Flush();
Assert.Equal(stringValue, Encoding.UTF8.GetString(stream.ToArray()));
writer.Reset(stream);
converter.Write(writer, (T)objectValue, null); // Test with null option
writer.Flush();
Assert.Equal(stringValue + stringValue, Encoding.UTF8.GetString(stream.ToArray()));
}
}
[Fact]
public static void Options_GetConverter_GivesCorrectDefaultConverterAndReadWriteSuccess()
{
var options = new JsonSerializerOptions();
GenericConverterTestHelper<bool>("BooleanConverter", true, "true", options);
GenericConverterTestHelper<byte>("ByteConverter", (byte)128, "128", options);
GenericConverterTestHelper<char>("CharConverter", 'A', "\"A\"", options);
GenericConverterTestHelper<double>("DoubleConverter", 15.1d, "15.1", options);
GenericConverterTestHelper<SampleEnum>("EnumConverter`1", SampleEnum.Two, "2", options);
GenericConverterTestHelper<short>("Int16Converter", (short)5, "5", options);
GenericConverterTestHelper<int>("Int32Converter", -100, "-100", options);
GenericConverterTestHelper<long>("Int64Converter", (long)11111, "11111", options);
GenericConverterTestHelper<sbyte>("SByteConverter", (sbyte)-121, "-121", options);
GenericConverterTestHelper<float>("SingleConverter", 14.5f, "14.5", options);
GenericConverterTestHelper<string>("StringConverter", "Hello", "\"Hello\"", options);
GenericConverterTestHelper<ushort>("UInt16Converter", (ushort)1206, "1206", options);
GenericConverterTestHelper<uint>("UInt32Converter", (uint)3333, "3333", options);
GenericConverterTestHelper<ulong>("UInt64Converter", (ulong)44444, "44444", options);
GenericConverterTestHelper<decimal>("DecimalConverter", 3.3m, "3.3", options);
GenericConverterTestHelper<byte[]>("ByteArrayConverter", new byte[] { 1, 2, 3, 4 }, "\"AQIDBA==\"", options);
GenericConverterTestHelper<DateTime>("DateTimeConverter", new DateTime(2018, 12, 3), "\"2018-12-03T00:00:00\"", options);
GenericConverterTestHelper<DateTimeOffset>("DateTimeOffsetConverter", new DateTimeOffset(new DateTime(2018, 12, 3, 00, 00, 00, DateTimeKind.Utc)), "\"2018-12-03T00:00:00+00:00\"", options);
Guid testGuid = new Guid();
GenericConverterTestHelper<Guid>("GuidConverter", testGuid, $"\"{testGuid}\"", options);
GenericConverterTestHelper<Uri>("UriConverter", new Uri("http://test.com"), "\"http://test.com\"", options);
}
[Fact]
// KeyValuePair converter is not a primitive JsonConverter<T>, so there's no way to properly flow the ReadStack state in the direct call to the serializer.
[ActiveIssue("https://github.com/dotnet/runtime/issues/50205")]
public static void Options_GetConverter_GivesCorrectKeyValuePairConverter()
{
GenericConverterTestHelper<KeyValuePair<string, string>>(
converterName: "KeyValuePairConverter`2",
objectValue: new KeyValuePair<string, string>("key", "value"),
stringValue: @"{""Key"":""key"",""Value"":""value""}",
options: new JsonSerializerOptions(),
nullOptionOkay: false);
}
[Fact]
public static void Options_GetConverter_GivesCorrectCustomConverterAndReadWriteSuccess()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new CustomConverterTests.LongArrayConverter());
GenericConverterTestHelper<long[]>("LongArrayConverter", new long[] { 1, 2, 3, 4 }, "\"1,2,3,4\"", options);
}
private static void GenericConverterTestHelper<T>(string converterName, object objectValue, string stringValue, JsonSerializerOptions options, bool nullOptionOkay = true)
{
JsonConverter<T> converter = (JsonConverter<T>)options.GetConverter(typeof(T));
Assert.True(converter.CanConvert(typeof(T)));
Assert.Equal(converterName, converter.GetType().Name);
ReadOnlySpan<byte> data = Encoding.UTF8.GetBytes(stringValue);
Utf8JsonReader reader = new Utf8JsonReader(data);
reader.Read();
T valueRead = converter.Read(ref reader, typeof(T), nullOptionOkay ? null: options);
Assert.Equal(objectValue, valueRead);
if (reader.TokenType != JsonTokenType.EndObject)
{
valueRead = converter.Read(ref reader, typeof(T), options); // Test with given option if reader position haven't advanced.
Assert.Equal(objectValue, valueRead);
}
using (var stream = new MemoryStream())
using (var writer = new Utf8JsonWriter(stream))
{
converter.Write(writer, (T)objectValue, options);
writer.Flush();
Assert.Equal(stringValue, Encoding.UTF8.GetString(stream.ToArray()));
writer.Reset(stream);
converter.Write(writer, (T)objectValue, nullOptionOkay ? null : options);
writer.Flush();
Assert.Equal(stringValue + stringValue, Encoding.UTF8.GetString(stream.ToArray()));
}
}
[Fact]
public static void CopyConstructor_OriginalLocked()
{
JsonSerializerOptions options = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
// Perform serialization with options, after which it will be locked.
JsonSerializer.Serialize("1", options);
Assert.Throws<InvalidOperationException>(() => options.ReferenceHandler = ReferenceHandler.Preserve);
var newOptions = new JsonSerializerOptions(options);
VerifyOptionsEqual(options, newOptions);
// No exception is thrown on mutating the new options instance because it is "unlocked".
newOptions.ReferenceHandler = ReferenceHandler.Preserve;
}
[Fact]
public static void CopyConstructor_MaxDepth()
{
static void RunTest(int maxDepth, int effectiveMaxDepth)
{
var options = new JsonSerializerOptions { MaxDepth = maxDepth };
var newOptions = new JsonSerializerOptions(options);
Assert.Equal(maxDepth, options.MaxDepth);
Assert.Equal(maxDepth, newOptions.MaxDepth);
// Test for default effective max depth in exception message.
var myList = new List<object>();
myList.Add(myList);
string effectiveMaxDepthAsStr = effectiveMaxDepth.ToString();
JsonException ex = Assert.Throws<JsonException>(() => JsonSerializer.Serialize(myList, options));
Assert.Contains(effectiveMaxDepthAsStr, ex.ToString());
ex = Assert.Throws<JsonException>(() => JsonSerializer.Serialize(myList, newOptions));
Assert.Contains(effectiveMaxDepthAsStr, ex.ToString());
}
// Zero max depth
RunTest(0, 64);
// Specified max depth
RunTest(25, 25);
}
[Fact]
public static void CopyConstructor_CopiesAllPublicProperties()
{
JsonSerializerOptions options = GetFullyPopulatedOptionsInstance();
var newOptions = new JsonSerializerOptions(options);
VerifyOptionsEqual(options, newOptions);
}
[Fact]
public static void CopyConstructor_NullInput()
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => new JsonSerializerOptions(null));
Assert.Contains("options", ex.ToString());
}
[Fact]
public static void JsonSerializerOptions_Default_MatchesDefaultConstructor()
{
var options = new JsonSerializerOptions();
JsonSerializerOptions optionsSingleton = JsonSerializerOptions.Default;
VerifyOptionsEqual(options, optionsSingleton);
}
[Fact]
public static void JsonSerializerOptions_Default_ReturnsSameInstance()
{
Assert.Same(JsonSerializerOptions.Default, JsonSerializerOptions.Default);
}
[Fact]
public static void JsonSerializerOptions_Default_IsReadOnly()
{
var optionsSingleton = JsonSerializerOptions.Default;
Assert.Throws<InvalidOperationException>(() => optionsSingleton.IncludeFields = true);
Assert.Throws<InvalidOperationException>(() => optionsSingleton.Converters.Add(new JsonStringEnumConverter()));
}
[Fact]
public static void DefaultSerializerOptions_General()
{
var options = new JsonSerializerOptions();
var newOptions = new JsonSerializerOptions(JsonSerializerDefaults.General);
VerifyOptionsEqual(options, newOptions);
}
[Fact]
public static void PredefinedSerializerOptions_Web()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
Assert.True(options.PropertyNameCaseInsensitive);
Assert.Same(JsonNamingPolicy.CamelCase, options.PropertyNamingPolicy);
Assert.Equal(JsonNumberHandling.AllowReadingFromString, options.NumberHandling);
}
[Theory]
[InlineData(-1)]
[InlineData(2)]
public static void PredefinedSerializerOptions_UnhandledDefaults(int enumValue)
{
var outOfRangeSerializerDefaults = (JsonSerializerDefaults)enumValue;
Assert.Throws<ArgumentOutOfRangeException>(() => new JsonSerializerOptions(outOfRangeSerializerDefaults));
}
private static JsonSerializerOptions GetFullyPopulatedOptionsInstance()
{
var options = new JsonSerializerOptions();
foreach (PropertyInfo property in typeof(JsonSerializerOptions).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
Type propertyType = property.PropertyType;
if (propertyType == typeof(bool))
{
// IgnoreNullValues and DefaultIgnoreCondition cannot be active at the same time.
if (property.Name != "IgnoreNullValues")
{
property.SetValue(options, true);
}
}
if (propertyType == typeof(int))
{
property.SetValue(options, 32);
}
else if (propertyType == typeof(IList<JsonConverter>))
{
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new ConverterForInt32());
}
else if (propertyType == typeof(JavaScriptEncoder))
{
options.Encoder = JavaScriptEncoder.Default;
}
else if (propertyType == typeof(JsonNamingPolicy))
{
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.DictionaryKeyPolicy = new SimpleSnakeCasePolicy();
}
else if (propertyType == typeof(ReferenceHandler))
{
options.ReferenceHandler = ReferenceHandler.Preserve;
}
else if (propertyType.IsValueType)
{
options.ReadCommentHandling = JsonCommentHandling.Disallow;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
options.NumberHandling = JsonNumberHandling.AllowReadingFromString;
options.UnknownTypeHandling = JsonUnknownTypeHandling.JsonNode;
}
else
{
// An exception thrown from here means this test should be updated
// to reflect any newly added properties on JsonSerializerOptions.
property.SetValue(options, Activator.CreateInstance(propertyType));
}
}
return options;
}
private static void VerifyOptionsEqual(JsonSerializerOptions options, JsonSerializerOptions newOptions)
{
foreach (PropertyInfo property in typeof(JsonSerializerOptions).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
Type propertyType = property.PropertyType;
if (propertyType == typeof(bool))
{
Assert.Equal((bool)property.GetValue(options), (bool)property.GetValue(newOptions));
}
else if (propertyType == typeof(int))
{
Assert.Equal((int)property.GetValue(options), (int)property.GetValue(newOptions));
}
else if (typeof(IEnumerable).IsAssignableFrom(propertyType))
{
var list1 = (IList<JsonConverter>)property.GetValue(options);
var list2 = (IList<JsonConverter>)property.GetValue(newOptions);
Assert.Equal(list1.Count, list2.Count);
for (int i = 0; i < list1.Count; i++)
{
Assert.Same(list1[i], list2[i]);
}
}
else if (propertyType.IsValueType)
{
if (property.Name == "ReadCommentHandling")
{
Assert.Equal(options.ReadCommentHandling, newOptions.ReadCommentHandling);
}
else if (property.Name == "DefaultIgnoreCondition")
{
Assert.Equal(options.DefaultIgnoreCondition, newOptions.DefaultIgnoreCondition);
}
else if (property.Name == "NumberHandling")
{
Assert.Equal(options.NumberHandling, newOptions.NumberHandling);
}
else if (property.Name == "UnknownTypeHandling")
{
Assert.Equal(options.UnknownTypeHandling, newOptions.UnknownTypeHandling);
}
else
{
Assert.True(false, $"Public option was added to JsonSerializerOptions but not copied in the copy ctor: {property.Name}");
}
}
else
{
Assert.Same(property.GetValue(options), property.GetValue(newOptions));
}
}
}
[Fact]
public static void CopyConstructor_IgnoreNullValuesCopied()
{
var options = new JsonSerializerOptions { IgnoreNullValues = true };
var newOptions = new JsonSerializerOptions(options);
VerifyOptionsEqual(options, newOptions);
}
[Fact]
public static void CannotSetBoth_IgnoreNullValues_And_DefaultIgnoreCondition()
{
// Set IgnoreNullValues first.
JsonSerializerOptions options = new JsonSerializerOptions { IgnoreNullValues = true };
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(
() => options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault);
string exAsStr = ex.ToString();
Assert.Contains("IgnoreNullValues", exAsStr);
Assert.Contains("DefaultIgnoreCondition", exAsStr);
options.IgnoreNullValues = false;
// We can set the property now.
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
// Set DefaultIgnoreCondition first.
options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault };
Assert.Throws<InvalidOperationException>(
() => options.IgnoreNullValues = true);
options.DefaultIgnoreCondition = JsonIgnoreCondition.Never;
// We can set the property now.
options.IgnoreNullValues = true;
}
[Fact]
public static void CannotSet_DefaultIgnoreCondition_To_Always()
{
Assert.Throws<ArgumentException>(() => new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.Always });
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/36605")]
public static void ConverterRead_VerifyInvalidTypeToConvertFails()
{
var options = new JsonSerializerOptions();
Type typeToConvert = typeof(KeyValuePair<int, int>);
byte[] bytes = Encoding.UTF8.GetBytes(@"{""Key"":1,""Value"":2}");
JsonConverter<KeyValuePair<int, int>> converter =
(JsonConverter<KeyValuePair<int, int>>)options.GetConverter(typeToConvert);
// Baseline
var reader = new Utf8JsonReader(bytes);
reader.Read();
KeyValuePair<int, int> kvp = converter.Read(ref reader, typeToConvert, options);
Assert.Equal(1, kvp.Key);
Assert.Equal(2, kvp.Value);
// Test
reader = new Utf8JsonReader(bytes);
reader.Read();
try
{
converter.Read(ref reader, typeof(Dictionary<string, int>), options);
}
catch (Exception ex)
{
if (!(ex is InvalidOperationException))
{
throw ex;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class OptionsTests
{
private class TestConverter : JsonConverter<bool>
{
public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
[Fact]
public static void SetOptionsFail()
{
var options = new JsonSerializerOptions();
// Verify these do not throw.
options.Converters.Clear();
TestConverter tc = new TestConverter();
options.Converters.Add(tc);
options.Converters.Insert(0, new TestConverter());
options.Converters.Remove(tc);
options.Converters.RemoveAt(0);
// Add one item for later.
options.Converters.Add(tc);
// Verify converter collection throws on null adds.
Assert.Throws<ArgumentNullException>(() => options.Converters.Add(null));
Assert.Throws<ArgumentNullException>(() => options.Converters.Insert(0, null));
Assert.Throws<ArgumentNullException>(() => options.Converters[0] = null);
// Perform serialization.
JsonSerializer.Deserialize<int>("1", options);
// Verify defaults and ensure getters do not throw.
Assert.False(options.AllowTrailingCommas);
Assert.Equal(16 * 1024, options.DefaultBufferSize);
Assert.Null(options.DictionaryKeyPolicy);
Assert.Null(options.Encoder);
Assert.False(options.IgnoreNullValues);
Assert.Equal(0, options.MaxDepth);
Assert.False(options.PropertyNameCaseInsensitive);
Assert.Null(options.PropertyNamingPolicy);
Assert.Equal(JsonCommentHandling.Disallow, options.ReadCommentHandling);
Assert.False(options.WriteIndented);
Assert.Equal(tc, options.Converters[0]);
Assert.True(options.Converters.Contains(tc));
options.Converters.CopyTo(new JsonConverter[1] { null }, 0);
Assert.Equal(1, options.Converters.Count);
Assert.False(options.Converters.Equals(tc));
Assert.NotNull(options.Converters.GetEnumerator());
Assert.Equal(0, options.Converters.IndexOf(tc));
Assert.False(options.Converters.IsReadOnly);
// Setters should always throw; we don't check to see if the value is the same or not.
Assert.Throws<InvalidOperationException>(() => options.AllowTrailingCommas = options.AllowTrailingCommas);
Assert.Throws<InvalidOperationException>(() => options.DefaultBufferSize = options.DefaultBufferSize);
Assert.Throws<InvalidOperationException>(() => options.DictionaryKeyPolicy = options.DictionaryKeyPolicy);
Assert.Throws<InvalidOperationException>(() => options.Encoder = JavaScriptEncoder.Default);
Assert.Throws<InvalidOperationException>(() => options.IgnoreNullValues = options.IgnoreNullValues);
Assert.Throws<InvalidOperationException>(() => options.MaxDepth = options.MaxDepth);
Assert.Throws<InvalidOperationException>(() => options.PropertyNameCaseInsensitive = options.PropertyNameCaseInsensitive);
Assert.Throws<InvalidOperationException>(() => options.PropertyNamingPolicy = options.PropertyNamingPolicy);
Assert.Throws<InvalidOperationException>(() => options.ReadCommentHandling = options.ReadCommentHandling);
Assert.Throws<InvalidOperationException>(() => options.WriteIndented = options.WriteIndented);
Assert.Throws<InvalidOperationException>(() => options.Converters[0] = tc);
Assert.Throws<InvalidOperationException>(() => options.Converters.Clear());
Assert.Throws<InvalidOperationException>(() => options.Converters.Add(tc));
Assert.Throws<InvalidOperationException>(() => options.Converters.Insert(0, new TestConverter()));
Assert.Throws<InvalidOperationException>(() => options.Converters.Remove(tc));
Assert.Throws<InvalidOperationException>(() => options.Converters.RemoveAt(0));
}
[Fact]
public static void DefaultBufferSizeFail()
{
Assert.Throws<ArgumentException>(() => new JsonSerializerOptions().DefaultBufferSize = 0);
Assert.Throws<ArgumentException>(() => new JsonSerializerOptions().DefaultBufferSize = -1);
}
[Fact]
public static void DefaultBufferSize()
{
var options = new JsonSerializerOptions();
Assert.Equal(16 * 1024, options.DefaultBufferSize);
options.DefaultBufferSize = 1;
Assert.Equal(1, options.DefaultBufferSize);
}
[Fact]
public static void AllowTrailingCommas()
{
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<int[]>("[1,]"));
var options = new JsonSerializerOptions();
options.AllowTrailingCommas = true;
int[] value = JsonSerializer.Deserialize<int[]>("[1,]", options);
Assert.Equal(1, value[0]);
}
[Fact]
public static void WriteIndented()
{
var obj = new BasicCompany();
obj.Initialize();
// Verify default value.
string json = JsonSerializer.Serialize(obj);
Assert.DoesNotContain(Environment.NewLine, json);
// Verify default value on options.
var options = new JsonSerializerOptions();
json = JsonSerializer.Serialize(obj, options);
Assert.DoesNotContain(Environment.NewLine, json);
// Change the value on options.
options = new JsonSerializerOptions();
options.WriteIndented = true;
json = JsonSerializer.Serialize(obj, options);
Assert.Contains(Environment.NewLine, json);
}
[Fact]
public static void ExtensionDataUsesReaderOptions()
{
// We just verify trailing commas.
const string json = @"{""MyIntMissing"":2,}";
// Verify baseline without options.
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithExtensionProperty>(json));
// Verify baseline with options.
var options = new JsonSerializerOptions();
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithExtensionProperty>(json, options));
// Set AllowTrailingCommas to true.
options = new JsonSerializerOptions();
options.AllowTrailingCommas = true;
JsonSerializer.Deserialize<ClassWithExtensionProperty>(json, options);
}
[Fact]
public static void ExtensionDataUsesWriterOptions()
{
// We just verify whitespace.
ClassWithExtensionProperty obj = JsonSerializer.Deserialize<ClassWithExtensionProperty>(@"{""MyIntMissing"":2}");
// Verify baseline without options.
string json = JsonSerializer.Serialize(obj);
Assert.False(HasNewLine());
// Verify baseline with options.
var options = new JsonSerializerOptions();
json = JsonSerializer.Serialize(obj, options);
Assert.False(HasNewLine());
// Set AllowTrailingCommas to true.
options = new JsonSerializerOptions();
options.WriteIndented = true;
json = JsonSerializer.Serialize(obj, options);
Assert.True(HasNewLine());
bool HasNewLine()
{
int iEnd = json.IndexOf("2", json.IndexOf("MyIntMissing"));
return json.Substring(iEnd + 1).StartsWith(Environment.NewLine);
}
}
[Fact]
public static void ReadCommentHandling()
{
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<object>("/* commment */"));
var options = new JsonSerializerOptions();
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<object>("/* commment */", options));
options = new JsonSerializerOptions();
options.ReadCommentHandling = JsonCommentHandling.Skip;
int value = JsonSerializer.Deserialize<int>("1 /* commment */", options);
Assert.Equal(1, value);
}
[Theory]
[InlineData(-1)]
[InlineData((int)JsonCommentHandling.Allow)]
[InlineData(3)]
[InlineData(byte.MaxValue)]
[InlineData(byte.MaxValue + 3)] // Other values, like byte.MaxValue + 1 overflows to 0 (i.e. JsonCommentHandling.Disallow), which is valid.
[InlineData(byte.MaxValue + 4)]
public static void ReadCommentHandlingDoesNotSupportAllow(int enumValue)
{
var options = new JsonSerializerOptions();
Assert.Throws<ArgumentOutOfRangeException>("value", () => options.ReadCommentHandling = (JsonCommentHandling)enumValue);
}
[Theory]
[InlineData(-1)]
public static void TestDepthInvalid(int depth)
{
var options = new JsonSerializerOptions();
Assert.Throws<ArgumentOutOfRangeException>("value", () => options.MaxDepth = depth);
}
[Fact]
public static void MaxDepthRead()
{
JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data);
var options = new JsonSerializerOptions();
JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data, options);
options = new JsonSerializerOptions();
options.MaxDepth = 1;
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data, options));
}
private class TestClassForEncoding
{
public string MyString { get; set; }
}
// This is a copy of the test data in System.Text.Json.Tests.JsonEncodedTextTests.JsonEncodedTextStringsCustom
public static IEnumerable<object[]> JsonEncodedTextStringsCustom
{
get
{
return new List<object[]>
{
new object[] { "age", "\\u0061\\u0067\\u0065" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\"\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\u0022\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u0022\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0032\\u0032\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9>>>>>\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003E\\u003E\\u003E\\u003E\\u003E\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003e\\u003e\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0033\\u0065\\\\\\u0075\\u0030\\u0030\\u0033\\u0065\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003E\\u003E\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0033\\u0045\\\\\\u0075\\u0030\\u0030\\u0033\\u0045\u00EA\u00EA\u00EA\u00EA\u00EA" },
};
}
}
[Theory]
[MemberData(nameof(JsonEncodedTextStringsCustom))]
public static void CustomEncoderAllowLatin1Supplement(string message, string expectedMessage)
{
// Latin-1 Supplement block starts from U+0080 and ends at U+00FF
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.Latin1Supplement);
var options = new JsonSerializerOptions();
options.Encoder = encoder;
var obj = new TestClassForEncoding();
obj.MyString = message;
string baselineJson = JsonSerializer.Serialize(obj);
Assert.DoesNotContain(expectedMessage, baselineJson);
string json = JsonSerializer.Serialize(obj, options);
Assert.Contains(expectedMessage, json);
obj = JsonSerializer.Deserialize<TestClassForEncoding>(json);
Assert.Equal(obj.MyString, message);
}
public static IEnumerable<object[]> JsonEncodedTextStringsCustomAll
{
get
{
return new List<object[]>
{
new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA" },
new object[] { "a\u0467\u0466a", "a\u0467\u0466a" },
};
}
}
[Theory]
[MemberData(nameof(JsonEncodedTextStringsCustomAll))]
public static void JsonEncodedTextStringsCustomAllowAll(string message, string expectedMessage)
{
// Allow all unicode values (except forbidden characters which we don't have in test data here)
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
var options = new JsonSerializerOptions();
options.Encoder = encoder;
var obj = new TestClassForEncoding();
obj.MyString = message;
string baselineJson = JsonSerializer.Serialize(obj);
Assert.DoesNotContain(expectedMessage, baselineJson);
string json = JsonSerializer.Serialize(obj, options);
Assert.Contains(expectedMessage, json);
obj = JsonSerializer.Deserialize<TestClassForEncoding>(json);
Assert.Equal(obj.MyString, message);
}
[Fact]
public static void Options_GetConverterForObjectJsonElement_GivesCorrectConverter()
{
GenericObjectOrJsonElementConverterTestHelper<object>("ObjectConverter", new object(), "{}");
JsonElement element = JsonDocument.Parse("[3]").RootElement;
GenericObjectOrJsonElementConverterTestHelper<JsonElement>("JsonElementConverter", element, "[3]");
}
private static void GenericObjectOrJsonElementConverterTestHelper<T>(string converterName, object objectValue, string stringValue)
{
var options = new JsonSerializerOptions();
JsonConverter<T> converter = (JsonConverter<T>)options.GetConverter(typeof(T));
Assert.Equal(converterName, converter.GetType().Name);
ReadOnlySpan<byte> data = Encoding.UTF8.GetBytes(stringValue);
Utf8JsonReader reader = new Utf8JsonReader(data);
reader.Read();
T readValue = converter.Read(ref reader, typeof(T), options);
if (readValue is JsonElement element)
{
JsonTestHelper.AssertJsonEqual(stringValue, element.ToString());
}
else
{
Assert.True(false, "Must be JsonElement");
}
using (var stream = new MemoryStream())
using (var writer = new Utf8JsonWriter(stream))
{
converter.Write(writer, (T)objectValue, options);
writer.Flush();
Assert.Equal(stringValue, Encoding.UTF8.GetString(stream.ToArray()));
writer.Reset(stream);
converter.Write(writer, (T)objectValue, null); // Test with null option
writer.Flush();
Assert.Equal(stringValue + stringValue, Encoding.UTF8.GetString(stream.ToArray()));
}
}
[Fact]
public static void Options_GetConverter_GivesCorrectDefaultConverterAndReadWriteSuccess()
{
var options = new JsonSerializerOptions();
GenericConverterTestHelper<bool>("BooleanConverter", true, "true", options);
GenericConverterTestHelper<byte>("ByteConverter", (byte)128, "128", options);
GenericConverterTestHelper<char>("CharConverter", 'A', "\"A\"", options);
GenericConverterTestHelper<double>("DoubleConverter", 15.1d, "15.1", options);
GenericConverterTestHelper<SampleEnum>("EnumConverter`1", SampleEnum.Two, "2", options);
GenericConverterTestHelper<short>("Int16Converter", (short)5, "5", options);
GenericConverterTestHelper<int>("Int32Converter", -100, "-100", options);
GenericConverterTestHelper<long>("Int64Converter", (long)11111, "11111", options);
GenericConverterTestHelper<sbyte>("SByteConverter", (sbyte)-121, "-121", options);
GenericConverterTestHelper<float>("SingleConverter", 14.5f, "14.5", options);
GenericConverterTestHelper<string>("StringConverter", "Hello", "\"Hello\"", options);
GenericConverterTestHelper<ushort>("UInt16Converter", (ushort)1206, "1206", options);
GenericConverterTestHelper<uint>("UInt32Converter", (uint)3333, "3333", options);
GenericConverterTestHelper<ulong>("UInt64Converter", (ulong)44444, "44444", options);
GenericConverterTestHelper<decimal>("DecimalConverter", 3.3m, "3.3", options);
GenericConverterTestHelper<byte[]>("ByteArrayConverter", new byte[] { 1, 2, 3, 4 }, "\"AQIDBA==\"", options);
GenericConverterTestHelper<DateTime>("DateTimeConverter", new DateTime(2018, 12, 3), "\"2018-12-03T00:00:00\"", options);
GenericConverterTestHelper<DateTimeOffset>("DateTimeOffsetConverter", new DateTimeOffset(new DateTime(2018, 12, 3, 00, 00, 00, DateTimeKind.Utc)), "\"2018-12-03T00:00:00+00:00\"", options);
Guid testGuid = new Guid();
GenericConverterTestHelper<Guid>("GuidConverter", testGuid, $"\"{testGuid}\"", options);
GenericConverterTestHelper<Uri>("UriConverter", new Uri("http://test.com"), "\"http://test.com\"", options);
}
[Fact]
// KeyValuePair converter is not a primitive JsonConverter<T>, so there's no way to properly flow the ReadStack state in the direct call to the serializer.
[ActiveIssue("https://github.com/dotnet/runtime/issues/50205")]
public static void Options_GetConverter_GivesCorrectKeyValuePairConverter()
{
GenericConverterTestHelper<KeyValuePair<string, string>>(
converterName: "KeyValuePairConverter`2",
objectValue: new KeyValuePair<string, string>("key", "value"),
stringValue: @"{""Key"":""key"",""Value"":""value""}",
options: new JsonSerializerOptions(),
nullOptionOkay: false);
}
[Fact]
public static void Options_GetConverter_GivesCorrectCustomConverterAndReadWriteSuccess()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new CustomConverterTests.LongArrayConverter());
GenericConverterTestHelper<long[]>("LongArrayConverter", new long[] { 1, 2, 3, 4 }, "\"1,2,3,4\"", options);
}
private static void GenericConverterTestHelper<T>(string converterName, object objectValue, string stringValue, JsonSerializerOptions options, bool nullOptionOkay = true)
{
JsonConverter<T> converter = (JsonConverter<T>)options.GetConverter(typeof(T));
Assert.True(converter.CanConvert(typeof(T)));
Assert.Equal(converterName, converter.GetType().Name);
ReadOnlySpan<byte> data = Encoding.UTF8.GetBytes(stringValue);
Utf8JsonReader reader = new Utf8JsonReader(data);
reader.Read();
T valueRead = converter.Read(ref reader, typeof(T), nullOptionOkay ? null: options);
Assert.Equal(objectValue, valueRead);
if (reader.TokenType != JsonTokenType.EndObject)
{
valueRead = converter.Read(ref reader, typeof(T), options); // Test with given option if reader position haven't advanced.
Assert.Equal(objectValue, valueRead);
}
using (var stream = new MemoryStream())
using (var writer = new Utf8JsonWriter(stream))
{
converter.Write(writer, (T)objectValue, options);
writer.Flush();
Assert.Equal(stringValue, Encoding.UTF8.GetString(stream.ToArray()));
writer.Reset(stream);
converter.Write(writer, (T)objectValue, nullOptionOkay ? null : options);
writer.Flush();
Assert.Equal(stringValue + stringValue, Encoding.UTF8.GetString(stream.ToArray()));
}
}
[Fact]
public static void CopyConstructor_OriginalLocked()
{
JsonSerializerOptions options = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
// Perform serialization with options, after which it will be locked.
JsonSerializer.Serialize("1", options);
Assert.Throws<InvalidOperationException>(() => options.ReferenceHandler = ReferenceHandler.Preserve);
var newOptions = new JsonSerializerOptions(options);
VerifyOptionsEqual(options, newOptions);
// No exception is thrown on mutating the new options instance because it is "unlocked".
newOptions.ReferenceHandler = ReferenceHandler.Preserve;
}
[Fact]
public static void CopyConstructor_MaxDepth()
{
static void RunTest(int maxDepth, int effectiveMaxDepth)
{
var options = new JsonSerializerOptions { MaxDepth = maxDepth };
var newOptions = new JsonSerializerOptions(options);
Assert.Equal(maxDepth, options.MaxDepth);
Assert.Equal(maxDepth, newOptions.MaxDepth);
// Test for default effective max depth in exception message.
var myList = new List<object>();
myList.Add(myList);
string effectiveMaxDepthAsStr = effectiveMaxDepth.ToString();
JsonException ex = Assert.Throws<JsonException>(() => JsonSerializer.Serialize(myList, options));
Assert.Contains(effectiveMaxDepthAsStr, ex.ToString());
ex = Assert.Throws<JsonException>(() => JsonSerializer.Serialize(myList, newOptions));
Assert.Contains(effectiveMaxDepthAsStr, ex.ToString());
}
// Zero max depth
RunTest(0, 64);
// Specified max depth
RunTest(25, 25);
}
[Fact]
public static void CopyConstructor_CopiesAllPublicProperties()
{
JsonSerializerOptions options = GetFullyPopulatedOptionsInstance();
var newOptions = new JsonSerializerOptions(options);
VerifyOptionsEqual(options, newOptions);
}
[Fact]
public static void CopyConstructor_NullInput()
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => new JsonSerializerOptions(null));
Assert.Contains("options", ex.ToString());
}
[Fact]
public static void JsonSerializerOptions_Default_MatchesDefaultConstructor()
{
var options = new JsonSerializerOptions();
JsonSerializerOptions optionsSingleton = JsonSerializerOptions.Default;
VerifyOptionsEqual(options, optionsSingleton);
}
[Fact]
public static void JsonSerializerOptions_Default_ReturnsSameInstance()
{
Assert.Same(JsonSerializerOptions.Default, JsonSerializerOptions.Default);
}
[Fact]
public static void JsonSerializerOptions_Default_IsReadOnly()
{
var optionsSingleton = JsonSerializerOptions.Default;
Assert.Throws<InvalidOperationException>(() => optionsSingleton.IncludeFields = true);
Assert.Throws<InvalidOperationException>(() => optionsSingleton.Converters.Add(new JsonStringEnumConverter()));
Assert.Throws<InvalidOperationException>(() => optionsSingleton.AddContext<JsonContext>());
Assert.Throws<InvalidOperationException>(() => new JsonContext(optionsSingleton));
}
[Fact]
public static void DefaultSerializerOptions_General()
{
var options = new JsonSerializerOptions();
var newOptions = new JsonSerializerOptions(JsonSerializerDefaults.General);
VerifyOptionsEqual(options, newOptions);
}
[Fact]
public static void PredefinedSerializerOptions_Web()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
Assert.True(options.PropertyNameCaseInsensitive);
Assert.Same(JsonNamingPolicy.CamelCase, options.PropertyNamingPolicy);
Assert.Equal(JsonNumberHandling.AllowReadingFromString, options.NumberHandling);
}
[Theory]
[InlineData(-1)]
[InlineData(2)]
public static void PredefinedSerializerOptions_UnhandledDefaults(int enumValue)
{
var outOfRangeSerializerDefaults = (JsonSerializerDefaults)enumValue;
Assert.Throws<ArgumentOutOfRangeException>(() => new JsonSerializerOptions(outOfRangeSerializerDefaults));
}
private static JsonSerializerOptions GetFullyPopulatedOptionsInstance()
{
var options = new JsonSerializerOptions();
foreach (PropertyInfo property in typeof(JsonSerializerOptions).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
Type propertyType = property.PropertyType;
if (propertyType == typeof(bool))
{
// IgnoreNullValues and DefaultIgnoreCondition cannot be active at the same time.
if (property.Name != "IgnoreNullValues")
{
property.SetValue(options, true);
}
}
if (propertyType == typeof(int))
{
property.SetValue(options, 32);
}
else if (propertyType == typeof(IList<JsonConverter>))
{
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new ConverterForInt32());
}
else if (propertyType == typeof(JavaScriptEncoder))
{
options.Encoder = JavaScriptEncoder.Default;
}
else if (propertyType == typeof(JsonNamingPolicy))
{
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.DictionaryKeyPolicy = new SimpleSnakeCasePolicy();
}
else if (propertyType == typeof(ReferenceHandler))
{
options.ReferenceHandler = ReferenceHandler.Preserve;
}
else if (propertyType.IsValueType)
{
options.ReadCommentHandling = JsonCommentHandling.Disallow;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
options.NumberHandling = JsonNumberHandling.AllowReadingFromString;
options.UnknownTypeHandling = JsonUnknownTypeHandling.JsonNode;
}
else
{
// An exception thrown from here means this test should be updated
// to reflect any newly added properties on JsonSerializerOptions.
property.SetValue(options, Activator.CreateInstance(propertyType));
}
}
return options;
}
private static void VerifyOptionsEqual(JsonSerializerOptions options, JsonSerializerOptions newOptions)
{
foreach (PropertyInfo property in typeof(JsonSerializerOptions).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
Type propertyType = property.PropertyType;
if (propertyType == typeof(bool))
{
Assert.Equal((bool)property.GetValue(options), (bool)property.GetValue(newOptions));
}
else if (propertyType == typeof(int))
{
Assert.Equal((int)property.GetValue(options), (int)property.GetValue(newOptions));
}
else if (typeof(IEnumerable).IsAssignableFrom(propertyType))
{
var list1 = (IList<JsonConverter>)property.GetValue(options);
var list2 = (IList<JsonConverter>)property.GetValue(newOptions);
Assert.Equal(list1.Count, list2.Count);
for (int i = 0; i < list1.Count; i++)
{
Assert.Same(list1[i], list2[i]);
}
}
else if (propertyType.IsValueType)
{
if (property.Name == "ReadCommentHandling")
{
Assert.Equal(options.ReadCommentHandling, newOptions.ReadCommentHandling);
}
else if (property.Name == "DefaultIgnoreCondition")
{
Assert.Equal(options.DefaultIgnoreCondition, newOptions.DefaultIgnoreCondition);
}
else if (property.Name == "NumberHandling")
{
Assert.Equal(options.NumberHandling, newOptions.NumberHandling);
}
else if (property.Name == "UnknownTypeHandling")
{
Assert.Equal(options.UnknownTypeHandling, newOptions.UnknownTypeHandling);
}
else
{
Assert.True(false, $"Public option was added to JsonSerializerOptions but not copied in the copy ctor: {property.Name}");
}
}
else
{
Assert.Same(property.GetValue(options), property.GetValue(newOptions));
}
}
}
[Fact]
public static void CopyConstructor_IgnoreNullValuesCopied()
{
var options = new JsonSerializerOptions { IgnoreNullValues = true };
var newOptions = new JsonSerializerOptions(options);
VerifyOptionsEqual(options, newOptions);
}
[Fact]
public static void CannotSetBoth_IgnoreNullValues_And_DefaultIgnoreCondition()
{
// Set IgnoreNullValues first.
JsonSerializerOptions options = new JsonSerializerOptions { IgnoreNullValues = true };
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(
() => options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault);
string exAsStr = ex.ToString();
Assert.Contains("IgnoreNullValues", exAsStr);
Assert.Contains("DefaultIgnoreCondition", exAsStr);
options.IgnoreNullValues = false;
// We can set the property now.
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
// Set DefaultIgnoreCondition first.
options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault };
Assert.Throws<InvalidOperationException>(
() => options.IgnoreNullValues = true);
options.DefaultIgnoreCondition = JsonIgnoreCondition.Never;
// We can set the property now.
options.IgnoreNullValues = true;
}
[Fact]
public static void CannotSet_DefaultIgnoreCondition_To_Always()
{
Assert.Throws<ArgumentException>(() => new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.Always });
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/36605")]
public static void ConverterRead_VerifyInvalidTypeToConvertFails()
{
var options = new JsonSerializerOptions();
Type typeToConvert = typeof(KeyValuePair<int, int>);
byte[] bytes = Encoding.UTF8.GetBytes(@"{""Key"":1,""Value"":2}");
JsonConverter<KeyValuePair<int, int>> converter =
(JsonConverter<KeyValuePair<int, int>>)options.GetConverter(typeToConvert);
// Baseline
var reader = new Utf8JsonReader(bytes);
reader.Read();
KeyValuePair<int, int> kvp = converter.Read(ref reader, typeToConvert, options);
Assert.Equal(1, kvp.Key);
Assert.Equal(2, kvp.Value);
// Test
reader = new Utf8JsonReader(bytes);
reader.Read();
try
{
converter.Read(ref reader, typeof(Dictionary<string, int>), options);
}
catch (Exception ex)
{
if (!(ex is InvalidOperationException))
{
throw ex;
}
}
}
}
}
| 1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/mono/mono/tests/pinvoke13.cs | //
// pinvoke13.cs
//
// Tests for pinvoke name mangling
//
using System;
using System.Runtime.InteropServices;
public class Tests
{
/*
* These tests exercise the search order associated with the different charset values.
*/
/* This should call NameManglingAnsi */
[DllImport("libtest", CharSet=CharSet.Ansi)]
private static extern int NameManglingAnsi (string data);
/* This should call NameManglingAnsi2A */
[DllImport ("libtest", CharSet=CharSet.Ansi)]
private static extern int NameManglingAnsi2 (string data);
/* This should call NameManglingUnicodeW */
[DllImport ("libtest", CharSet=CharSet.Unicode)]
private static extern int NameManglingUnicode (string data);
/* This should call NameManglingUnicode2 */
[DllImport ("libtest", CharSet=CharSet.Unicode)]
private static extern int NameManglingUnicode2 (string data);
/* This should call NameManglingAutoW under windows, and NameManglingAuto under unix */
[DllImport ("libtest", CharSet=CharSet.Auto)]
private static extern int NameManglingAuto (string s);
public static int Main (String[] args) {
int res;
res = NameManglingAnsi ("ABC");
if (res != 198)
return 1;
res = NameManglingAnsi2 ("ABC");
if (res != 198)
return 2;
res = NameManglingUnicode ("ABC");
if (res != 198)
return 3;
res = NameManglingUnicode2 ("ABC");
if (res != 198)
return 4;
res = NameManglingAuto ("ABC");
if (res != 0)
return 5;
return 0;
}
}
| //
// pinvoke13.cs
//
// Tests for pinvoke name mangling
//
using System;
using System.Runtime.InteropServices;
public class Tests
{
/*
* These tests exercise the search order associated with the different charset values.
*/
/* This should call NameManglingAnsi */
[DllImport("libtest", CharSet=CharSet.Ansi)]
private static extern int NameManglingAnsi (string data);
/* This should call NameManglingAnsi2A */
[DllImport ("libtest", CharSet=CharSet.Ansi)]
private static extern int NameManglingAnsi2 (string data);
/* This should call NameManglingUnicodeW */
[DllImport ("libtest", CharSet=CharSet.Unicode)]
private static extern int NameManglingUnicode (string data);
/* This should call NameManglingUnicode2 */
[DllImport ("libtest", CharSet=CharSet.Unicode)]
private static extern int NameManglingUnicode2 (string data);
/* This should call NameManglingAutoW under windows, and NameManglingAuto under unix */
[DllImport ("libtest", CharSet=CharSet.Auto)]
private static extern int NameManglingAuto (string s);
public static int Main (String[] args) {
int res;
res = NameManglingAnsi ("ABC");
if (res != 198)
return 1;
res = NameManglingAnsi2 ("ABC");
if (res != 198)
return 2;
res = NameManglingUnicode ("ABC");
if (res != 198)
return 3;
res = NameManglingUnicode2 ("ABC");
if (res != 198)
return 4;
res = NameManglingAuto ("ABC");
if (res != 0)
return 5;
return 0;
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/mono/mono/tests/iface-large.cs | interface IA {
void f001 ();
void f002 ();
void f003 ();
void f004 ();
void f005 ();
void f006 ();
void f007 ();
void f008 ();
void f009 ();
void f010 ();
void f011 ();
void f012 ();
void f013 ();
void f014 ();
void f015 ();
void f016 ();
void f017 ();
void f018 ();
void f019 ();
void f020 ();
void f021 ();
void f022 ();
void f023 ();
void f024 ();
void f025 ();
void f026 ();
void f027 ();
void f028 ();
void f029 ();
void f030 ();
void f031 ();
void f032 ();
void f033 ();
void f034 ();
void f035 ();
void f036 ();
void f037 ();
void f038 ();
void f039 ();
void f040 ();
void f041 ();
void f042 ();
void f043 ();
void f044 ();
void f045 ();
void f046 ();
void f047 ();
void f048 ();
void f049 ();
void f050 ();
void f051 ();
void f052 ();
void f053 ();
void f054 ();
void f055 ();
void f056 ();
void f057 ();
void f058 ();
void f059 ();
void f060 ();
void f061 ();
void f062 ();
void f063 ();
void f064 ();
void f065 ();
void f066 ();
void f067 ();
void f068 ();
void f069 ();
void f070 ();
void f071 ();
void f072 ();
void f073 ();
void f074 ();
void f075 ();
void f076 ();
void f077 ();
void f078 ();
void f079 ();
void f080 ();
void f081 ();
void f082 ();
void f083 ();
void f084 ();
void f085 ();
void f086 ();
void f087 ();
void f088 ();
void f089 ();
void f090 ();
void f091 ();
void f092 ();
void f093 ();
void f094 ();
void f095 ();
void f096 ();
void f097 ();
void f098 ();
void f099 ();
void f100 ();
void f101 ();
void f102 ();
void f103 ();
void f104 ();
void f105 ();
void f106 ();
void f107 ();
void f108 ();
void f109 ();
void f110 ();
void f111 ();
void f112 ();
void f113 ();
void f114 ();
void f115 ();
void f116 ();
void f117 ();
void f118 ();
void f119 ();
void f120 ();
void f121 ();
void f122 ();
void f123 ();
void f124 ();
void f125 ();
void f126 ();
void f127 ();
void f128 ();
void f129 ();
void f130 ();
void f131 ();
void f132 ();
void f133 ();
void f134 ();
void f135 ();
void f136 ();
void f137 ();
void f138 ();
void f139 ();
void f140 ();
void f141 ();
void f142 ();
void f143 ();
void f144 ();
void f145 ();
void f146 ();
void f147 ();
void f148 ();
void f149 ();
void f150 ();
void f151 ();
void f152 ();
void f153 ();
void f154 ();
void f155 ();
void f156 ();
void f157 ();
void f158 ();
void f159 ();
void f160 ();
void f161 ();
void f162 ();
void f163 ();
void f164 ();
void f165 ();
void f166 ();
void f167 ();
void f168 ();
void f169 ();
void f170 ();
void f171 ();
void f172 ();
void f173 ();
void f174 ();
void f175 ();
void f176 ();
void f177 ();
void f178 ();
void f179 ();
void f180 ();
void f181 ();
void f182 ();
void f183 ();
void f184 ();
void f185 ();
void f186 ();
void f187 ();
void f188 ();
void f189 ();
void f190 ();
void f191 ();
void f192 ();
void f193 ();
void f194 ();
void f195 ();
void f196 ();
void f197 ();
void f198 ();
void f199 ();
void f200 ();
void f201 ();
void f202 ();
void f203 ();
void f204 ();
void f205 ();
void f206 ();
void f207 ();
void f208 ();
void f209 ();
void f210 ();
void f211 ();
void f212 ();
void f213 ();
void f214 ();
void f215 ();
void f216 ();
void f217 ();
void f218 ();
void f219 ();
void f220 ();
void f221 ();
void f222 ();
void f223 ();
void f224 ();
void f225 ();
void f226 ();
void f227 ();
void f228 ();
void f229 ();
void f230 ();
void f231 ();
void f232 ();
void f233 ();
void f234 ();
void f235 ();
void f236 ();
void f237 ();
void f238 ();
void f239 ();
void f240 ();
void f241 ();
void f242 ();
void f243 ();
void f244 ();
void f245 ();
void f246 ();
void f247 ();
void f248 ();
void f249 ();
void f250 ();
void f251 ();
void f252 ();
void f253 ();
void f254 ();
void f255 ();
void f256 ();
void f257 ();
void f258 ();
void f259 ();
void f260 ();
void f261 ();
void f262 ();
void f263 ();
void f264 ();
void f265 ();
void f266 ();
void f267 ();
void f268 ();
void f269 ();
void f270 ();
void f271 ();
void f272 ();
void f273 ();
void f274 ();
void f275 ();
void f276 ();
void f277 ();
void f278 ();
void f279 ();
void f280 ();
void f281 ();
void f282 ();
void f283 ();
void f284 ();
void f285 ();
void f286 ();
void f287 ();
void f288 ();
void f289 ();
void f290 ();
void f291 ();
void f292 ();
void f293 ();
void f294 ();
void f295 ();
void f296 ();
void f297 ();
void f298 ();
void f299 ();
void f300 ();
void f301 ();
void f302 ();
void f303 ();
void f304 ();
void f305 ();
void f306 ();
void f307 ();
void f308 ();
void f309 ();
void f310 ();
void f311 ();
void f312 ();
void f313 ();
void f314 ();
void f315 ();
void f316 ();
void f317 ();
void f318 ();
void f319 ();
void f320 ();
void f321 ();
void f322 ();
void f323 ();
void f324 ();
void f325 ();
void f326 ();
void f327 ();
void f328 ();
void f329 ();
void f330 ();
void f331 ();
void f332 ();
void f333 ();
void f334 ();
void f335 ();
void f336 ();
void f337 ();
void f338 ();
void f339 ();
void f340 ();
void f341 ();
void f342 ();
void f343 ();
void f344 ();
void f345 ();
void f346 ();
void f347 ();
void f348 ();
void f349 ();
void f350 ();
void f351 ();
void f352 ();
void f353 ();
void f354 ();
void f355 ();
void f356 ();
void f357 ();
void f358 ();
void f359 ();
void f360 ();
void f361 ();
void f362 ();
void f363 ();
void f364 ();
void f365 ();
void f366 ();
void f367 ();
void f368 ();
void f369 ();
void f370 ();
void f371 ();
void f372 ();
void f373 ();
void f374 ();
void f375 ();
void f376 ();
void f377 ();
void f378 ();
void f379 ();
void f380 ();
void f381 ();
void f382 ();
void f383 ();
void f384 ();
void f385 ();
void f386 ();
void f387 ();
void f388 ();
void f389 ();
void f390 ();
void f391 ();
void f392 ();
void f393 ();
void f394 ();
void f395 ();
void f396 ();
void f397 ();
void f398 ();
void f399 ();
void f400 ();
void f401 ();
void f402 ();
void f403 ();
void f404 ();
void f405 ();
void f406 ();
void f407 ();
void f408 ();
void f409 ();
void f410 ();
void f411 ();
void f412 ();
void f413 ();
void f414 ();
void f415 ();
void f416 ();
void f417 ();
void f418 ();
void f419 ();
void f420 ();
void f421 ();
void f422 ();
void f423 ();
void f424 ();
void f425 ();
void f426 ();
void f427 ();
void f428 ();
void f429 ();
void f430 ();
void f431 ();
void f432 ();
void f433 ();
void f434 ();
void f435 ();
void f436 ();
void f437 ();
void f438 ();
void f439 ();
void f440 ();
void f441 ();
void f442 ();
void f443 ();
void f444 ();
void f445 ();
void f446 ();
void f447 ();
void f448 ();
void f449 ();
void f450 ();
void f451 ();
void f452 ();
void f453 ();
void f454 ();
void f455 ();
void f456 ();
void f457 ();
void f458 ();
void f459 ();
void f460 ();
void f461 ();
void f462 ();
void f463 ();
void f464 ();
void f465 ();
void f466 ();
void f467 ();
void f468 ();
void f469 ();
void f470 ();
void f471 ();
void f472 ();
void f473 ();
void f474 ();
void f475 ();
void f476 ();
void f477 ();
void f478 ();
void f479 ();
void f480 ();
void f481 ();
void f482 ();
void f483 ();
void f484 ();
void f485 ();
void f486 ();
void f487 ();
void f488 ();
void f489 ();
void f490 ();
void f491 ();
void f492 ();
void f493 ();
void f494 ();
void f495 ();
void f496 ();
void f497 ();
void f498 ();
void f499 ();
void f500 ();
void f501 ();
void f502 ();
void f503 ();
void f504 ();
void f505 ();
void f506 ();
void f507 ();
void f508 ();
void f509 ();
void f510 ();
void f511 ();
void f512 ();
void f513 ();
void f514 ();
void f515 ();
void f516 ();
void f517 ();
void f518 ();
void f519 ();
void f520 ();
void f521 ();
void f522 ();
void f523 ();
void f524 ();
void f525 ();
void f526 ();
void f527 ();
void f528 ();
void f529 ();
void f530 ();
void f531 ();
void f532 ();
void f533 ();
void f534 ();
void f535 ();
void f536 ();
void f537 ();
void f538 ();
void f539 ();
void f540 ();
void f541 ();
void f542 ();
void f543 ();
void f544 ();
void f545 ();
void f546 ();
void f547 ();
void f548 ();
void f549 ();
void f550 ();
void f551 ();
void f552 ();
void f553 ();
void f554 ();
void f555 ();
void f556 ();
void f557 ();
void f558 ();
void f559 ();
void f560 ();
void f561 ();
void f562 ();
void f563 ();
void f564 ();
void f565 ();
void f566 ();
void f567 ();
void f568 ();
void f569 ();
void f570 ();
void f571 ();
void f572 ();
void f573 ();
void f574 ();
void f575 ();
void f576 ();
void f577 ();
void f578 ();
void f579 ();
void f580 ();
void f581 ();
void f582 ();
void f583 ();
void f584 ();
void f585 ();
void f586 ();
void f587 ();
void f588 ();
void f589 ();
void f590 ();
void f591 ();
void f592 ();
void f593 ();
void f594 ();
void f595 ();
void f596 ();
void f597 ();
void f598 ();
void f599 ();
void f600 ();
void f601 ();
void f602 ();
void f603 ();
void f604 ();
void f605 ();
void f606 ();
void f607 ();
void f608 ();
void f609 ();
void f610 ();
void f611 ();
void f612 ();
void f613 ();
void f614 ();
void f615 ();
void f616 ();
void f617 ();
void f618 ();
void f619 ();
void f620 ();
void f621 ();
void f622 ();
void f623 ();
void f624 ();
void f625 ();
void f626 ();
void f627 ();
void f628 ();
void f629 ();
void f630 ();
void f631 ();
void f632 ();
void f633 ();
void f634 ();
void f635 ();
void f636 ();
void f637 ();
void f638 ();
void f639 ();
void f640 ();
void f641 ();
void f642 ();
void f643 ();
void f644 ();
void f645 ();
void f646 ();
void f647 ();
void f648 ();
void f649 ();
void f650 ();
void f651 ();
void f652 ();
void f653 ();
void f654 ();
void f655 ();
void f656 ();
void f657 ();
void f658 ();
void f659 ();
void f660 ();
void f661 ();
void f662 ();
void f663 ();
void f664 ();
void f665 ();
void f666 ();
void f667 ();
void f668 ();
void f669 ();
void f670 ();
void f671 ();
void f672 ();
void f673 ();
void f674 ();
void f675 ();
void f676 ();
void f677 ();
void f678 ();
void f679 ();
void f680 ();
void f681 ();
void f682 ();
void f683 ();
void f684 ();
void f685 ();
void f686 ();
void f687 ();
void f688 ();
void f689 ();
void f690 ();
void f691 ();
void f692 ();
void f693 ();
void f694 ();
void f695 ();
void f696 ();
void f697 ();
void f698 ();
void f699 ();
void f700 ();
void f701 ();
void f702 ();
void f703 ();
void f704 ();
void f705 ();
void f706 ();
void f707 ();
void f708 ();
void f709 ();
void f710 ();
void f711 ();
void f712 ();
void f713 ();
void f714 ();
void f715 ();
void f716 ();
void f717 ();
void f718 ();
void f719 ();
void f720 ();
void f721 ();
void f722 ();
void f723 ();
void f724 ();
void f725 ();
void f726 ();
void f727 ();
void f728 ();
void f729 ();
void f730 ();
void f731 ();
void f732 ();
void f733 ();
void f734 ();
void f735 ();
void f736 ();
void f737 ();
void f738 ();
void f739 ();
void f740 ();
void f741 ();
void f742 ();
void f743 ();
void f744 ();
void f745 ();
void f746 ();
void f747 ();
void f748 ();
void f749 ();
void f750 ();
}
class Test {
static void Main ()
{
if (typeof (IA).GetMethods ().Length != 750)
throw new System.Exception ();
}
}
| interface IA {
void f001 ();
void f002 ();
void f003 ();
void f004 ();
void f005 ();
void f006 ();
void f007 ();
void f008 ();
void f009 ();
void f010 ();
void f011 ();
void f012 ();
void f013 ();
void f014 ();
void f015 ();
void f016 ();
void f017 ();
void f018 ();
void f019 ();
void f020 ();
void f021 ();
void f022 ();
void f023 ();
void f024 ();
void f025 ();
void f026 ();
void f027 ();
void f028 ();
void f029 ();
void f030 ();
void f031 ();
void f032 ();
void f033 ();
void f034 ();
void f035 ();
void f036 ();
void f037 ();
void f038 ();
void f039 ();
void f040 ();
void f041 ();
void f042 ();
void f043 ();
void f044 ();
void f045 ();
void f046 ();
void f047 ();
void f048 ();
void f049 ();
void f050 ();
void f051 ();
void f052 ();
void f053 ();
void f054 ();
void f055 ();
void f056 ();
void f057 ();
void f058 ();
void f059 ();
void f060 ();
void f061 ();
void f062 ();
void f063 ();
void f064 ();
void f065 ();
void f066 ();
void f067 ();
void f068 ();
void f069 ();
void f070 ();
void f071 ();
void f072 ();
void f073 ();
void f074 ();
void f075 ();
void f076 ();
void f077 ();
void f078 ();
void f079 ();
void f080 ();
void f081 ();
void f082 ();
void f083 ();
void f084 ();
void f085 ();
void f086 ();
void f087 ();
void f088 ();
void f089 ();
void f090 ();
void f091 ();
void f092 ();
void f093 ();
void f094 ();
void f095 ();
void f096 ();
void f097 ();
void f098 ();
void f099 ();
void f100 ();
void f101 ();
void f102 ();
void f103 ();
void f104 ();
void f105 ();
void f106 ();
void f107 ();
void f108 ();
void f109 ();
void f110 ();
void f111 ();
void f112 ();
void f113 ();
void f114 ();
void f115 ();
void f116 ();
void f117 ();
void f118 ();
void f119 ();
void f120 ();
void f121 ();
void f122 ();
void f123 ();
void f124 ();
void f125 ();
void f126 ();
void f127 ();
void f128 ();
void f129 ();
void f130 ();
void f131 ();
void f132 ();
void f133 ();
void f134 ();
void f135 ();
void f136 ();
void f137 ();
void f138 ();
void f139 ();
void f140 ();
void f141 ();
void f142 ();
void f143 ();
void f144 ();
void f145 ();
void f146 ();
void f147 ();
void f148 ();
void f149 ();
void f150 ();
void f151 ();
void f152 ();
void f153 ();
void f154 ();
void f155 ();
void f156 ();
void f157 ();
void f158 ();
void f159 ();
void f160 ();
void f161 ();
void f162 ();
void f163 ();
void f164 ();
void f165 ();
void f166 ();
void f167 ();
void f168 ();
void f169 ();
void f170 ();
void f171 ();
void f172 ();
void f173 ();
void f174 ();
void f175 ();
void f176 ();
void f177 ();
void f178 ();
void f179 ();
void f180 ();
void f181 ();
void f182 ();
void f183 ();
void f184 ();
void f185 ();
void f186 ();
void f187 ();
void f188 ();
void f189 ();
void f190 ();
void f191 ();
void f192 ();
void f193 ();
void f194 ();
void f195 ();
void f196 ();
void f197 ();
void f198 ();
void f199 ();
void f200 ();
void f201 ();
void f202 ();
void f203 ();
void f204 ();
void f205 ();
void f206 ();
void f207 ();
void f208 ();
void f209 ();
void f210 ();
void f211 ();
void f212 ();
void f213 ();
void f214 ();
void f215 ();
void f216 ();
void f217 ();
void f218 ();
void f219 ();
void f220 ();
void f221 ();
void f222 ();
void f223 ();
void f224 ();
void f225 ();
void f226 ();
void f227 ();
void f228 ();
void f229 ();
void f230 ();
void f231 ();
void f232 ();
void f233 ();
void f234 ();
void f235 ();
void f236 ();
void f237 ();
void f238 ();
void f239 ();
void f240 ();
void f241 ();
void f242 ();
void f243 ();
void f244 ();
void f245 ();
void f246 ();
void f247 ();
void f248 ();
void f249 ();
void f250 ();
void f251 ();
void f252 ();
void f253 ();
void f254 ();
void f255 ();
void f256 ();
void f257 ();
void f258 ();
void f259 ();
void f260 ();
void f261 ();
void f262 ();
void f263 ();
void f264 ();
void f265 ();
void f266 ();
void f267 ();
void f268 ();
void f269 ();
void f270 ();
void f271 ();
void f272 ();
void f273 ();
void f274 ();
void f275 ();
void f276 ();
void f277 ();
void f278 ();
void f279 ();
void f280 ();
void f281 ();
void f282 ();
void f283 ();
void f284 ();
void f285 ();
void f286 ();
void f287 ();
void f288 ();
void f289 ();
void f290 ();
void f291 ();
void f292 ();
void f293 ();
void f294 ();
void f295 ();
void f296 ();
void f297 ();
void f298 ();
void f299 ();
void f300 ();
void f301 ();
void f302 ();
void f303 ();
void f304 ();
void f305 ();
void f306 ();
void f307 ();
void f308 ();
void f309 ();
void f310 ();
void f311 ();
void f312 ();
void f313 ();
void f314 ();
void f315 ();
void f316 ();
void f317 ();
void f318 ();
void f319 ();
void f320 ();
void f321 ();
void f322 ();
void f323 ();
void f324 ();
void f325 ();
void f326 ();
void f327 ();
void f328 ();
void f329 ();
void f330 ();
void f331 ();
void f332 ();
void f333 ();
void f334 ();
void f335 ();
void f336 ();
void f337 ();
void f338 ();
void f339 ();
void f340 ();
void f341 ();
void f342 ();
void f343 ();
void f344 ();
void f345 ();
void f346 ();
void f347 ();
void f348 ();
void f349 ();
void f350 ();
void f351 ();
void f352 ();
void f353 ();
void f354 ();
void f355 ();
void f356 ();
void f357 ();
void f358 ();
void f359 ();
void f360 ();
void f361 ();
void f362 ();
void f363 ();
void f364 ();
void f365 ();
void f366 ();
void f367 ();
void f368 ();
void f369 ();
void f370 ();
void f371 ();
void f372 ();
void f373 ();
void f374 ();
void f375 ();
void f376 ();
void f377 ();
void f378 ();
void f379 ();
void f380 ();
void f381 ();
void f382 ();
void f383 ();
void f384 ();
void f385 ();
void f386 ();
void f387 ();
void f388 ();
void f389 ();
void f390 ();
void f391 ();
void f392 ();
void f393 ();
void f394 ();
void f395 ();
void f396 ();
void f397 ();
void f398 ();
void f399 ();
void f400 ();
void f401 ();
void f402 ();
void f403 ();
void f404 ();
void f405 ();
void f406 ();
void f407 ();
void f408 ();
void f409 ();
void f410 ();
void f411 ();
void f412 ();
void f413 ();
void f414 ();
void f415 ();
void f416 ();
void f417 ();
void f418 ();
void f419 ();
void f420 ();
void f421 ();
void f422 ();
void f423 ();
void f424 ();
void f425 ();
void f426 ();
void f427 ();
void f428 ();
void f429 ();
void f430 ();
void f431 ();
void f432 ();
void f433 ();
void f434 ();
void f435 ();
void f436 ();
void f437 ();
void f438 ();
void f439 ();
void f440 ();
void f441 ();
void f442 ();
void f443 ();
void f444 ();
void f445 ();
void f446 ();
void f447 ();
void f448 ();
void f449 ();
void f450 ();
void f451 ();
void f452 ();
void f453 ();
void f454 ();
void f455 ();
void f456 ();
void f457 ();
void f458 ();
void f459 ();
void f460 ();
void f461 ();
void f462 ();
void f463 ();
void f464 ();
void f465 ();
void f466 ();
void f467 ();
void f468 ();
void f469 ();
void f470 ();
void f471 ();
void f472 ();
void f473 ();
void f474 ();
void f475 ();
void f476 ();
void f477 ();
void f478 ();
void f479 ();
void f480 ();
void f481 ();
void f482 ();
void f483 ();
void f484 ();
void f485 ();
void f486 ();
void f487 ();
void f488 ();
void f489 ();
void f490 ();
void f491 ();
void f492 ();
void f493 ();
void f494 ();
void f495 ();
void f496 ();
void f497 ();
void f498 ();
void f499 ();
void f500 ();
void f501 ();
void f502 ();
void f503 ();
void f504 ();
void f505 ();
void f506 ();
void f507 ();
void f508 ();
void f509 ();
void f510 ();
void f511 ();
void f512 ();
void f513 ();
void f514 ();
void f515 ();
void f516 ();
void f517 ();
void f518 ();
void f519 ();
void f520 ();
void f521 ();
void f522 ();
void f523 ();
void f524 ();
void f525 ();
void f526 ();
void f527 ();
void f528 ();
void f529 ();
void f530 ();
void f531 ();
void f532 ();
void f533 ();
void f534 ();
void f535 ();
void f536 ();
void f537 ();
void f538 ();
void f539 ();
void f540 ();
void f541 ();
void f542 ();
void f543 ();
void f544 ();
void f545 ();
void f546 ();
void f547 ();
void f548 ();
void f549 ();
void f550 ();
void f551 ();
void f552 ();
void f553 ();
void f554 ();
void f555 ();
void f556 ();
void f557 ();
void f558 ();
void f559 ();
void f560 ();
void f561 ();
void f562 ();
void f563 ();
void f564 ();
void f565 ();
void f566 ();
void f567 ();
void f568 ();
void f569 ();
void f570 ();
void f571 ();
void f572 ();
void f573 ();
void f574 ();
void f575 ();
void f576 ();
void f577 ();
void f578 ();
void f579 ();
void f580 ();
void f581 ();
void f582 ();
void f583 ();
void f584 ();
void f585 ();
void f586 ();
void f587 ();
void f588 ();
void f589 ();
void f590 ();
void f591 ();
void f592 ();
void f593 ();
void f594 ();
void f595 ();
void f596 ();
void f597 ();
void f598 ();
void f599 ();
void f600 ();
void f601 ();
void f602 ();
void f603 ();
void f604 ();
void f605 ();
void f606 ();
void f607 ();
void f608 ();
void f609 ();
void f610 ();
void f611 ();
void f612 ();
void f613 ();
void f614 ();
void f615 ();
void f616 ();
void f617 ();
void f618 ();
void f619 ();
void f620 ();
void f621 ();
void f622 ();
void f623 ();
void f624 ();
void f625 ();
void f626 ();
void f627 ();
void f628 ();
void f629 ();
void f630 ();
void f631 ();
void f632 ();
void f633 ();
void f634 ();
void f635 ();
void f636 ();
void f637 ();
void f638 ();
void f639 ();
void f640 ();
void f641 ();
void f642 ();
void f643 ();
void f644 ();
void f645 ();
void f646 ();
void f647 ();
void f648 ();
void f649 ();
void f650 ();
void f651 ();
void f652 ();
void f653 ();
void f654 ();
void f655 ();
void f656 ();
void f657 ();
void f658 ();
void f659 ();
void f660 ();
void f661 ();
void f662 ();
void f663 ();
void f664 ();
void f665 ();
void f666 ();
void f667 ();
void f668 ();
void f669 ();
void f670 ();
void f671 ();
void f672 ();
void f673 ();
void f674 ();
void f675 ();
void f676 ();
void f677 ();
void f678 ();
void f679 ();
void f680 ();
void f681 ();
void f682 ();
void f683 ();
void f684 ();
void f685 ();
void f686 ();
void f687 ();
void f688 ();
void f689 ();
void f690 ();
void f691 ();
void f692 ();
void f693 ();
void f694 ();
void f695 ();
void f696 ();
void f697 ();
void f698 ();
void f699 ();
void f700 ();
void f701 ();
void f702 ();
void f703 ();
void f704 ();
void f705 ();
void f706 ();
void f707 ();
void f708 ();
void f709 ();
void f710 ();
void f711 ();
void f712 ();
void f713 ();
void f714 ();
void f715 ();
void f716 ();
void f717 ();
void f718 ();
void f719 ();
void f720 ();
void f721 ();
void f722 ();
void f723 ();
void f724 ();
void f725 ();
void f726 ();
void f727 ();
void f728 ();
void f729 ();
void f730 ();
void f731 ();
void f732 ();
void f733 ();
void f734 ();
void f735 ();
void f736 ();
void f737 ();
void f738 ();
void f739 ();
void f740 ();
void f741 ();
void f742 ();
void f743 ();
void f744 ();
void f745 ();
void f746 ();
void f747 ();
void f748 ();
void f749 ();
void f750 ();
}
class Test {
static void Main ()
{
if (typeof (IA).GetMethods ().Length != 750)
throw new System.Exception ();
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.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 ILCompiler.DependencyAnalysisFramework;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
// This node represents the concept of a virtual method being used.
// It has no direct depedencies, but may be referred to by conditional static
// dependencies, or static dependencies from elsewhere.
//
// It is used to keep track of uses of virtual methods to ensure that the
// vtables are properly constructed
internal class VirtualMethodUseNode : DependencyNodeCore<NodeFactory>
{
private readonly MethodDesc _decl;
public VirtualMethodUseNode(MethodDesc decl)
{
Debug.Assert(!decl.IsRuntimeDeterminedExactMethod);
Debug.Assert(decl.IsVirtual);
Debug.Assert(!decl.Signature.IsStatic);
// Virtual method use always represents the slot defining method of the virtual.
// Places that might see virtual methods being used through an override need to normalize
// to the slot defining method.
Debug.Assert(MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(decl) == decl);
// Generic virtual methods are tracked by an orthogonal mechanism.
Debug.Assert(!decl.HasInstantiation);
_decl = decl;
}
protected override string GetName(NodeFactory factory) => $"VirtualMethodUse {_decl.ToString()}";
protected override void OnMarked(NodeFactory factory)
{
// If the VTable slice is getting built on demand, the fact that the virtual method is used means
// that the slot is used.
var lazyVTableSlice = factory.VTable(_decl.OwningType) as LazilyBuiltVTableSliceNode;
if (lazyVTableSlice != null)
lazyVTableSlice.AddEntry(factory, _decl);
}
public override bool HasConditionalStaticDependencies => _decl.Context.SupportsUniversalCanon && _decl.OwningType.HasInstantiation && !_decl.OwningType.IsInterface;
public override bool HasDynamicDependencies => false;
public override bool InterestingForDynamicDependencyAnalysis => false;
public override bool StaticDependenciesAreComputed => true;
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
{
DependencyList dependencies = new DependencyList();
MethodDesc canonDecl = _decl.GetCanonMethodTarget(CanonicalFormKind.Specific);
if (canonDecl != _decl)
dependencies.Add(factory.VirtualMethodUse(canonDecl), "Canonical method");
dependencies.Add(factory.VTable(_decl.OwningType), "VTable of a VirtualMethodUse");
// Do not report things like Foo<object, __Canon>.Frob().
if (!_decl.IsCanonicalMethod(CanonicalFormKind.Any) || canonDecl == _decl)
factory.MetadataManager.GetDependenciesDueToVirtualMethodReflectability(ref dependencies, factory, _decl);
if (VariantInterfaceMethodUseNode.IsVariantMethodCall(factory, _decl))
dependencies.Add(factory.VariantInterfaceMethodUse(_decl.GetTypicalMethodDefinition()), "Variant interface call");
return dependencies;
}
public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory factory)
{
Debug.Assert(_decl.OwningType.HasInstantiation);
Debug.Assert(!_decl.OwningType.IsInterface);
Debug.Assert(factory.TypeSystemContext.SupportsUniversalCanon);
DefType universalCanonicalOwningType = (DefType)_decl.OwningType.ConvertToCanonForm(CanonicalFormKind.Universal);
Debug.Assert(universalCanonicalOwningType.IsCanonicalSubtype(CanonicalFormKind.Universal));
if (!factory.VTable(universalCanonicalOwningType).HasFixedSlots)
{
// This code ensures that in cases where we don't structurally force all universal canonical instantiations
// to have full vtables, that we ensure that all vtables are equivalently shaped between universal and non-universal types
return new CombinedDependencyListEntry[] {
new CombinedDependencyListEntry(
factory.VirtualMethodUse(_decl.GetCanonMethodTarget(CanonicalFormKind.Universal)),
factory.NativeLayout.TemplateTypeLayout(universalCanonicalOwningType),
"If universal canon instantiation of method exists, ensure that the universal canonical type has the right set of dependencies")
};
}
else
{
return Array.Empty<CombinedDependencyListEntry>();
}
}
public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<NodeFactory>> markedNodes, int firstNode, NodeFactory factory) => null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using ILCompiler.DependencyAnalysisFramework;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
// This node represents the concept of a virtual method being used.
// It has no direct depedencies, but may be referred to by conditional static
// dependencies, or static dependencies from elsewhere.
//
// It is used to keep track of uses of virtual methods to ensure that the
// vtables are properly constructed
internal class VirtualMethodUseNode : DependencyNodeCore<NodeFactory>
{
private readonly MethodDesc _decl;
public VirtualMethodUseNode(MethodDesc decl)
{
Debug.Assert(!decl.IsRuntimeDeterminedExactMethod);
Debug.Assert(decl.IsVirtual);
Debug.Assert(!decl.Signature.IsStatic);
// Virtual method use always represents the slot defining method of the virtual.
// Places that might see virtual methods being used through an override need to normalize
// to the slot defining method.
Debug.Assert(MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(decl) == decl);
// Generic virtual methods are tracked by an orthogonal mechanism.
Debug.Assert(!decl.HasInstantiation);
_decl = decl;
}
protected override string GetName(NodeFactory factory) => $"VirtualMethodUse {_decl.ToString()}";
protected override void OnMarked(NodeFactory factory)
{
// If the VTable slice is getting built on demand, the fact that the virtual method is used means
// that the slot is used.
var lazyVTableSlice = factory.VTable(_decl.OwningType) as LazilyBuiltVTableSliceNode;
if (lazyVTableSlice != null)
lazyVTableSlice.AddEntry(factory, _decl);
}
public override bool HasConditionalStaticDependencies => _decl.Context.SupportsUniversalCanon && _decl.OwningType.HasInstantiation && !_decl.OwningType.IsInterface;
public override bool HasDynamicDependencies => false;
public override bool InterestingForDynamicDependencyAnalysis => false;
public override bool StaticDependenciesAreComputed => true;
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
{
DependencyList dependencies = new DependencyList();
MethodDesc canonDecl = _decl.GetCanonMethodTarget(CanonicalFormKind.Specific);
if (canonDecl != _decl)
dependencies.Add(factory.VirtualMethodUse(canonDecl), "Canonical method");
dependencies.Add(factory.VTable(_decl.OwningType), "VTable of a VirtualMethodUse");
// Do not report things like Foo<object, __Canon>.Frob().
if (!_decl.IsCanonicalMethod(CanonicalFormKind.Any) || canonDecl == _decl)
factory.MetadataManager.GetDependenciesDueToVirtualMethodReflectability(ref dependencies, factory, _decl);
if (VariantInterfaceMethodUseNode.IsVariantMethodCall(factory, _decl))
dependencies.Add(factory.VariantInterfaceMethodUse(_decl.GetTypicalMethodDefinition()), "Variant interface call");
return dependencies;
}
public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory factory)
{
Debug.Assert(_decl.OwningType.HasInstantiation);
Debug.Assert(!_decl.OwningType.IsInterface);
Debug.Assert(factory.TypeSystemContext.SupportsUniversalCanon);
DefType universalCanonicalOwningType = (DefType)_decl.OwningType.ConvertToCanonForm(CanonicalFormKind.Universal);
Debug.Assert(universalCanonicalOwningType.IsCanonicalSubtype(CanonicalFormKind.Universal));
if (!factory.VTable(universalCanonicalOwningType).HasFixedSlots)
{
// This code ensures that in cases where we don't structurally force all universal canonical instantiations
// to have full vtables, that we ensure that all vtables are equivalently shaped between universal and non-universal types
return new CombinedDependencyListEntry[] {
new CombinedDependencyListEntry(
factory.VirtualMethodUse(_decl.GetCanonMethodTarget(CanonicalFormKind.Universal)),
factory.NativeLayout.TemplateTypeLayout(universalCanonicalOwningType),
"If universal canon instantiation of method exists, ensure that the universal canonical type has the right set of dependencies")
};
}
else
{
return Array.Empty<CombinedDependencyListEntry>();
}
}
public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<NodeFactory>> markedNodes, int firstNode, NodeFactory factory) => null;
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ExtractVector64.Int16.1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ExtractVector64_Int16_1()
{
var test = new ExtractVectorTest__ExtractVector64_Int16_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ExtractVectorTest__ExtractVector64_Int16_1
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int16> _fld1;
public Vector64<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ExtractVectorTest__ExtractVector64_Int16_1 testClass)
{
var result = AdvSimd.ExtractVector64(_fld1, _fld2, ElementIndex);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ExtractVectorTest__ExtractVector64_Int16_1 testClass)
{
fixed (Vector64<Int16>* pFld1 = &_fld1)
fixed (Vector64<Int16>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)pFld1),
AdvSimd.LoadVector64((Int16*)pFld2),
ElementIndex
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly byte ElementIndex = 1;
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector64<Int16> _clsVar1;
private static Vector64<Int16> _clsVar2;
private Vector64<Int16> _fld1;
private Vector64<Int16> _fld2;
private DataTable _dataTable;
static ExtractVectorTest__ExtractVector64_Int16_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
}
public ExtractVectorTest__ExtractVector64_Int16_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ExtractVector64(
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractVector64), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr),
ElementIndex
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractVector64), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)),
ElementIndex
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ExtractVector64(
_clsVar1,
_clsVar2,
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int16>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)(pClsVar1)),
AdvSimd.LoadVector64((Int16*)(pClsVar2)),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ExtractVector64(op1, op2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ExtractVector64(op1, op2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractVectorTest__ExtractVector64_Int16_1();
var result = AdvSimd.ExtractVector64(test._fld1, test._fld2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ExtractVectorTest__ExtractVector64_Int16_1();
fixed (Vector64<Int16>* pFld1 = &test._fld1)
fixed (Vector64<Int16>* pFld2 = &test._fld2)
{
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)pFld1),
AdvSimd.LoadVector64((Int16*)pFld2),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ExtractVector64(_fld1, _fld2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int16>* pFld1 = &_fld1)
fixed (Vector64<Int16>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)pFld1),
AdvSimd.LoadVector64((Int16*)pFld2),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ExtractVector64(test._fld1, test._fld2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)(&test._fld1)),
AdvSimd.LoadVector64((Int16*)(&test._fld2)),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ExtractVector(firstOp, secondOp, ElementIndex, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractVector64)}<Int16>(Vector64<Int16>, Vector64<Int16>, 1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.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 ExtractVector64_Int16_1()
{
var test = new ExtractVectorTest__ExtractVector64_Int16_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ExtractVectorTest__ExtractVector64_Int16_1
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int16> _fld1;
public Vector64<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ExtractVectorTest__ExtractVector64_Int16_1 testClass)
{
var result = AdvSimd.ExtractVector64(_fld1, _fld2, ElementIndex);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ExtractVectorTest__ExtractVector64_Int16_1 testClass)
{
fixed (Vector64<Int16>* pFld1 = &_fld1)
fixed (Vector64<Int16>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)pFld1),
AdvSimd.LoadVector64((Int16*)pFld2),
ElementIndex
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly byte ElementIndex = 1;
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector64<Int16> _clsVar1;
private static Vector64<Int16> _clsVar2;
private Vector64<Int16> _fld1;
private Vector64<Int16> _fld2;
private DataTable _dataTable;
static ExtractVectorTest__ExtractVector64_Int16_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
}
public ExtractVectorTest__ExtractVector64_Int16_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ExtractVector64(
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractVector64), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr),
ElementIndex
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractVector64), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)),
ElementIndex
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ExtractVector64(
_clsVar1,
_clsVar2,
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int16>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)(pClsVar1)),
AdvSimd.LoadVector64((Int16*)(pClsVar2)),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ExtractVector64(op1, op2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ExtractVector64(op1, op2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractVectorTest__ExtractVector64_Int16_1();
var result = AdvSimd.ExtractVector64(test._fld1, test._fld2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ExtractVectorTest__ExtractVector64_Int16_1();
fixed (Vector64<Int16>* pFld1 = &test._fld1)
fixed (Vector64<Int16>* pFld2 = &test._fld2)
{
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)pFld1),
AdvSimd.LoadVector64((Int16*)pFld2),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ExtractVector64(_fld1, _fld2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int16>* pFld1 = &_fld1)
fixed (Vector64<Int16>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)pFld1),
AdvSimd.LoadVector64((Int16*)pFld2),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ExtractVector64(test._fld1, test._fld2, ElementIndex);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ExtractVector64(
AdvSimd.LoadVector64((Int16*)(&test._fld1)),
AdvSimd.LoadVector64((Int16*)(&test._fld2)),
ElementIndex
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ExtractVector(firstOp, secondOp, ElementIndex, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractVector64)}<Int16>(Vector64<Int16>, Vector64<Int16>, 1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
namespace System.Reflection.Emit
{
public sealed class FieldBuilder : FieldInfo
{
internal FieldBuilder()
{
// Prevent generating a default constructor
}
public override FieldAttributes Attributes
{
get
{
return default;
}
}
public override Type DeclaringType
{
get
{
return default;
}
}
public override RuntimeFieldHandle FieldHandle
{
get
{
return default;
}
}
public override Type FieldType
{
get
{
return default;
}
}
public override string Name
{
get
{
return default;
}
}
public override Type ReflectedType
{
get
{
return default;
}
}
public override object[] GetCustomAttributes(bool inherit)
{
return default;
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return default;
}
public override object GetValue(object obj)
{
return default;
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return default;
}
public void SetConstant(object defaultValue)
{
}
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
}
public void SetOffset(int iOffset)
{
}
public override void SetValue(object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
namespace System.Reflection.Emit
{
public sealed class FieldBuilder : FieldInfo
{
internal FieldBuilder()
{
// Prevent generating a default constructor
}
public override FieldAttributes Attributes
{
get
{
return default;
}
}
public override Type DeclaringType
{
get
{
return default;
}
}
public override RuntimeFieldHandle FieldHandle
{
get
{
return default;
}
}
public override Type FieldType
{
get
{
return default;
}
}
public override string Name
{
get
{
return default;
}
}
public override Type ReflectedType
{
get
{
return default;
}
}
public override object[] GetCustomAttributes(bool inherit)
{
return default;
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return default;
}
public override object GetValue(object obj)
{
return default;
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return default;
}
public void SetConstant(object defaultValue)
{
}
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
}
public void SetOffset(int iOffset)
{
}
public override void SetValue(object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Composition.Convention/tests/ConventionBuilderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Composition.Convention.Tests
{
public class ConventionBuilderTests
{
private interface IFoo { }
private class FooImpl : IFoo
{
public string P1 { get; set; }
public string P2 { get; set; }
public IEnumerable<IFoo> P3 { get; set; }
}
private class FooImplWithConstructors : IFoo
{
public FooImplWithConstructors() { }
public FooImplWithConstructors(IEnumerable<IFoo> ids) { }
public FooImplWithConstructors(int id, string name) { }
}
[Fact]
public void MapType_ShouldReturnProjectedAttributesForType()
{
var builder = new ConventionBuilder();
builder.
ForTypesDerivedFrom<IFoo>().
Export<IFoo>();
Attribute[] fooImplAttributes = builder.GetDeclaredAttributes(typeof(FooImpl), typeof(FooImpl).GetTypeInfo());
Attribute[] fooImplWithConstructorsAttributes = builder.GetDeclaredAttributes(typeof(FooImplWithConstructors), typeof(FooImplWithConstructors).GetTypeInfo());
var exports = new List<object>();
exports.AddRange(fooImplAttributes);
exports.AddRange(fooImplWithConstructorsAttributes);
Assert.Equal(2, exports.Count);
foreach (var exportAttribute in exports)
{
Assert.Equal(typeof(IFoo), ((ExportAttribute)exportAttribute).ContractType);
Assert.Null(((ExportAttribute)exportAttribute).ContractName);
}
}
[Fact]
public void MapType_ConventionSelectedConstructor()
{
var builder = new ConventionBuilder();
builder.
ForTypesDerivedFrom<IFoo>().
Export<IFoo>();
TypeInfo fooImplWithConstructorsTypeInfo = typeof(FooImplWithConstructors).GetTypeInfo();
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
ConstructorInfo constructor1 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single();
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count());
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor2).Count());
ConstructorInfo ci = constructor3;
IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci);
Assert.Equal(1, attrs.Count());
Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType());
}
[Fact]
public void MapType_OverridingSelectionOfConventionSelectedConstructor()
{
var builder = new ConventionBuilder();
builder.
ForTypesDerivedFrom<IFoo>().
Export<IFoo>();
builder.ForType<FooImplWithConstructors>()
.SelectConstructor(cis => cis.Single(c => c.GetParameters().Length == 1));
TypeInfo fooImplWithConstructors = typeof(FooImplWithConstructors).GetTypeInfo();
ConstructorInfo constructor1 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single();
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count());
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor3).Count());
ConstructorInfo ci = constructor2;
IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci);
Assert.Equal(1, attrs.Count());
Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType());
}
[Fact]
public void MapType_OverridingSelectionOfConventionSelectedConstructor_WithPartBuilderOfT()
{
var builder = new ConventionBuilder();
builder.
ForTypesDerivedFrom<IFoo>().
Export<IFoo>();
builder.ForType<FooImplWithConstructors>().
SelectConstructor(param => new FooImplWithConstructors(param.Import<IEnumerable<IFoo>>()));
TypeInfo fooImplWithConstructors = typeof(FooImplWithConstructors).GetTypeInfo();
ConstructorInfo constructor1 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single();
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count());
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor3).Count());
ConstructorInfo ci = constructor2;
IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci);
Assert.Equal(1, attrs.Count());
Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Composition.Convention.Tests
{
public class ConventionBuilderTests
{
private interface IFoo { }
private class FooImpl : IFoo
{
public string P1 { get; set; }
public string P2 { get; set; }
public IEnumerable<IFoo> P3 { get; set; }
}
private class FooImplWithConstructors : IFoo
{
public FooImplWithConstructors() { }
public FooImplWithConstructors(IEnumerable<IFoo> ids) { }
public FooImplWithConstructors(int id, string name) { }
}
[Fact]
public void MapType_ShouldReturnProjectedAttributesForType()
{
var builder = new ConventionBuilder();
builder.
ForTypesDerivedFrom<IFoo>().
Export<IFoo>();
Attribute[] fooImplAttributes = builder.GetDeclaredAttributes(typeof(FooImpl), typeof(FooImpl).GetTypeInfo());
Attribute[] fooImplWithConstructorsAttributes = builder.GetDeclaredAttributes(typeof(FooImplWithConstructors), typeof(FooImplWithConstructors).GetTypeInfo());
var exports = new List<object>();
exports.AddRange(fooImplAttributes);
exports.AddRange(fooImplWithConstructorsAttributes);
Assert.Equal(2, exports.Count);
foreach (var exportAttribute in exports)
{
Assert.Equal(typeof(IFoo), ((ExportAttribute)exportAttribute).ContractType);
Assert.Null(((ExportAttribute)exportAttribute).ContractName);
}
}
[Fact]
public void MapType_ConventionSelectedConstructor()
{
var builder = new ConventionBuilder();
builder.
ForTypesDerivedFrom<IFoo>().
Export<IFoo>();
TypeInfo fooImplWithConstructorsTypeInfo = typeof(FooImplWithConstructors).GetTypeInfo();
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
ConstructorInfo constructor1 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single();
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count());
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor2).Count());
ConstructorInfo ci = constructor3;
IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci);
Assert.Equal(1, attrs.Count());
Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType());
}
[Fact]
public void MapType_OverridingSelectionOfConventionSelectedConstructor()
{
var builder = new ConventionBuilder();
builder.
ForTypesDerivedFrom<IFoo>().
Export<IFoo>();
builder.ForType<FooImplWithConstructors>()
.SelectConstructor(cis => cis.Single(c => c.GetParameters().Length == 1));
TypeInfo fooImplWithConstructors = typeof(FooImplWithConstructors).GetTypeInfo();
ConstructorInfo constructor1 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single();
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count());
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor3).Count());
ConstructorInfo ci = constructor2;
IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci);
Assert.Equal(1, attrs.Count());
Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType());
}
[Fact]
public void MapType_OverridingSelectionOfConventionSelectedConstructor_WithPartBuilderOfT()
{
var builder = new ConventionBuilder();
builder.
ForTypesDerivedFrom<IFoo>().
Export<IFoo>();
builder.ForType<FooImplWithConstructors>().
SelectConstructor(param => new FooImplWithConstructors(param.Import<IEnumerable<IFoo>>()));
TypeInfo fooImplWithConstructors = typeof(FooImplWithConstructors).GetTypeInfo();
ConstructorInfo constructor1 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single();
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count());
Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor3).Count());
ConstructorInfo ci = constructor2;
IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci);
Assert.Equal(1, attrs.Count());
Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType());
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.IO.FileSystem/tests/Enumeration/IncludePredicateTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO.Enumeration;
using System.Linq;
using Xunit;
namespace System.IO.Tests.Enumeration
{
public abstract class IncludePredicateTests : FileSystemTest
{
public static IEnumerable<string> GetFileFullPathsWithExtension(string directory,
bool recursive, params string[] extensions)
{
return new FileSystemEnumerable<string>(
directory,
(ref FileSystemEntry entry) => entry.ToFullPath(),
new EnumerationOptions() { RecurseSubdirectories = recursive })
{
ShouldIncludePredicate = (ref FileSystemEntry entry) =>
{
if (entry.IsDirectory) return false;
foreach (string extension in extensions)
{
if (Path.GetExtension(entry.FileName).EndsWith(extension))
return true;
}
return false;
}
};
}
[Fact]
public void CustomExtensionMatch()
{
DirectoryInfo testDirectory = Directory.CreateDirectory(GetTestFilePath());
DirectoryInfo testSubdirectory = Directory.CreateDirectory(Path.Combine(testDirectory.FullName, "Subdirectory"));
FileInfo fileOne = new FileInfo(Path.Combine(testDirectory.FullName, "fileone.htm"));
FileInfo fileTwo = new FileInfo(Path.Combine(testDirectory.FullName, "filetwo.html"));
FileInfo fileThree = new FileInfo(Path.Combine(testSubdirectory.FullName, "filethree.doc"));
FileInfo fileFour = new FileInfo(Path.Combine(testSubdirectory.FullName, "filefour.docx"));
fileOne.Create().Dispose();
fileTwo.Create().Dispose();
fileThree.Create().Dispose();
fileFour.Create().Dispose();
string[] paths = GetFileFullPathsWithExtension(testDirectory.FullName, true, ".htm", ".doc").ToArray();
FSAssert.EqualWhenOrdered(new string[] { fileOne.FullName, fileThree.FullName }, paths);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO.Enumeration;
using System.Linq;
using Xunit;
namespace System.IO.Tests.Enumeration
{
public abstract class IncludePredicateTests : FileSystemTest
{
public static IEnumerable<string> GetFileFullPathsWithExtension(string directory,
bool recursive, params string[] extensions)
{
return new FileSystemEnumerable<string>(
directory,
(ref FileSystemEntry entry) => entry.ToFullPath(),
new EnumerationOptions() { RecurseSubdirectories = recursive })
{
ShouldIncludePredicate = (ref FileSystemEntry entry) =>
{
if (entry.IsDirectory) return false;
foreach (string extension in extensions)
{
if (Path.GetExtension(entry.FileName).EndsWith(extension))
return true;
}
return false;
}
};
}
[Fact]
public void CustomExtensionMatch()
{
DirectoryInfo testDirectory = Directory.CreateDirectory(GetTestFilePath());
DirectoryInfo testSubdirectory = Directory.CreateDirectory(Path.Combine(testDirectory.FullName, "Subdirectory"));
FileInfo fileOne = new FileInfo(Path.Combine(testDirectory.FullName, "fileone.htm"));
FileInfo fileTwo = new FileInfo(Path.Combine(testDirectory.FullName, "filetwo.html"));
FileInfo fileThree = new FileInfo(Path.Combine(testSubdirectory.FullName, "filethree.doc"));
FileInfo fileFour = new FileInfo(Path.Combine(testSubdirectory.FullName, "filefour.docx"));
fileOne.Create().Dispose();
fileTwo.Create().Dispose();
fileThree.Create().Dispose();
fileFour.Create().Dispose();
string[] paths = GetFileFullPathsWithExtension(testDirectory.FullName, true, ".htm", ".doc").ToArray();
FSAssert.EqualWhenOrdered(new string[] { fileOne.FullName, fileThree.FullName }, paths);
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/LoadVector128.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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LoadVector128_Double()
{
var test = new LoadUnaryOpTest__LoadVector128_Double();
if (test.IsSupported)
{
// Validates basic functionality works
test.RunBasicScenario_Load();
// Validates calling via reflection works
test.RunReflectionScenario_Load();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class LoadUnaryOpTest__LoadVector128_Double
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private DataTable _dataTable;
public LoadUnaryOpTest__LoadVector128_Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LoadVector128(
(Double*)(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector128), new Type[] { typeof(Double*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_Load();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(firstOp[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector128)}<Double>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LoadVector128_Double()
{
var test = new LoadUnaryOpTest__LoadVector128_Double();
if (test.IsSupported)
{
// Validates basic functionality works
test.RunBasicScenario_Load();
// Validates calling via reflection works
test.RunReflectionScenario_Load();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class LoadUnaryOpTest__LoadVector128_Double
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private DataTable _dataTable;
public LoadUnaryOpTest__LoadVector128_Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LoadVector128(
(Double*)(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector128), new Type[] { typeof(Double*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_Load();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(firstOp[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector128)}<Double>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Security.Permissions/tests/HostSecurityManagerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Policy;
using Xunit;
namespace System.Security.Permissions.Tests
{
public class HostSecurityManagerTests
{
[Fact]
public static void CallMethods()
{
HostSecurityManager hsm = new HostSecurityManager();
ApplicationTrust at = hsm.DetermineApplicationTrust(new Evidence(), new Evidence(), new TrustManagerContext());
Evidence e = hsm.ProvideAppDomainEvidence(new Evidence());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Policy;
using Xunit;
namespace System.Security.Permissions.Tests
{
public class HostSecurityManagerTests
{
[Fact]
public static void CallMethods()
{
HostSecurityManager hsm = new HostSecurityManager();
ApplicationTrust at = hsm.DetermineApplicationTrust(new Evidence(), new Evidence(), new TrustManagerContext());
Evidence e = hsm.ProvideAppDomainEvidence(new Evidence());
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/Microsoft.Extensions.Logging.Configuration/ref/Microsoft.Extensions.Logging.Configuration.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Extensions.Logging
{
public static partial class LoggingBuilderExtensions
{
public static Microsoft.Extensions.Logging.ILoggingBuilder AddConfiguration(this Microsoft.Extensions.Logging.ILoggingBuilder builder, Microsoft.Extensions.Configuration.IConfiguration configuration) { throw null; }
}
}
namespace Microsoft.Extensions.Logging.Configuration
{
public partial interface ILoggerProviderConfigurationFactory
{
Microsoft.Extensions.Configuration.IConfiguration GetConfiguration(System.Type providerType);
}
public partial interface ILoggerProviderConfiguration<T>
{
Microsoft.Extensions.Configuration.IConfiguration Configuration { get; }
}
public static partial class LoggerProviderOptions
{
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
public static void RegisterProviderOptions<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] TOptions, TProvider>(Microsoft.Extensions.DependencyInjection.IServiceCollection services) where TOptions : class { }
}
public partial class LoggerProviderOptionsChangeTokenSource<TOptions, TProvider> : Microsoft.Extensions.Options.ConfigurationChangeTokenSource<TOptions>
{
public LoggerProviderOptionsChangeTokenSource(Microsoft.Extensions.Logging.Configuration.ILoggerProviderConfiguration<TProvider> providerConfiguration) : base (default(Microsoft.Extensions.Configuration.IConfiguration)) { }
}
public static partial class LoggingBuilderConfigurationExtensions
{
public static void AddConfiguration(this Microsoft.Extensions.Logging.ILoggingBuilder builder) { }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Extensions.Logging
{
public static partial class LoggingBuilderExtensions
{
public static Microsoft.Extensions.Logging.ILoggingBuilder AddConfiguration(this Microsoft.Extensions.Logging.ILoggingBuilder builder, Microsoft.Extensions.Configuration.IConfiguration configuration) { throw null; }
}
}
namespace Microsoft.Extensions.Logging.Configuration
{
public partial interface ILoggerProviderConfigurationFactory
{
Microsoft.Extensions.Configuration.IConfiguration GetConfiguration(System.Type providerType);
}
public partial interface ILoggerProviderConfiguration<T>
{
Microsoft.Extensions.Configuration.IConfiguration Configuration { get; }
}
public static partial class LoggerProviderOptions
{
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")]
public static void RegisterProviderOptions<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] TOptions, TProvider>(Microsoft.Extensions.DependencyInjection.IServiceCollection services) where TOptions : class { }
}
public partial class LoggerProviderOptionsChangeTokenSource<TOptions, TProvider> : Microsoft.Extensions.Options.ConfigurationChangeTokenSource<TOptions>
{
public LoggerProviderOptionsChangeTokenSource(Microsoft.Extensions.Logging.Configuration.ILoggerProviderConfiguration<TProvider> providerConfiguration) : base (default(Microsoft.Extensions.Configuration.IConfiguration)) { }
}
public static partial class LoggingBuilderConfigurationExtensions
{
public static void AddConfiguration(this Microsoft.Extensions.Logging.ILoggingBuilder builder) { }
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class TypeForwardedToAttribute : Attribute
{
public TypeForwardedToAttribute(Type destination)
{
Destination = destination;
}
public Type Destination { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class TypeForwardedToAttribute : Attribute
{
public TypeForwardedToAttribute(Type destination)
{
Destination = destination;
}
public Type Destination { get; }
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/coreclr/tools/Common/TypeSystem/Common/DefType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Internal.TypeSystem
{
/// <summary>
/// Type that is logically equivalent to a type which is defined by a TypeDef
/// record in an ECMA 335 metadata stream - a class, an interface, or a value type.
/// </summary>
public abstract partial class DefType : TypeDesc
{
/// <summary>
/// Gets the namespace of the type.
/// </summary>
public virtual string Namespace => null;
/// <summary>
/// Gets the name of the type as represented in the metadata.
/// </summary>
public virtual string Name => null;
/// <summary>
/// Gets the containing type of this type or null if the type is not nested.
/// </summary>
public virtual DefType ContainingType => null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Internal.TypeSystem
{
/// <summary>
/// Type that is logically equivalent to a type which is defined by a TypeDef
/// record in an ECMA 335 metadata stream - a class, an interface, or a value type.
/// </summary>
public abstract partial class DefType : TypeDesc
{
/// <summary>
/// Gets the namespace of the type.
/// </summary>
public virtual string Namespace => null;
/// <summary>
/// Gets the name of the type as represented in the metadata.
/// </summary>
public virtual string Name => null;
/// <summary>
/// Gets the containing type of this type or null if the type is not nested.
/// </summary>
public virtual DefType ContainingType => null;
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/installer/tests/HostActivation.Tests/WindowsSpecificBehavior.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;
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace Microsoft.DotNet.CoreSetup.Test.HostActivation
{
public class WindowsSpecificBehavior : IClassFixture<WindowsSpecificBehavior.SharedTestState>
{
private SharedTestState sharedTestState;
public WindowsSpecificBehavior(SharedTestState fixture)
{
sharedTestState = fixture;
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Manifests are only supported on Windows OSes.
public void MuxerRunsPortableAppWithoutWindowsOsShims()
{
TestProjectFixture portableAppFixture = sharedTestState.TestWindowsOsShimsAppFixture.Copy();
portableAppFixture.BuiltDotnet.Exec(portableAppFixture.TestProject.AppDll)
.CaptureStdErr()
.CaptureStdOut()
.Execute()
.Should().Pass()
.And.HaveStdOutContaining("Reported OS version is newer or equal to the true OS version - no shims.");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void FrameworkDependent_DLL_LongPath_Succeeds()
{
// Long paths must also be enabled via a machine-wide setting. Only run the test if it is enabled.
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\FileSystem"))
{
if (key == null)
{
return;
}
object longPathsSetting = key.GetValue("LongPathsEnabled", null);
if (longPathsSetting == null || !(longPathsSetting is int) || (int)longPathsSetting == 0)
{
return;
}
}
var fixture = sharedTestState.PortableAppWithLongPathFixture
.Copy();
var dotnet = fixture.BuiltDotnet;
var appDll = fixture.TestProject.AppDll;
dotnet.Exec(appDll, fixture.TestProject.Location)
.CaptureStdErr()
.CaptureStdOut()
.Execute()
.Should().Pass()
.And.HaveStdOutContaining("Hello World")
.And.HaveStdOutContaining("CreateDirectoryW with long path succeeded");
}
// Testing the standalone version (apphost) would require to make a copy of the entire SDK
// and overwrite the apphost.exe in it. Currently this is just too expensive for one test (160MB of data).
public class SharedTestState : IDisposable
{
private static RepoDirectoriesProvider RepoDirectories { get; set; }
public TestProjectFixture PortableAppWithLongPathFixture { get; }
public TestProjectFixture TestWindowsOsShimsAppFixture { get; }
public SharedTestState()
{
RepoDirectories = new RepoDirectoriesProvider();
PortableAppWithLongPathFixture = new TestProjectFixture("PortableAppWithLongPath", RepoDirectories)
.EnsureRestored()
.BuildProject();
TestWindowsOsShimsAppFixture = new TestProjectFixture("TestWindowsOsShimsApp", RepoDirectories)
.EnsureRestored()
.PublishProject();
}
public void Dispose()
{
PortableAppWithLongPathFixture.Dispose();
TestWindowsOsShimsAppFixture.Dispose();
}
}
}
}
| // 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;
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace Microsoft.DotNet.CoreSetup.Test.HostActivation
{
public class WindowsSpecificBehavior : IClassFixture<WindowsSpecificBehavior.SharedTestState>
{
private SharedTestState sharedTestState;
public WindowsSpecificBehavior(SharedTestState fixture)
{
sharedTestState = fixture;
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Manifests are only supported on Windows OSes.
public void MuxerRunsPortableAppWithoutWindowsOsShims()
{
TestProjectFixture portableAppFixture = sharedTestState.TestWindowsOsShimsAppFixture.Copy();
portableAppFixture.BuiltDotnet.Exec(portableAppFixture.TestProject.AppDll)
.CaptureStdErr()
.CaptureStdOut()
.Execute()
.Should().Pass()
.And.HaveStdOutContaining("Reported OS version is newer or equal to the true OS version - no shims.");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void FrameworkDependent_DLL_LongPath_Succeeds()
{
// Long paths must also be enabled via a machine-wide setting. Only run the test if it is enabled.
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\FileSystem"))
{
if (key == null)
{
return;
}
object longPathsSetting = key.GetValue("LongPathsEnabled", null);
if (longPathsSetting == null || !(longPathsSetting is int) || (int)longPathsSetting == 0)
{
return;
}
}
var fixture = sharedTestState.PortableAppWithLongPathFixture
.Copy();
var dotnet = fixture.BuiltDotnet;
var appDll = fixture.TestProject.AppDll;
dotnet.Exec(appDll, fixture.TestProject.Location)
.CaptureStdErr()
.CaptureStdOut()
.Execute()
.Should().Pass()
.And.HaveStdOutContaining("Hello World")
.And.HaveStdOutContaining("CreateDirectoryW with long path succeeded");
}
// Testing the standalone version (apphost) would require to make a copy of the entire SDK
// and overwrite the apphost.exe in it. Currently this is just too expensive for one test (160MB of data).
public class SharedTestState : IDisposable
{
private static RepoDirectoriesProvider RepoDirectories { get; set; }
public TestProjectFixture PortableAppWithLongPathFixture { get; }
public TestProjectFixture TestWindowsOsShimsAppFixture { get; }
public SharedTestState()
{
RepoDirectories = new RepoDirectoriesProvider();
PortableAppWithLongPathFixture = new TestProjectFixture("PortableAppWithLongPath", RepoDirectories)
.EnsureRestored()
.BuildProject();
TestWindowsOsShimsAppFixture = new TestProjectFixture("TestWindowsOsShimsApp", RepoDirectories)
.EnsureRestored()
.PublishProject();
}
public void Dispose()
{
PortableAppWithLongPathFixture.Dispose();
TestWindowsOsShimsAppFixture.Dispose();
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/BuildWasmApps/Wasm.Build.Tests/BuildTestBase.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.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Xml;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
#nullable enable
// [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]
namespace Wasm.Build.Tests
{
public abstract class BuildTestBase : IClassFixture<SharedBuildPerTestClassFixture>, IDisposable
{
public const string DefaultTargetFramework = "net7.0";
public static readonly string NuGetConfigFileNameForDefaultFramework = $"nuget7.config";
protected static readonly bool s_skipProjectCleanup;
protected static readonly string s_xharnessRunnerCommand;
protected string? _projectDir;
protected readonly ITestOutputHelper _testOutput;
protected string _logPath;
protected bool _enablePerTestCleanup = false;
protected SharedBuildPerTestClassFixture _buildContext;
// FIXME: use an envvar to override this
protected static int s_defaultPerTestTimeoutMs = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 30*60*1000 : 15*60*1000;
protected static BuildEnvironment s_buildEnv;
private const string s_runtimePackPathPattern = "\\*\\* MicrosoftNetCoreAppRuntimePackDir : ([^ ]*)";
private static Regex s_runtimePackPathRegex;
public static bool IsUsingWorkloads => s_buildEnv.IsWorkload;
public static bool IsNotUsingWorkloads => !s_buildEnv.IsWorkload;
static BuildTestBase()
{
try
{
s_buildEnv = new BuildEnvironment();
s_runtimePackPathRegex = new Regex(s_runtimePackPathPattern);
s_skipProjectCleanup = !string.IsNullOrEmpty(EnvironmentVariables.SkipProjectCleanup) && EnvironmentVariables.SkipProjectCleanup == "1";
if (string.IsNullOrEmpty(EnvironmentVariables.XHarnessCliPath))
s_xharnessRunnerCommand = "xharness";
else
s_xharnessRunnerCommand = EnvironmentVariables.XHarnessCliPath;
string? nugetPackagesPath = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
if (!string.IsNullOrEmpty(nugetPackagesPath))
{
if (!Directory.Exists(nugetPackagesPath))
Directory.CreateDirectory(nugetPackagesPath);
}
Console.WriteLine ("");
Console.WriteLine ($"==============================================================================================");
Console.WriteLine ($"=============== Running with {(s_buildEnv.IsWorkload ? "Workloads" : "EMSDK")} ===============");
Console.WriteLine ($"==============================================================================================");
Console.WriteLine ("");
}
catch (Exception ex)
{
Console.WriteLine ($"Exception: {ex}");
throw;
}
}
public BuildTestBase(ITestOutputHelper output, SharedBuildPerTestClassFixture buildContext)
{
Console.WriteLine($"{Environment.NewLine}-------- New test --------{Environment.NewLine}");
_buildContext = buildContext;
_testOutput = output;
_logPath = s_buildEnv.LogRootPath; // FIXME:
}
/*
* TODO:
- AOT modes
- llvmonly
- aotinterp
- skipped assemblies should get have their pinvoke/icall stuff scanned
- only buildNative
- aot but no wrapper - check that AppBundle wasn't generated
*/
public static IEnumerable<IEnumerable<object?>> ConfigWithAOTData(bool aot, string? config=null)
{
if (config == null)
{
return new IEnumerable<object?>[]
{
#if TEST_DEBUG_CONFIG_ALSO
// list of each member data - for Debug+@aot
new object?[] { new BuildArgs("placeholder", "Debug", aot, "placeholder", string.Empty) }.AsEnumerable(),
#endif
// list of each member data - for Release+@aot
new object?[] { new BuildArgs("placeholder", "Release", aot, "placeholder", string.Empty) }.AsEnumerable()
}.AsEnumerable();
}
else
{
return new IEnumerable<object?>[]
{
new object?[] { new BuildArgs("placeholder", config, aot, "placeholder", string.Empty) }.AsEnumerable()
};
}
}
protected string RunAndTestWasmApp(BuildArgs buildArgs,
RunHost host,
string id,
Action<string>? test=null,
string? buildDir = null,
int expectedExitCode = 0,
string? args = null,
Dictionary<string, string>? envVars = null,
string targetFramework = DefaultTargetFramework)
{
buildDir ??= _projectDir;
envVars ??= new();
envVars["XHARNESS_DISABLE_COLORED_OUTPUT"] = "true";
if (buildArgs.AOT)
{
envVars["MONO_LOG_LEVEL"] = "debug";
envVars["MONO_LOG_MASK"] = "aot";
}
if (s_buildEnv.EnvVars != null)
{
foreach (var kvp in s_buildEnv.EnvVars)
envVars[kvp.Key] = kvp.Value;
}
string bundleDir = Path.Combine(GetBinDir(baseDir: buildDir, config: buildArgs.Config, targetFramework: targetFramework), "AppBundle");
(string testCommand, string extraXHarnessArgs) = host switch
{
RunHost.V8 => ("wasm test", "--js-file=test-main.js --engine=V8 -v trace"),
RunHost.NodeJS => ("wasm test", "--js-file=test-main.js --engine=NodeJS -v trace"),
_ => ("wasm test-browser", $"-v trace -b {host}")
};
string testLogPath = Path.Combine(_logPath, host.ToString());
string output = RunWithXHarness(
testCommand,
testLogPath,
buildArgs.ProjectName,
bundleDir,
_testOutput,
envVars: envVars,
expectedAppExitCode: expectedExitCode,
extraXHarnessArgs: extraXHarnessArgs,
appArgs: args);
if (buildArgs.AOT)
{
Assert.Contains("AOT: image 'System.Private.CoreLib' found.", output);
Assert.Contains($"AOT: image '{buildArgs.ProjectName}' found.", output);
}
else
{
Assert.DoesNotContain("AOT: image 'System.Private.CoreLib' found.", output);
Assert.DoesNotContain($"AOT: image '{buildArgs.ProjectName}' found.", output);
}
if (test != null)
test(output);
return output;
}
protected static string RunWithXHarness(string testCommand, string testLogPath, string projectName, string bundleDir,
ITestOutputHelper _testOutput, IDictionary<string, string>? envVars=null,
int expectedAppExitCode=0, int xharnessExitCode=0, string? extraXHarnessArgs=null, string? appArgs=null)
{
Console.WriteLine($"============== {testCommand} =============");
Directory.CreateDirectory(testLogPath);
StringBuilder args = new();
args.Append(s_xharnessRunnerCommand);
args.Append($" {testCommand}");
args.Append($" --app=.");
args.Append($" --output-directory={testLogPath}");
args.Append($" --expected-exit-code={expectedAppExitCode}");
args.Append($" {extraXHarnessArgs ?? string.Empty}");
args.Append(" -- ");
// App arguments
if (envVars != null)
{
var setenv = string.Join(' ', envVars.Select(kvp => $"\"--setenv={kvp.Key}={kvp.Value}\"").ToArray());
args.Append($" {setenv}");
}
args.Append($" --run {projectName}.dll");
args.Append($" {appArgs ?? string.Empty}");
_testOutput.WriteLine(string.Empty);
_testOutput.WriteLine($"---------- Running with {testCommand} ---------");
var (exitCode, output) = RunProcess(s_buildEnv.DotNet, _testOutput,
args: args.ToString(),
workingDir: bundleDir,
envVars: envVars,
label: testCommand,
timeoutMs: s_defaultPerTestTimeoutMs);
File.WriteAllText(Path.Combine(testLogPath, $"xharness.log"), output);
if (exitCode != xharnessExitCode)
{
_testOutput.WriteLine($"Exit code: {exitCode}");
if (exitCode != expectedAppExitCode)
throw new XunitException($"[{testCommand}] Exit code, expected {expectedAppExitCode} but got {exitCode} for command: {testCommand} {args}");
}
return output;
}
[MemberNotNull(nameof(_projectDir), nameof(_logPath))]
protected void InitPaths(string id)
{
if (_projectDir == null)
_projectDir = Path.Combine(AppContext.BaseDirectory, id);
_logPath = Path.Combine(s_buildEnv.LogRootPath, id);
Directory.CreateDirectory(_logPath);
}
protected static void InitProjectDir(string dir)
{
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, "Directory.Build.props"), s_buildEnv.DirectoryBuildPropsContents);
File.WriteAllText(Path.Combine(dir, "Directory.Build.targets"), s_buildEnv.DirectoryBuildTargetsContents);
File.Copy(Path.Combine(BuildEnvironment.TestDataPath, NuGetConfigFileNameForDefaultFramework), Path.Combine(dir, "nuget.config"));
Directory.CreateDirectory(Path.Combine(dir, ".nuget"));
}
protected const string SimpleProjectTemplate =
@$"<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>{DefaultTargetFramework}</TargetFramework>
<OutputType>Exe</OutputType>
<WasmGenerateRunV8Script>true</WasmGenerateRunV8Script>
<WasmMainJSPath>test-main.js</WasmMainJSPath>
##EXTRA_PROPERTIES##
</PropertyGroup>
<ItemGroup>
##EXTRA_ITEMS##
</ItemGroup>
##INSERT_AT_END##
</Project>";
protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties="", string extraItems="", string insertAtEnd="", string projectTemplate=SimpleProjectTemplate)
{
if (buildArgs.AOT)
{
extraProperties = $"{extraProperties}\n<RunAOTCompilation>true</RunAOTCompilation>";
extraProperties += $"\n<EmccVerbose>{RuntimeInformation.IsOSPlatform(OSPlatform.Windows)}</EmccVerbose>\n";
}
string projectContents = projectTemplate
.Replace("##EXTRA_PROPERTIES##", extraProperties)
.Replace("##EXTRA_ITEMS##", extraItems)
.Replace("##INSERT_AT_END##", insertAtEnd);
return buildArgs with { ProjectFileContents = projectContents };
}
public (string projectDir, string buildOutput) BuildProject(BuildArgs buildArgs,
string id,
BuildProjectOptions options)
{
string msgPrefix = options.Label != null ? $"[{options.Label}] " : string.Empty;
if (options.UseCache && _buildContext.TryGetBuildFor(buildArgs, out BuildProduct? product))
{
Console.WriteLine ($"Using existing build found at {product.ProjectDir}, with build log at {product.LogFile}");
Assert.True(product.Result, $"Found existing build at {product.ProjectDir}, but it had failed. Check build log at {product.LogFile}");
_projectDir = product.ProjectDir;
// use this test's id for the run logs
_logPath = Path.Combine(s_buildEnv.LogRootPath, id);
return (_projectDir, "FIXME");
}
if (options.CreateProject)
{
InitPaths(id);
InitProjectDir(_projectDir);
options.InitProject?.Invoke();
File.WriteAllText(Path.Combine(_projectDir, $"{buildArgs.ProjectName}.csproj"), buildArgs.ProjectFileContents);
File.Copy(Path.Combine(AppContext.BaseDirectory, "test-main.js"), Path.Combine(_projectDir, "test-main.js"));
}
else if (_projectDir is null)
{
throw new Exception("_projectDir should be set, to use options.createProject=false");
}
StringBuilder sb = new();
sb.Append(options.Publish ? "publish" : "build");
if (options.Publish && options.BuildOnlyAfterPublish)
sb.Append(" -p:WasmBuildOnlyAfterPublish=true");
sb.Append($" {s_buildEnv.DefaultBuildArgs}");
sb.Append($" /p:Configuration={buildArgs.Config}");
string logFileSuffix = options.Label == null ? string.Empty : options.Label.Replace(' ', '_');
string logFilePath = Path.Combine(_logPath, $"{buildArgs.ProjectName}{logFileSuffix}.binlog");
_testOutput.WriteLine($"-------- Building ---------");
_testOutput.WriteLine($"Binlog path: {logFilePath}");
Console.WriteLine($"Binlog path: {logFilePath}");
sb.Append($" /bl:\"{logFilePath}\" /nologo");
sb.Append($" /fl /flp:\"v:diag,LogFile={logFilePath}.log\" /v:{options.Verbosity ?? "minimal"}");
if (buildArgs.ExtraBuildArgs != null)
sb.Append($" {buildArgs.ExtraBuildArgs} ");
Console.WriteLine($"Building {buildArgs.ProjectName} in {_projectDir}");
(int exitCode, string buildOutput) result;
try
{
result = AssertBuild(sb.ToString(), id, expectSuccess: options.ExpectSuccess, envVars: s_buildEnv.EnvVars);
//AssertRuntimePackPath(result.buildOutput);
// check that we are using the correct runtime pack!
if (options.ExpectSuccess)
{
string bundleDir = Path.Combine(GetBinDir(config: buildArgs.Config, targetFramework: options.TargetFramework ?? DefaultTargetFramework), "AppBundle");
AssertBasicAppBundle(bundleDir, buildArgs.ProjectName, buildArgs.Config, options.MainJS ?? "test-main.js", options.HasV8Script, options.HasIcudt, options.DotnetWasmFromRuntimePack ?? !buildArgs.AOT);
}
if (options.UseCache)
_buildContext.CacheBuild(buildArgs, new BuildProduct(_projectDir, logFilePath, true));
return (_projectDir, result.buildOutput);
}
catch
{
if (options.UseCache)
_buildContext.CacheBuild(buildArgs, new BuildProduct(_projectDir, logFilePath, false));
throw;
}
}
public void InitBlazorWasmProjectDir(string id)
{
InitPaths(id);
if (Directory.Exists(_projectDir))
Directory.Delete(_projectDir, recursive: true);
Directory.CreateDirectory(_projectDir);
Directory.CreateDirectory(Path.Combine(_projectDir, ".nuget"));
File.Copy(Path.Combine(BuildEnvironment.TestDataPath, NuGetConfigFileNameForDefaultFramework), Path.Combine(_projectDir, "nuget.config"));
File.Copy(Path.Combine(BuildEnvironment.TestDataPath, "Blazor.Directory.Build.props"), Path.Combine(_projectDir, "Directory.Build.props"));
File.Copy(Path.Combine(BuildEnvironment.TestDataPath, "Blazor.Directory.Build.targets"), Path.Combine(_projectDir, "Directory.Build.targets"));
}
public string CreateWasmTemplateProject(string id, string template = "wasmbrowser")
{
InitPaths(id);
InitProjectDir(id);
new DotNetCommand(s_buildEnv, useDefaultArgs: false)
.WithWorkingDirectory(_projectDir!)
.ExecuteWithCapturedOutput($"new {template}")
.EnsureSuccessful();
return Path.Combine(_projectDir!, $"{id}.csproj");
}
public string CreateBlazorWasmTemplateProject(string id)
{
InitBlazorWasmProjectDir(id);
new DotNetCommand(s_buildEnv, useDefaultArgs: false)
.WithWorkingDirectory(_projectDir!)
.ExecuteWithCapturedOutput("new blazorwasm")
.EnsureSuccessful();
return Path.Combine(_projectDir!, $"{id}.csproj");
}
protected (CommandResult, string) BlazorBuild(BlazorBuildOptions options, params string[] extraArgs)
{
var res = BuildInternal(options.Id, options.Config, publish: false, extraArgs);
AssertDotNetNativeFiles(options.ExpectedFileType, options.Config, forPublish: false, targetFramework: options.TargetFramework);
AssertBlazorBundle(options.Config, isPublish: false, dotnetWasmFromRuntimePack: options.ExpectedFileType == NativeFilesType.FromRuntimePack);
return res;
}
protected (CommandResult, string) BlazorPublish(BlazorBuildOptions options, params string[] extraArgs)
{
var res = BuildInternal(options.Id, options.Config, publish: true, extraArgs);
AssertDotNetNativeFiles(options.ExpectedFileType, options.Config, forPublish: true, targetFramework: options.TargetFramework);
AssertBlazorBundle(options.Config, isPublish: true, dotnetWasmFromRuntimePack: options.ExpectedFileType == NativeFilesType.FromRuntimePack);
if (options.ExpectedFileType == NativeFilesType.AOT)
{
// check for this too, so we know the format is correct for the negative
// test for jsinterop.webassembly.dll
Assert.Contains("Microsoft.JSInterop.dll -> Microsoft.JSInterop.dll.bc", res.Item1.Output);
// make sure this assembly gets skipped
Assert.DoesNotContain("Microsoft.JSInterop.WebAssembly.dll -> Microsoft.JSInterop.WebAssembly.dll.bc", res.Item1.Output);
}
return res;
}
protected (CommandResult, string) BuildInternal(string id, string config, bool publish=false, params string[] extraArgs)
{
string label = publish ? "publish" : "build";
Console.WriteLine($"{Environment.NewLine}** {label} **{Environment.NewLine}");
string logPath = Path.Combine(s_buildEnv.LogRootPath, id, $"{id}-{label}.binlog");
string[] combinedArgs = new[]
{
label, // same as the command name
$"-bl:{logPath}",
$"-p:Configuration={config}",
"-p:BlazorEnableCompression=false",
"-p:_WasmDevel=true"
}.Concat(extraArgs).ToArray();
CommandResult res = new DotNetCommand(s_buildEnv)
.WithWorkingDirectory(_projectDir!)
.ExecuteWithCapturedOutput(combinedArgs)
.EnsureSuccessful();
return (res, logPath);
}
protected void AssertDotNetNativeFiles(NativeFilesType type, string config, bool forPublish, string targetFramework = DefaultTargetFramework)
{
string label = forPublish ? "publish" : "build";
string objBuildDir = Path.Combine(_projectDir!, "obj", config, targetFramework, "wasm", forPublish ? "for-publish" : "for-build");
string binFrameworkDir = FindBlazorBinFrameworkDir(config, forPublish);
string srcDir = type switch
{
NativeFilesType.FromRuntimePack => s_buildEnv.RuntimeNativeDir,
NativeFilesType.Relinked => objBuildDir,
NativeFilesType.AOT => objBuildDir,
_ => throw new ArgumentOutOfRangeException(nameof(type))
};
AssertSameFile(Path.Combine(srcDir, "dotnet.wasm"), Path.Combine(binFrameworkDir, "dotnet.wasm"), label);
// find dotnet*js
string? dotnetJsPath = Directory.EnumerateFiles(binFrameworkDir)
.Where(p => Path.GetFileName(p).StartsWith("dotnet.", StringComparison.OrdinalIgnoreCase) &&
Path.GetFileName(p).EndsWith(".js", StringComparison.OrdinalIgnoreCase))
.SingleOrDefault();
Assert.True(!string.IsNullOrEmpty(dotnetJsPath), $"[{label}] Expected to find dotnet*js in {binFrameworkDir}");
AssertSameFile(Path.Combine(srcDir, "dotnet.js"), dotnetJsPath!, label);
if (type != NativeFilesType.FromRuntimePack)
{
// check that the files are *not* from runtime pack
AssertNotSameFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.wasm"), Path.Combine(binFrameworkDir, "dotnet.wasm"), label);
AssertNotSameFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.js"), dotnetJsPath!, label);
}
}
static void AssertRuntimePackPath(string buildOutput)
{
var match = s_runtimePackPathRegex.Match(buildOutput);
if (!match.Success || match.Groups.Count != 2)
throw new XunitException($"Could not find the pattern in the build output: '{s_runtimePackPathPattern}'.{Environment.NewLine}Build output: {buildOutput}");
string actualPath = match.Groups[1].Value;
if (string.Compare(actualPath, s_buildEnv.RuntimePackDir) != 0)
throw new XunitException($"Runtime pack path doesn't match.{Environment.NewLine}Expected: {s_buildEnv.RuntimePackDir}{Environment.NewLine}Actual: {actualPath}");
}
protected static void AssertBasicAppBundle(string bundleDir, string projectName, string config, string mainJS, bool hasV8Script, bool hasIcudt=true, bool dotnetWasmFromRuntimePack=true)
{
AssertFilesExist(bundleDir, new []
{
"index.html",
mainJS,
"dotnet.timezones.blat",
"dotnet.wasm",
"mono-config.json",
"dotnet.js"
});
AssertFilesExist(bundleDir, new[] { "run-v8.sh" }, expectToExist: hasV8Script);
AssertFilesExist(bundleDir, new[] { "icudt.dat" }, expectToExist: hasIcudt);
string managedDir = Path.Combine(bundleDir, "managed");
AssertFilesExist(managedDir, new[] { $"{projectName}.dll" });
bool is_debug = config == "Debug";
if (is_debug)
{
// Use cecil to check embedded pdb?
// AssertFilesExist(managedDir, new[] { $"{projectName}.pdb" });
//FIXME: um.. what about these? embedded? why is linker omitting them?
//foreach (string file in Directory.EnumerateFiles(managedDir, "*.dll"))
//{
//string pdb = Path.ChangeExtension(file, ".pdb");
//Assert.True(File.Exists(pdb), $"Could not find {pdb} for {file}");
//}
}
AssertDotNetWasmJs(bundleDir, fromRuntimePack: dotnetWasmFromRuntimePack);
}
protected static void AssertDotNetWasmJs(string bundleDir, bool fromRuntimePack)
{
AssertFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.wasm"),
Path.Combine(bundleDir, "dotnet.wasm"),
"Expected dotnet.wasm to be same as the runtime pack",
same: fromRuntimePack);
AssertFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.js"),
Path.Combine(bundleDir, "dotnet.js"),
"Expected dotnet.js to be same as the runtime pack",
same: fromRuntimePack);
}
protected static void AssertFilesDontExist(string dir, string[] filenames, string? label = null)
=> AssertFilesExist(dir, filenames, label, expectToExist: false);
protected static void AssertFilesExist(string dir, string[] filenames, string? label = null, bool expectToExist=true)
{
Assert.True(Directory.Exists(dir), $"[{label}] {dir} not found");
foreach (string filename in filenames)
{
string path = Path.Combine(dir, filename);
if (expectToExist)
{
Assert.True(File.Exists(path),
label != null
? $"{label}: File exists: {path}"
: $"File exists: {path}");
}
else
{
Assert.False(File.Exists(path),
label != null
? $"{label}: {path} should not exist"
: $"{path} should not exist");
}
}
}
protected static void AssertSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: true);
protected static void AssertNotSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: false);
protected static void AssertFile(string file0, string file1, string? label=null, bool same=true)
{
Assert.True(File.Exists(file0), $"{label}: Expected to find {file0}");
Assert.True(File.Exists(file1), $"{label}: Expected to find {file1}");
FileInfo finfo0 = new(file0);
FileInfo finfo1 = new(file1);
if (same)
Assert.True(finfo0.Length == finfo1.Length, $"{label}:{Environment.NewLine} File sizes don't match for {file0} ({finfo0.Length}), and {file1} ({finfo1.Length})");
else
Assert.True(finfo0.Length != finfo1.Length, $"{label}:{Environment.NewLine} File sizes should not match for {file0} ({finfo0.Length}), and {file1} ({finfo1.Length})");
}
protected (int exitCode, string buildOutput) AssertBuild(string args, string label="build", bool expectSuccess=true, IDictionary<string, string>? envVars=null, int? timeoutMs=null)
{
var result = RunProcess(s_buildEnv.DotNet, _testOutput, args, workingDir: _projectDir, label: label, envVars: envVars, timeoutMs: timeoutMs ?? s_defaultPerTestTimeoutMs);
if (expectSuccess)
Assert.True(0 == result.exitCode, $"Build process exited with non-zero exit code: {result.exitCode}");
else
Assert.True(0 != result.exitCode, $"Build should have failed, but it didn't. Process exited with exitCode : {result.exitCode}");
return result;
}
protected void AssertBlazorBundle(string config, bool isPublish, bool dotnetWasmFromRuntimePack, string? binFrameworkDir=null)
{
binFrameworkDir ??= FindBlazorBinFrameworkDir(config, isPublish);
AssertBlazorBootJson(config, isPublish, binFrameworkDir: binFrameworkDir);
AssertFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.wasm"),
Path.Combine(binFrameworkDir, "dotnet.wasm"),
"Expected dotnet.wasm to be same as the runtime pack",
same: dotnetWasmFromRuntimePack);
string? dotnetJsPath = Directory.EnumerateFiles(binFrameworkDir, "dotnet.*.js").FirstOrDefault();
Assert.True(dotnetJsPath != null, $"Could not find blazor's dotnet*js in {binFrameworkDir}");
AssertFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.js"),
dotnetJsPath!,
"Expected dotnet.js to be same as the runtime pack",
same: dotnetWasmFromRuntimePack);
}
protected void AssertBlazorBootJson(string config, bool isPublish, string? binFrameworkDir=null)
{
binFrameworkDir ??= FindBlazorBinFrameworkDir(config, isPublish);
string bootJsonPath = Path.Combine(binFrameworkDir, "blazor.boot.json");
Assert.True(File.Exists(bootJsonPath), $"Expected to find {bootJsonPath}");
string bootJson = File.ReadAllText(bootJsonPath);
var bootJsonNode = JsonNode.Parse(bootJson);
var runtimeObj = bootJsonNode?["resources"]?["runtime"]?.AsObject();
Assert.NotNull(runtimeObj);
string msgPrefix=$"[{( isPublish ? "publish" : "build" )}]";
Assert.True(runtimeObj!.Where(kvp => kvp.Key == "dotnet.wasm").Any(), $"{msgPrefix} Could not find dotnet.wasm entry in blazor.boot.json");
Assert.True(runtimeObj!.Where(kvp => kvp.Key.StartsWith("dotnet.", StringComparison.OrdinalIgnoreCase) &&
kvp.Key.EndsWith(".js", StringComparison.OrdinalIgnoreCase)).Any(),
$"{msgPrefix} Could not find dotnet.*js in {bootJson}");
}
protected string FindBlazorBinFrameworkDir(string config, bool forPublish, string framework = DefaultTargetFramework)
{
string basePath = Path.Combine(_projectDir!, "bin", config, framework);
if (forPublish)
basePath = FindSubDirIgnoringCase(basePath, "publish");
return Path.Combine(basePath, "wwwroot", "_framework");
}
private string FindSubDirIgnoringCase(string parentDir, string dirName)
{
IEnumerable<string> matchingDirs = Directory.EnumerateDirectories(parentDir,
dirName,
new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive });
string? first = matchingDirs.FirstOrDefault();
if (matchingDirs.Count() > 1)
throw new Exception($"Found multiple directories with names that differ only in case. {string.Join(", ", matchingDirs.ToArray())}");
return first ?? Path.Combine(parentDir, dirName);
}
protected string GetBinDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null)
{
var dir = baseDir ?? _projectDir;
Assert.NotNull(dir);
return Path.Combine(dir!, "bin", config, targetFramework, "browser-wasm");
}
protected string GetObjDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null)
{
var dir = baseDir ?? _projectDir;
Assert.NotNull(dir);
return Path.Combine(dir!, "obj", config, targetFramework, "browser-wasm");
}
public static (int exitCode, string buildOutput) RunProcess(string path,
ITestOutputHelper _testOutput,
string args = "",
IDictionary<string, string>? envVars = null,
string? workingDir = null,
string? label = null,
bool logToXUnit = true,
int? timeoutMs = null)
{
_testOutput.WriteLine($"Running {path} {args}");
Console.WriteLine($"Running: {path}: {args}");
Console.WriteLine($"WorkingDirectory: {workingDir}");
_testOutput.WriteLine($"WorkingDirectory: {workingDir}");
StringBuilder outputBuilder = new ();
object syncObj = new();
var processStartInfo = new ProcessStartInfo
{
FileName = path,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
};
if (workingDir == null || !Directory.Exists(workingDir))
throw new Exception($"Working directory {workingDir} not found");
if (workingDir != null)
processStartInfo.WorkingDirectory = workingDir;
if (envVars != null)
{
if (envVars.Count > 0)
_testOutput.WriteLine("Setting environment variables for execution:");
foreach (KeyValuePair<string, string> envVar in envVars)
{
processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
_testOutput.WriteLine($"\t{envVar.Key} = {envVar.Value}");
}
}
Process process = new ();
process.StartInfo = processStartInfo;
process.EnableRaisingEvents = true;
// AutoResetEvent resetEvent = new (false);
// process.Exited += (_, _) => { Console.WriteLine ($"- exited called"); resetEvent.Set(); };
if (!process.Start())
throw new ArgumentException("No process was started: process.Start() return false.");
try
{
DataReceivedEventHandler logStdErr = (sender, e) => LogData($"[{label}-stderr]", e.Data);
DataReceivedEventHandler logStdOut = (sender, e) => LogData($"[{label}]", e.Data);
process.ErrorDataReceived += logStdErr;
process.OutputDataReceived += logStdOut;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// process.WaitForExit doesn't work if the process exits too quickly?
// resetEvent.WaitOne();
if (!process.WaitForExit(timeoutMs ?? s_defaultPerTestTimeoutMs))
{
// process didn't exit
process.Kill(entireProcessTree: true);
lock (syncObj)
{
var lastLines = outputBuilder.ToString().Split('\r', '\n').TakeLast(20);
throw new XunitException($"Process timed out. Last 20 lines of output:{Environment.NewLine}{string.Join(Environment.NewLine, lastLines)}");
}
}
else
{
// this will ensure that all the async event handling
// has completed
// https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.waitforexit?view=net-5.0#System_Diagnostics_Process_WaitForExit_System_Int32_
process.WaitForExit();
}
process.ErrorDataReceived -= logStdErr;
process.OutputDataReceived -= logStdOut;
process.CancelErrorRead();
process.CancelOutputRead();
lock (syncObj)
{
var exitCode = process.ExitCode;
return (process.ExitCode, outputBuilder.ToString().Trim('\r', '\n'));
}
}
catch (Exception ex)
{
Console.WriteLine($"-- exception -- {ex}");
throw;
}
void LogData(string label, string? message)
{
lock (syncObj)
{
if (logToXUnit && message != null)
{
_testOutput.WriteLine($"{label} {message}");
Console.WriteLine($"{label} {message}");
}
outputBuilder.AppendLine($"{label} {message}");
}
}
}
public static string AddItemsPropertiesToProject(string projectFile, string? extraProperties=null, string? extraItems=null, string? atTheEnd=null)
{
if (extraProperties == null && extraItems == null && atTheEnd == null)
return projectFile;
XmlDocument doc = new();
doc.Load(projectFile);
XmlNode root = doc.DocumentElement ?? throw new Exception();
if (extraItems != null)
{
XmlNode node = doc.CreateNode(XmlNodeType.Element, "ItemGroup", null);
node.InnerXml = extraItems;
root.AppendChild(node);
}
if (extraProperties != null)
{
XmlNode node = doc.CreateNode(XmlNodeType.Element, "PropertyGroup", null);
node.InnerXml = extraProperties;
root.AppendChild(node);
}
if (atTheEnd != null)
{
XmlNode node = doc.CreateNode(XmlNodeType.DocumentFragment, "foo", null);
node.InnerXml = atTheEnd;
root.InsertAfter(node, root.LastChild);
}
doc.Save(projectFile);
return projectFile;
}
public void Dispose()
{
if (_projectDir != null && _enablePerTestCleanup)
_buildContext.RemoveFromCache(_projectDir, keepDir: s_skipProjectCleanup);
}
private static string GetEnvironmentVariableOrDefault(string envVarName, string defaultValue)
{
string? value = Environment.GetEnvironmentVariable(envVarName);
return string.IsNullOrEmpty(value) ? defaultValue : value;
}
internal BuildPaths GetBuildPaths(BuildArgs buildArgs, bool forPublish=true)
{
string objDir = GetObjDir(buildArgs.Config);
string bundleDir = Path.Combine(GetBinDir(baseDir: _projectDir, config: buildArgs.Config), "AppBundle");
string wasmDir = Path.Combine(objDir, "wasm", forPublish ? "for-publish" : "for-build");
return new BuildPaths(wasmDir, objDir, GetBinDir(buildArgs.Config), bundleDir);
}
internal IDictionary<string, FileStat> StatFiles(IEnumerable<string> fullpaths)
{
Dictionary<string, FileStat> table = new();
foreach (string file in fullpaths)
{
if (File.Exists(file))
table.Add(Path.GetFileName(file), new FileStat(FullPath: file, Exists: true, LastWriteTimeUtc: File.GetLastWriteTimeUtc(file), Length: new FileInfo(file).Length));
else
table.Add(Path.GetFileName(file), new FileStat(FullPath: file, Exists: false, LastWriteTimeUtc: DateTime.MinValue, Length: 0));
}
return table;
}
protected static string s_mainReturns42 = @"
public class TestClass {
public static int Main()
{
return 42;
}
}";
}
public record BuildArgs(string ProjectName,
string Config,
bool AOT,
string ProjectFileContents,
string? ExtraBuildArgs);
public record BuildProduct(string ProjectDir, string LogFile, bool Result);
internal record FileStat (bool Exists, DateTime LastWriteTimeUtc, long Length, string FullPath);
internal record BuildPaths(string ObjWasmDir, string ObjDir, string BinDir, string BundleDir);
public record BuildProjectOptions
(
Action? InitProject = null,
bool? DotnetWasmFromRuntimePack = null,
bool HasIcudt = true,
bool UseCache = true,
bool ExpectSuccess = true,
bool CreateProject = true,
bool Publish = true,
bool BuildOnlyAfterPublish = true,
bool HasV8Script = true,
string? Verbosity = null,
string? Label = null,
string? TargetFramework = null,
string? MainJS = null
);
public record BlazorBuildOptions
(
string Id,
string Config,
NativeFilesType ExpectedFileType,
string TargetFramework = BuildTestBase.DefaultTargetFramework
);
}
| // 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.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Xml;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
#nullable enable
// [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]
namespace Wasm.Build.Tests
{
public abstract class BuildTestBase : IClassFixture<SharedBuildPerTestClassFixture>, IDisposable
{
public const string DefaultTargetFramework = "net7.0";
public static readonly string NuGetConfigFileNameForDefaultFramework = $"nuget7.config";
protected static readonly bool s_skipProjectCleanup;
protected static readonly string s_xharnessRunnerCommand;
protected string? _projectDir;
protected readonly ITestOutputHelper _testOutput;
protected string _logPath;
protected bool _enablePerTestCleanup = false;
protected SharedBuildPerTestClassFixture _buildContext;
// FIXME: use an envvar to override this
protected static int s_defaultPerTestTimeoutMs = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 30*60*1000 : 15*60*1000;
protected static BuildEnvironment s_buildEnv;
private const string s_runtimePackPathPattern = "\\*\\* MicrosoftNetCoreAppRuntimePackDir : ([^ ]*)";
private static Regex s_runtimePackPathRegex;
public static bool IsUsingWorkloads => s_buildEnv.IsWorkload;
public static bool IsNotUsingWorkloads => !s_buildEnv.IsWorkload;
static BuildTestBase()
{
try
{
s_buildEnv = new BuildEnvironment();
s_runtimePackPathRegex = new Regex(s_runtimePackPathPattern);
s_skipProjectCleanup = !string.IsNullOrEmpty(EnvironmentVariables.SkipProjectCleanup) && EnvironmentVariables.SkipProjectCleanup == "1";
if (string.IsNullOrEmpty(EnvironmentVariables.XHarnessCliPath))
s_xharnessRunnerCommand = "xharness";
else
s_xharnessRunnerCommand = EnvironmentVariables.XHarnessCliPath;
string? nugetPackagesPath = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
if (!string.IsNullOrEmpty(nugetPackagesPath))
{
if (!Directory.Exists(nugetPackagesPath))
Directory.CreateDirectory(nugetPackagesPath);
}
Console.WriteLine ("");
Console.WriteLine ($"==============================================================================================");
Console.WriteLine ($"=============== Running with {(s_buildEnv.IsWorkload ? "Workloads" : "EMSDK")} ===============");
Console.WriteLine ($"==============================================================================================");
Console.WriteLine ("");
}
catch (Exception ex)
{
Console.WriteLine ($"Exception: {ex}");
throw;
}
}
public BuildTestBase(ITestOutputHelper output, SharedBuildPerTestClassFixture buildContext)
{
Console.WriteLine($"{Environment.NewLine}-------- New test --------{Environment.NewLine}");
_buildContext = buildContext;
_testOutput = output;
_logPath = s_buildEnv.LogRootPath; // FIXME:
}
/*
* TODO:
- AOT modes
- llvmonly
- aotinterp
- skipped assemblies should get have their pinvoke/icall stuff scanned
- only buildNative
- aot but no wrapper - check that AppBundle wasn't generated
*/
public static IEnumerable<IEnumerable<object?>> ConfigWithAOTData(bool aot, string? config=null)
{
if (config == null)
{
return new IEnumerable<object?>[]
{
#if TEST_DEBUG_CONFIG_ALSO
// list of each member data - for Debug+@aot
new object?[] { new BuildArgs("placeholder", "Debug", aot, "placeholder", string.Empty) }.AsEnumerable(),
#endif
// list of each member data - for Release+@aot
new object?[] { new BuildArgs("placeholder", "Release", aot, "placeholder", string.Empty) }.AsEnumerable()
}.AsEnumerable();
}
else
{
return new IEnumerable<object?>[]
{
new object?[] { new BuildArgs("placeholder", config, aot, "placeholder", string.Empty) }.AsEnumerable()
};
}
}
protected string RunAndTestWasmApp(BuildArgs buildArgs,
RunHost host,
string id,
Action<string>? test=null,
string? buildDir = null,
int expectedExitCode = 0,
string? args = null,
Dictionary<string, string>? envVars = null,
string targetFramework = DefaultTargetFramework)
{
buildDir ??= _projectDir;
envVars ??= new();
envVars["XHARNESS_DISABLE_COLORED_OUTPUT"] = "true";
if (buildArgs.AOT)
{
envVars["MONO_LOG_LEVEL"] = "debug";
envVars["MONO_LOG_MASK"] = "aot";
}
if (s_buildEnv.EnvVars != null)
{
foreach (var kvp in s_buildEnv.EnvVars)
envVars[kvp.Key] = kvp.Value;
}
string bundleDir = Path.Combine(GetBinDir(baseDir: buildDir, config: buildArgs.Config, targetFramework: targetFramework), "AppBundle");
(string testCommand, string extraXHarnessArgs) = host switch
{
RunHost.V8 => ("wasm test", "--js-file=test-main.js --engine=V8 -v trace"),
RunHost.NodeJS => ("wasm test", "--js-file=test-main.js --engine=NodeJS -v trace"),
_ => ("wasm test-browser", $"-v trace -b {host}")
};
string testLogPath = Path.Combine(_logPath, host.ToString());
string output = RunWithXHarness(
testCommand,
testLogPath,
buildArgs.ProjectName,
bundleDir,
_testOutput,
envVars: envVars,
expectedAppExitCode: expectedExitCode,
extraXHarnessArgs: extraXHarnessArgs,
appArgs: args);
if (buildArgs.AOT)
{
Assert.Contains("AOT: image 'System.Private.CoreLib' found.", output);
Assert.Contains($"AOT: image '{buildArgs.ProjectName}' found.", output);
}
else
{
Assert.DoesNotContain("AOT: image 'System.Private.CoreLib' found.", output);
Assert.DoesNotContain($"AOT: image '{buildArgs.ProjectName}' found.", output);
}
if (test != null)
test(output);
return output;
}
protected static string RunWithXHarness(string testCommand, string testLogPath, string projectName, string bundleDir,
ITestOutputHelper _testOutput, IDictionary<string, string>? envVars=null,
int expectedAppExitCode=0, int xharnessExitCode=0, string? extraXHarnessArgs=null, string? appArgs=null)
{
Console.WriteLine($"============== {testCommand} =============");
Directory.CreateDirectory(testLogPath);
StringBuilder args = new();
args.Append(s_xharnessRunnerCommand);
args.Append($" {testCommand}");
args.Append($" --app=.");
args.Append($" --output-directory={testLogPath}");
args.Append($" --expected-exit-code={expectedAppExitCode}");
args.Append($" {extraXHarnessArgs ?? string.Empty}");
args.Append(" -- ");
// App arguments
if (envVars != null)
{
var setenv = string.Join(' ', envVars.Select(kvp => $"\"--setenv={kvp.Key}={kvp.Value}\"").ToArray());
args.Append($" {setenv}");
}
args.Append($" --run {projectName}.dll");
args.Append($" {appArgs ?? string.Empty}");
_testOutput.WriteLine(string.Empty);
_testOutput.WriteLine($"---------- Running with {testCommand} ---------");
var (exitCode, output) = RunProcess(s_buildEnv.DotNet, _testOutput,
args: args.ToString(),
workingDir: bundleDir,
envVars: envVars,
label: testCommand,
timeoutMs: s_defaultPerTestTimeoutMs);
File.WriteAllText(Path.Combine(testLogPath, $"xharness.log"), output);
if (exitCode != xharnessExitCode)
{
_testOutput.WriteLine($"Exit code: {exitCode}");
if (exitCode != expectedAppExitCode)
throw new XunitException($"[{testCommand}] Exit code, expected {expectedAppExitCode} but got {exitCode} for command: {testCommand} {args}");
}
return output;
}
[MemberNotNull(nameof(_projectDir), nameof(_logPath))]
protected void InitPaths(string id)
{
if (_projectDir == null)
_projectDir = Path.Combine(AppContext.BaseDirectory, id);
_logPath = Path.Combine(s_buildEnv.LogRootPath, id);
Directory.CreateDirectory(_logPath);
}
protected static void InitProjectDir(string dir)
{
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, "Directory.Build.props"), s_buildEnv.DirectoryBuildPropsContents);
File.WriteAllText(Path.Combine(dir, "Directory.Build.targets"), s_buildEnv.DirectoryBuildTargetsContents);
File.Copy(Path.Combine(BuildEnvironment.TestDataPath, NuGetConfigFileNameForDefaultFramework), Path.Combine(dir, "nuget.config"));
Directory.CreateDirectory(Path.Combine(dir, ".nuget"));
}
protected const string SimpleProjectTemplate =
@$"<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>{DefaultTargetFramework}</TargetFramework>
<OutputType>Exe</OutputType>
<WasmGenerateRunV8Script>true</WasmGenerateRunV8Script>
<WasmMainJSPath>test-main.js</WasmMainJSPath>
##EXTRA_PROPERTIES##
</PropertyGroup>
<ItemGroup>
##EXTRA_ITEMS##
</ItemGroup>
##INSERT_AT_END##
</Project>";
protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties="", string extraItems="", string insertAtEnd="", string projectTemplate=SimpleProjectTemplate)
{
if (buildArgs.AOT)
{
extraProperties = $"{extraProperties}\n<RunAOTCompilation>true</RunAOTCompilation>";
extraProperties += $"\n<EmccVerbose>{RuntimeInformation.IsOSPlatform(OSPlatform.Windows)}</EmccVerbose>\n";
}
string projectContents = projectTemplate
.Replace("##EXTRA_PROPERTIES##", extraProperties)
.Replace("##EXTRA_ITEMS##", extraItems)
.Replace("##INSERT_AT_END##", insertAtEnd);
return buildArgs with { ProjectFileContents = projectContents };
}
public (string projectDir, string buildOutput) BuildProject(BuildArgs buildArgs,
string id,
BuildProjectOptions options)
{
string msgPrefix = options.Label != null ? $"[{options.Label}] " : string.Empty;
if (options.UseCache && _buildContext.TryGetBuildFor(buildArgs, out BuildProduct? product))
{
Console.WriteLine ($"Using existing build found at {product.ProjectDir}, with build log at {product.LogFile}");
Assert.True(product.Result, $"Found existing build at {product.ProjectDir}, but it had failed. Check build log at {product.LogFile}");
_projectDir = product.ProjectDir;
// use this test's id for the run logs
_logPath = Path.Combine(s_buildEnv.LogRootPath, id);
return (_projectDir, "FIXME");
}
if (options.CreateProject)
{
InitPaths(id);
InitProjectDir(_projectDir);
options.InitProject?.Invoke();
File.WriteAllText(Path.Combine(_projectDir, $"{buildArgs.ProjectName}.csproj"), buildArgs.ProjectFileContents);
File.Copy(Path.Combine(AppContext.BaseDirectory, "test-main.js"), Path.Combine(_projectDir, "test-main.js"));
}
else if (_projectDir is null)
{
throw new Exception("_projectDir should be set, to use options.createProject=false");
}
StringBuilder sb = new();
sb.Append(options.Publish ? "publish" : "build");
if (options.Publish && options.BuildOnlyAfterPublish)
sb.Append(" -p:WasmBuildOnlyAfterPublish=true");
sb.Append($" {s_buildEnv.DefaultBuildArgs}");
sb.Append($" /p:Configuration={buildArgs.Config}");
string logFileSuffix = options.Label == null ? string.Empty : options.Label.Replace(' ', '_');
string logFilePath = Path.Combine(_logPath, $"{buildArgs.ProjectName}{logFileSuffix}.binlog");
_testOutput.WriteLine($"-------- Building ---------");
_testOutput.WriteLine($"Binlog path: {logFilePath}");
Console.WriteLine($"Binlog path: {logFilePath}");
sb.Append($" /bl:\"{logFilePath}\" /nologo");
sb.Append($" /fl /flp:\"v:diag,LogFile={logFilePath}.log\" /v:{options.Verbosity ?? "minimal"}");
if (buildArgs.ExtraBuildArgs != null)
sb.Append($" {buildArgs.ExtraBuildArgs} ");
Console.WriteLine($"Building {buildArgs.ProjectName} in {_projectDir}");
(int exitCode, string buildOutput) result;
try
{
result = AssertBuild(sb.ToString(), id, expectSuccess: options.ExpectSuccess, envVars: s_buildEnv.EnvVars);
//AssertRuntimePackPath(result.buildOutput);
// check that we are using the correct runtime pack!
if (options.ExpectSuccess)
{
string bundleDir = Path.Combine(GetBinDir(config: buildArgs.Config, targetFramework: options.TargetFramework ?? DefaultTargetFramework), "AppBundle");
AssertBasicAppBundle(bundleDir, buildArgs.ProjectName, buildArgs.Config, options.MainJS ?? "test-main.js", options.HasV8Script, options.HasIcudt, options.DotnetWasmFromRuntimePack ?? !buildArgs.AOT);
}
if (options.UseCache)
_buildContext.CacheBuild(buildArgs, new BuildProduct(_projectDir, logFilePath, true));
return (_projectDir, result.buildOutput);
}
catch
{
if (options.UseCache)
_buildContext.CacheBuild(buildArgs, new BuildProduct(_projectDir, logFilePath, false));
throw;
}
}
public void InitBlazorWasmProjectDir(string id)
{
InitPaths(id);
if (Directory.Exists(_projectDir))
Directory.Delete(_projectDir, recursive: true);
Directory.CreateDirectory(_projectDir);
Directory.CreateDirectory(Path.Combine(_projectDir, ".nuget"));
File.Copy(Path.Combine(BuildEnvironment.TestDataPath, NuGetConfigFileNameForDefaultFramework), Path.Combine(_projectDir, "nuget.config"));
File.Copy(Path.Combine(BuildEnvironment.TestDataPath, "Blazor.Directory.Build.props"), Path.Combine(_projectDir, "Directory.Build.props"));
File.Copy(Path.Combine(BuildEnvironment.TestDataPath, "Blazor.Directory.Build.targets"), Path.Combine(_projectDir, "Directory.Build.targets"));
}
public string CreateWasmTemplateProject(string id, string template = "wasmbrowser")
{
InitPaths(id);
InitProjectDir(id);
new DotNetCommand(s_buildEnv, useDefaultArgs: false)
.WithWorkingDirectory(_projectDir!)
.ExecuteWithCapturedOutput($"new {template}")
.EnsureSuccessful();
return Path.Combine(_projectDir!, $"{id}.csproj");
}
public string CreateBlazorWasmTemplateProject(string id)
{
InitBlazorWasmProjectDir(id);
new DotNetCommand(s_buildEnv, useDefaultArgs: false)
.WithWorkingDirectory(_projectDir!)
.ExecuteWithCapturedOutput("new blazorwasm")
.EnsureSuccessful();
return Path.Combine(_projectDir!, $"{id}.csproj");
}
protected (CommandResult, string) BlazorBuild(BlazorBuildOptions options, params string[] extraArgs)
{
var res = BuildInternal(options.Id, options.Config, publish: false, extraArgs);
AssertDotNetNativeFiles(options.ExpectedFileType, options.Config, forPublish: false, targetFramework: options.TargetFramework);
AssertBlazorBundle(options.Config, isPublish: false, dotnetWasmFromRuntimePack: options.ExpectedFileType == NativeFilesType.FromRuntimePack);
return res;
}
protected (CommandResult, string) BlazorPublish(BlazorBuildOptions options, params string[] extraArgs)
{
var res = BuildInternal(options.Id, options.Config, publish: true, extraArgs);
AssertDotNetNativeFiles(options.ExpectedFileType, options.Config, forPublish: true, targetFramework: options.TargetFramework);
AssertBlazorBundle(options.Config, isPublish: true, dotnetWasmFromRuntimePack: options.ExpectedFileType == NativeFilesType.FromRuntimePack);
if (options.ExpectedFileType == NativeFilesType.AOT)
{
// check for this too, so we know the format is correct for the negative
// test for jsinterop.webassembly.dll
Assert.Contains("Microsoft.JSInterop.dll -> Microsoft.JSInterop.dll.bc", res.Item1.Output);
// make sure this assembly gets skipped
Assert.DoesNotContain("Microsoft.JSInterop.WebAssembly.dll -> Microsoft.JSInterop.WebAssembly.dll.bc", res.Item1.Output);
}
return res;
}
protected (CommandResult, string) BuildInternal(string id, string config, bool publish=false, params string[] extraArgs)
{
string label = publish ? "publish" : "build";
Console.WriteLine($"{Environment.NewLine}** {label} **{Environment.NewLine}");
string logPath = Path.Combine(s_buildEnv.LogRootPath, id, $"{id}-{label}.binlog");
string[] combinedArgs = new[]
{
label, // same as the command name
$"-bl:{logPath}",
$"-p:Configuration={config}",
"-p:BlazorEnableCompression=false",
"-p:_WasmDevel=true"
}.Concat(extraArgs).ToArray();
CommandResult res = new DotNetCommand(s_buildEnv)
.WithWorkingDirectory(_projectDir!)
.ExecuteWithCapturedOutput(combinedArgs)
.EnsureSuccessful();
return (res, logPath);
}
protected void AssertDotNetNativeFiles(NativeFilesType type, string config, bool forPublish, string targetFramework = DefaultTargetFramework)
{
string label = forPublish ? "publish" : "build";
string objBuildDir = Path.Combine(_projectDir!, "obj", config, targetFramework, "wasm", forPublish ? "for-publish" : "for-build");
string binFrameworkDir = FindBlazorBinFrameworkDir(config, forPublish);
string srcDir = type switch
{
NativeFilesType.FromRuntimePack => s_buildEnv.RuntimeNativeDir,
NativeFilesType.Relinked => objBuildDir,
NativeFilesType.AOT => objBuildDir,
_ => throw new ArgumentOutOfRangeException(nameof(type))
};
AssertSameFile(Path.Combine(srcDir, "dotnet.wasm"), Path.Combine(binFrameworkDir, "dotnet.wasm"), label);
// find dotnet*js
string? dotnetJsPath = Directory.EnumerateFiles(binFrameworkDir)
.Where(p => Path.GetFileName(p).StartsWith("dotnet.", StringComparison.OrdinalIgnoreCase) &&
Path.GetFileName(p).EndsWith(".js", StringComparison.OrdinalIgnoreCase))
.SingleOrDefault();
Assert.True(!string.IsNullOrEmpty(dotnetJsPath), $"[{label}] Expected to find dotnet*js in {binFrameworkDir}");
AssertSameFile(Path.Combine(srcDir, "dotnet.js"), dotnetJsPath!, label);
if (type != NativeFilesType.FromRuntimePack)
{
// check that the files are *not* from runtime pack
AssertNotSameFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.wasm"), Path.Combine(binFrameworkDir, "dotnet.wasm"), label);
AssertNotSameFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.js"), dotnetJsPath!, label);
}
}
static void AssertRuntimePackPath(string buildOutput)
{
var match = s_runtimePackPathRegex.Match(buildOutput);
if (!match.Success || match.Groups.Count != 2)
throw new XunitException($"Could not find the pattern in the build output: '{s_runtimePackPathPattern}'.{Environment.NewLine}Build output: {buildOutput}");
string actualPath = match.Groups[1].Value;
if (string.Compare(actualPath, s_buildEnv.RuntimePackDir) != 0)
throw new XunitException($"Runtime pack path doesn't match.{Environment.NewLine}Expected: {s_buildEnv.RuntimePackDir}{Environment.NewLine}Actual: {actualPath}");
}
protected static void AssertBasicAppBundle(string bundleDir, string projectName, string config, string mainJS, bool hasV8Script, bool hasIcudt=true, bool dotnetWasmFromRuntimePack=true)
{
AssertFilesExist(bundleDir, new []
{
"index.html",
mainJS,
"dotnet.timezones.blat",
"dotnet.wasm",
"mono-config.json",
"dotnet.js"
});
AssertFilesExist(bundleDir, new[] { "run-v8.sh" }, expectToExist: hasV8Script);
AssertFilesExist(bundleDir, new[] { "icudt.dat" }, expectToExist: hasIcudt);
string managedDir = Path.Combine(bundleDir, "managed");
AssertFilesExist(managedDir, new[] { $"{projectName}.dll" });
bool is_debug = config == "Debug";
if (is_debug)
{
// Use cecil to check embedded pdb?
// AssertFilesExist(managedDir, new[] { $"{projectName}.pdb" });
//FIXME: um.. what about these? embedded? why is linker omitting them?
//foreach (string file in Directory.EnumerateFiles(managedDir, "*.dll"))
//{
//string pdb = Path.ChangeExtension(file, ".pdb");
//Assert.True(File.Exists(pdb), $"Could not find {pdb} for {file}");
//}
}
AssertDotNetWasmJs(bundleDir, fromRuntimePack: dotnetWasmFromRuntimePack);
}
protected static void AssertDotNetWasmJs(string bundleDir, bool fromRuntimePack)
{
AssertFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.wasm"),
Path.Combine(bundleDir, "dotnet.wasm"),
"Expected dotnet.wasm to be same as the runtime pack",
same: fromRuntimePack);
AssertFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.js"),
Path.Combine(bundleDir, "dotnet.js"),
"Expected dotnet.js to be same as the runtime pack",
same: fromRuntimePack);
}
protected static void AssertFilesDontExist(string dir, string[] filenames, string? label = null)
=> AssertFilesExist(dir, filenames, label, expectToExist: false);
protected static void AssertFilesExist(string dir, string[] filenames, string? label = null, bool expectToExist=true)
{
Assert.True(Directory.Exists(dir), $"[{label}] {dir} not found");
foreach (string filename in filenames)
{
string path = Path.Combine(dir, filename);
if (expectToExist)
{
Assert.True(File.Exists(path),
label != null
? $"{label}: File exists: {path}"
: $"File exists: {path}");
}
else
{
Assert.False(File.Exists(path),
label != null
? $"{label}: {path} should not exist"
: $"{path} should not exist");
}
}
}
protected static void AssertSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: true);
protected static void AssertNotSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: false);
protected static void AssertFile(string file0, string file1, string? label=null, bool same=true)
{
Assert.True(File.Exists(file0), $"{label}: Expected to find {file0}");
Assert.True(File.Exists(file1), $"{label}: Expected to find {file1}");
FileInfo finfo0 = new(file0);
FileInfo finfo1 = new(file1);
if (same)
Assert.True(finfo0.Length == finfo1.Length, $"{label}:{Environment.NewLine} File sizes don't match for {file0} ({finfo0.Length}), and {file1} ({finfo1.Length})");
else
Assert.True(finfo0.Length != finfo1.Length, $"{label}:{Environment.NewLine} File sizes should not match for {file0} ({finfo0.Length}), and {file1} ({finfo1.Length})");
}
protected (int exitCode, string buildOutput) AssertBuild(string args, string label="build", bool expectSuccess=true, IDictionary<string, string>? envVars=null, int? timeoutMs=null)
{
var result = RunProcess(s_buildEnv.DotNet, _testOutput, args, workingDir: _projectDir, label: label, envVars: envVars, timeoutMs: timeoutMs ?? s_defaultPerTestTimeoutMs);
if (expectSuccess)
Assert.True(0 == result.exitCode, $"Build process exited with non-zero exit code: {result.exitCode}");
else
Assert.True(0 != result.exitCode, $"Build should have failed, but it didn't. Process exited with exitCode : {result.exitCode}");
return result;
}
protected void AssertBlazorBundle(string config, bool isPublish, bool dotnetWasmFromRuntimePack, string? binFrameworkDir=null)
{
binFrameworkDir ??= FindBlazorBinFrameworkDir(config, isPublish);
AssertBlazorBootJson(config, isPublish, binFrameworkDir: binFrameworkDir);
AssertFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.wasm"),
Path.Combine(binFrameworkDir, "dotnet.wasm"),
"Expected dotnet.wasm to be same as the runtime pack",
same: dotnetWasmFromRuntimePack);
string? dotnetJsPath = Directory.EnumerateFiles(binFrameworkDir, "dotnet.*.js").FirstOrDefault();
Assert.True(dotnetJsPath != null, $"Could not find blazor's dotnet*js in {binFrameworkDir}");
AssertFile(Path.Combine(s_buildEnv.RuntimeNativeDir, "dotnet.js"),
dotnetJsPath!,
"Expected dotnet.js to be same as the runtime pack",
same: dotnetWasmFromRuntimePack);
}
protected void AssertBlazorBootJson(string config, bool isPublish, string? binFrameworkDir=null)
{
binFrameworkDir ??= FindBlazorBinFrameworkDir(config, isPublish);
string bootJsonPath = Path.Combine(binFrameworkDir, "blazor.boot.json");
Assert.True(File.Exists(bootJsonPath), $"Expected to find {bootJsonPath}");
string bootJson = File.ReadAllText(bootJsonPath);
var bootJsonNode = JsonNode.Parse(bootJson);
var runtimeObj = bootJsonNode?["resources"]?["runtime"]?.AsObject();
Assert.NotNull(runtimeObj);
string msgPrefix=$"[{( isPublish ? "publish" : "build" )}]";
Assert.True(runtimeObj!.Where(kvp => kvp.Key == "dotnet.wasm").Any(), $"{msgPrefix} Could not find dotnet.wasm entry in blazor.boot.json");
Assert.True(runtimeObj!.Where(kvp => kvp.Key.StartsWith("dotnet.", StringComparison.OrdinalIgnoreCase) &&
kvp.Key.EndsWith(".js", StringComparison.OrdinalIgnoreCase)).Any(),
$"{msgPrefix} Could not find dotnet.*js in {bootJson}");
}
protected string FindBlazorBinFrameworkDir(string config, bool forPublish, string framework = DefaultTargetFramework)
{
string basePath = Path.Combine(_projectDir!, "bin", config, framework);
if (forPublish)
basePath = FindSubDirIgnoringCase(basePath, "publish");
return Path.Combine(basePath, "wwwroot", "_framework");
}
private string FindSubDirIgnoringCase(string parentDir, string dirName)
{
IEnumerable<string> matchingDirs = Directory.EnumerateDirectories(parentDir,
dirName,
new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive });
string? first = matchingDirs.FirstOrDefault();
if (matchingDirs.Count() > 1)
throw new Exception($"Found multiple directories with names that differ only in case. {string.Join(", ", matchingDirs.ToArray())}");
return first ?? Path.Combine(parentDir, dirName);
}
protected string GetBinDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null)
{
var dir = baseDir ?? _projectDir;
Assert.NotNull(dir);
return Path.Combine(dir!, "bin", config, targetFramework, "browser-wasm");
}
protected string GetObjDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null)
{
var dir = baseDir ?? _projectDir;
Assert.NotNull(dir);
return Path.Combine(dir!, "obj", config, targetFramework, "browser-wasm");
}
public static (int exitCode, string buildOutput) RunProcess(string path,
ITestOutputHelper _testOutput,
string args = "",
IDictionary<string, string>? envVars = null,
string? workingDir = null,
string? label = null,
bool logToXUnit = true,
int? timeoutMs = null)
{
_testOutput.WriteLine($"Running {path} {args}");
Console.WriteLine($"Running: {path}: {args}");
Console.WriteLine($"WorkingDirectory: {workingDir}");
_testOutput.WriteLine($"WorkingDirectory: {workingDir}");
StringBuilder outputBuilder = new ();
object syncObj = new();
var processStartInfo = new ProcessStartInfo
{
FileName = path,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
};
if (workingDir == null || !Directory.Exists(workingDir))
throw new Exception($"Working directory {workingDir} not found");
if (workingDir != null)
processStartInfo.WorkingDirectory = workingDir;
if (envVars != null)
{
if (envVars.Count > 0)
_testOutput.WriteLine("Setting environment variables for execution:");
foreach (KeyValuePair<string, string> envVar in envVars)
{
processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
_testOutput.WriteLine($"\t{envVar.Key} = {envVar.Value}");
}
}
Process process = new ();
process.StartInfo = processStartInfo;
process.EnableRaisingEvents = true;
// AutoResetEvent resetEvent = new (false);
// process.Exited += (_, _) => { Console.WriteLine ($"- exited called"); resetEvent.Set(); };
if (!process.Start())
throw new ArgumentException("No process was started: process.Start() return false.");
try
{
DataReceivedEventHandler logStdErr = (sender, e) => LogData($"[{label}-stderr]", e.Data);
DataReceivedEventHandler logStdOut = (sender, e) => LogData($"[{label}]", e.Data);
process.ErrorDataReceived += logStdErr;
process.OutputDataReceived += logStdOut;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// process.WaitForExit doesn't work if the process exits too quickly?
// resetEvent.WaitOne();
if (!process.WaitForExit(timeoutMs ?? s_defaultPerTestTimeoutMs))
{
// process didn't exit
process.Kill(entireProcessTree: true);
lock (syncObj)
{
var lastLines = outputBuilder.ToString().Split('\r', '\n').TakeLast(20);
throw new XunitException($"Process timed out. Last 20 lines of output:{Environment.NewLine}{string.Join(Environment.NewLine, lastLines)}");
}
}
else
{
// this will ensure that all the async event handling
// has completed
// https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.waitforexit?view=net-5.0#System_Diagnostics_Process_WaitForExit_System_Int32_
process.WaitForExit();
}
process.ErrorDataReceived -= logStdErr;
process.OutputDataReceived -= logStdOut;
process.CancelErrorRead();
process.CancelOutputRead();
lock (syncObj)
{
var exitCode = process.ExitCode;
return (process.ExitCode, outputBuilder.ToString().Trim('\r', '\n'));
}
}
catch (Exception ex)
{
Console.WriteLine($"-- exception -- {ex}");
throw;
}
void LogData(string label, string? message)
{
lock (syncObj)
{
if (logToXUnit && message != null)
{
_testOutput.WriteLine($"{label} {message}");
Console.WriteLine($"{label} {message}");
}
outputBuilder.AppendLine($"{label} {message}");
}
}
}
public static string AddItemsPropertiesToProject(string projectFile, string? extraProperties=null, string? extraItems=null, string? atTheEnd=null)
{
if (extraProperties == null && extraItems == null && atTheEnd == null)
return projectFile;
XmlDocument doc = new();
doc.Load(projectFile);
XmlNode root = doc.DocumentElement ?? throw new Exception();
if (extraItems != null)
{
XmlNode node = doc.CreateNode(XmlNodeType.Element, "ItemGroup", null);
node.InnerXml = extraItems;
root.AppendChild(node);
}
if (extraProperties != null)
{
XmlNode node = doc.CreateNode(XmlNodeType.Element, "PropertyGroup", null);
node.InnerXml = extraProperties;
root.AppendChild(node);
}
if (atTheEnd != null)
{
XmlNode node = doc.CreateNode(XmlNodeType.DocumentFragment, "foo", null);
node.InnerXml = atTheEnd;
root.InsertAfter(node, root.LastChild);
}
doc.Save(projectFile);
return projectFile;
}
public void Dispose()
{
if (_projectDir != null && _enablePerTestCleanup)
_buildContext.RemoveFromCache(_projectDir, keepDir: s_skipProjectCleanup);
}
private static string GetEnvironmentVariableOrDefault(string envVarName, string defaultValue)
{
string? value = Environment.GetEnvironmentVariable(envVarName);
return string.IsNullOrEmpty(value) ? defaultValue : value;
}
internal BuildPaths GetBuildPaths(BuildArgs buildArgs, bool forPublish=true)
{
string objDir = GetObjDir(buildArgs.Config);
string bundleDir = Path.Combine(GetBinDir(baseDir: _projectDir, config: buildArgs.Config), "AppBundle");
string wasmDir = Path.Combine(objDir, "wasm", forPublish ? "for-publish" : "for-build");
return new BuildPaths(wasmDir, objDir, GetBinDir(buildArgs.Config), bundleDir);
}
internal IDictionary<string, FileStat> StatFiles(IEnumerable<string> fullpaths)
{
Dictionary<string, FileStat> table = new();
foreach (string file in fullpaths)
{
if (File.Exists(file))
table.Add(Path.GetFileName(file), new FileStat(FullPath: file, Exists: true, LastWriteTimeUtc: File.GetLastWriteTimeUtc(file), Length: new FileInfo(file).Length));
else
table.Add(Path.GetFileName(file), new FileStat(FullPath: file, Exists: false, LastWriteTimeUtc: DateTime.MinValue, Length: 0));
}
return table;
}
protected static string s_mainReturns42 = @"
public class TestClass {
public static int Main()
{
return 42;
}
}";
}
public record BuildArgs(string ProjectName,
string Config,
bool AOT,
string ProjectFileContents,
string? ExtraBuildArgs);
public record BuildProduct(string ProjectDir, string LogFile, bool Result);
internal record FileStat (bool Exists, DateTime LastWriteTimeUtc, long Length, string FullPath);
internal record BuildPaths(string ObjWasmDir, string ObjDir, string BinDir, string BundleDir);
public record BuildProjectOptions
(
Action? InitProject = null,
bool? DotnetWasmFromRuntimePack = null,
bool HasIcudt = true,
bool UseCache = true,
bool ExpectSuccess = true,
bool CreateProject = true,
bool Publish = true,
bool BuildOnlyAfterPublish = true,
bool HasV8Script = true,
string? Verbosity = null,
string? Label = null,
string? TargetFramework = null,
string? MainJS = null
);
public record BlazorBuildOptions
(
string Id,
string Config,
NativeFilesType ExpectedFileType,
string TargetFramework = BuildTestBase.DefaultTargetFramework
);
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.ComponentModel.EventBasedAsync/tests/AsyncOperationTests.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.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.ComponentModel.EventBasedAsync.Tests
{
public class AsyncOperationTests
{
private const int SpinTimeoutSeconds = 30;
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Noop()
{
// Test that a simple AsyncOperation can be dispatched and completed via AsyncOperationManager
Task.Run(() =>
{
var operation = new TestAsyncOperation(op => { });
operation.Wait();
Assert.True(operation.Completed);
Assert.False(operation.Cancelled);
Assert.Null(operation.Exception);
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ThrowAfterAsyncComplete()
{
Task.Run(() =>
{
var operation = new TestAsyncOperation(op => { });
operation.Wait();
SendOrPostCallback noopCallback = state => { };
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.Post(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.PostOperationCompleted(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.OperationCompleted());
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ThrowAfterSynchronousComplete()
{
Task.Run(() =>
{
var operation = AsyncOperationManager.CreateOperation(null);
operation.OperationCompleted();
SendOrPostCallback noopCallback = state => { };
Assert.Throws<InvalidOperationException>(() => operation.Post(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.PostOperationCompleted(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.OperationCompleted());
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Cancel()
{
// Test that cancellation gets passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs)
Task.Run(() =>
{
var cancelEvent = new ManualResetEventSlim();
var operation = new TestAsyncOperation(op =>
{
Assert.True(cancelEvent.Wait(TimeSpan.FromSeconds(SpinTimeoutSeconds)));
}, cancelEvent: cancelEvent);
operation.Cancel();
operation.Wait();
Assert.True(operation.Completed);
Assert.True(operation.Cancelled);
Assert.Null(operation.Exception);
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Throw()
{
// Test that exceptions get passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs)
Task.Run(() =>
{
var operation = new TestAsyncOperation(op =>
{
throw new TestException("Test throw");
});
Assert.Throws<TestException>(() => operation.Wait());
}).GetAwaiter().GetResult();
}
[Fact]
public static void PostNullDelegate()
{
// the xUnit SynchronizationContext - AysncTestSyncContext interferes with the current SynchronizationContext
// used by AsyncOperation when there is exception thrown -> the SC.OperationCompleted() is not called.
// use new SC here to avoid this issue
var orignal = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
// Pass a non-null state just to emphasize we're only testing passing a null delegate
var state = new object();
var operation = AsyncOperationManager.CreateOperation(state);
Assert.Throws<ArgumentNullException>(() => operation.Post(null, state));
Assert.Throws<ArgumentNullException>(() => operation.PostOperationCompleted(null, state));
}
finally
{
SynchronizationContext.SetSynchronizationContext(orignal);
}
}
// A simple wrapper for AsyncOperation which executes the specified delegate and a completion handler asynchronously.
public class TestAsyncOperation
{
private readonly object _operationId;
private readonly Action<TestAsyncOperation> _executeDelegate;
private readonly ManualResetEventSlim _cancelEvent;
private readonly ManualResetEventSlim _completeEvent;
public AsyncOperation AsyncOperation { get; private set; }
public bool Completed { get { return _completeEvent.IsSet; } }
public bool Cancelled { get { return _cancelEvent.IsSet; } }
public Exception Exception { get; private set; }
public TestAsyncOperation(Action<TestAsyncOperation> executeDelegate, ManualResetEventSlim cancelEvent = null)
{
// Create an async operation passing an object as the state so we can
// verify that state is passed properly.
_operationId = new object();
AsyncOperation = AsyncOperationManager.CreateOperation(_operationId);
Assert.Same(_operationId, AsyncOperation.UserSuppliedState);
Assert.Same(AsyncOperationManager.SynchronizationContext, AsyncOperation.SynchronizationContext);
_completeEvent = new ManualResetEventSlim(false);
_cancelEvent = cancelEvent ?? new ManualResetEventSlim(false);
// Post work to the wrapped synchronization context
_executeDelegate = executeDelegate;
AsyncOperation.Post((SendOrPostCallback)ExecuteWorker, _operationId);
}
public void Wait()
{
Assert.True(_completeEvent.Wait(TimeSpan.FromSeconds(SpinTimeoutSeconds)));
if (Exception != null)
{
throw Exception;
}
}
public void Cancel()
{
CompleteOperationAsync(cancelled: true);
}
private void ExecuteWorker(object operationId)
{
Assert.Same(_operationId, operationId);
Exception exception = null;
try
{
_executeDelegate(this);
}
catch (Exception e)
{
exception = e;
}
finally
{
CompleteOperationAsync(exception: exception);
}
}
private void CompleteOperationAsync(Exception exception = null, bool cancelled = false)
{
if (!(Completed || Cancelled))
{
AsyncOperation.PostOperationCompleted(
(SendOrPostCallback)OnOperationCompleted,
new AsyncCompletedEventArgs(
exception,
cancelled,
_operationId));
}
}
private void OnOperationCompleted(object state)
{
AsyncCompletedEventArgs e = Assert.IsType<AsyncCompletedEventArgs>(state);
Assert.Equal(_operationId, e.UserState);
Exception = e.Error;
// Make sure to set _cancelEvent before _completeEvent so that anyone waiting on
// _completeEvent will not be at risk of reading Cancelled before it is set.
if (e.Cancelled)
_cancelEvent.Set();
_completeEvent.Set();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.ComponentModel.EventBasedAsync.Tests
{
public class AsyncOperationTests
{
private const int SpinTimeoutSeconds = 30;
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Noop()
{
// Test that a simple AsyncOperation can be dispatched and completed via AsyncOperationManager
Task.Run(() =>
{
var operation = new TestAsyncOperation(op => { });
operation.Wait();
Assert.True(operation.Completed);
Assert.False(operation.Cancelled);
Assert.Null(operation.Exception);
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ThrowAfterAsyncComplete()
{
Task.Run(() =>
{
var operation = new TestAsyncOperation(op => { });
operation.Wait();
SendOrPostCallback noopCallback = state => { };
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.Post(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.PostOperationCompleted(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.OperationCompleted());
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ThrowAfterSynchronousComplete()
{
Task.Run(() =>
{
var operation = AsyncOperationManager.CreateOperation(null);
operation.OperationCompleted();
SendOrPostCallback noopCallback = state => { };
Assert.Throws<InvalidOperationException>(() => operation.Post(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.PostOperationCompleted(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.OperationCompleted());
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Cancel()
{
// Test that cancellation gets passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs)
Task.Run(() =>
{
var cancelEvent = new ManualResetEventSlim();
var operation = new TestAsyncOperation(op =>
{
Assert.True(cancelEvent.Wait(TimeSpan.FromSeconds(SpinTimeoutSeconds)));
}, cancelEvent: cancelEvent);
operation.Cancel();
operation.Wait();
Assert.True(operation.Completed);
Assert.True(operation.Cancelled);
Assert.Null(operation.Exception);
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Throw()
{
// Test that exceptions get passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs)
Task.Run(() =>
{
var operation = new TestAsyncOperation(op =>
{
throw new TestException("Test throw");
});
Assert.Throws<TestException>(() => operation.Wait());
}).GetAwaiter().GetResult();
}
[Fact]
public static void PostNullDelegate()
{
// the xUnit SynchronizationContext - AysncTestSyncContext interferes with the current SynchronizationContext
// used by AsyncOperation when there is exception thrown -> the SC.OperationCompleted() is not called.
// use new SC here to avoid this issue
var orignal = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
// Pass a non-null state just to emphasize we're only testing passing a null delegate
var state = new object();
var operation = AsyncOperationManager.CreateOperation(state);
Assert.Throws<ArgumentNullException>(() => operation.Post(null, state));
Assert.Throws<ArgumentNullException>(() => operation.PostOperationCompleted(null, state));
}
finally
{
SynchronizationContext.SetSynchronizationContext(orignal);
}
}
// A simple wrapper for AsyncOperation which executes the specified delegate and a completion handler asynchronously.
public class TestAsyncOperation
{
private readonly object _operationId;
private readonly Action<TestAsyncOperation> _executeDelegate;
private readonly ManualResetEventSlim _cancelEvent;
private readonly ManualResetEventSlim _completeEvent;
public AsyncOperation AsyncOperation { get; private set; }
public bool Completed { get { return _completeEvent.IsSet; } }
public bool Cancelled { get { return _cancelEvent.IsSet; } }
public Exception Exception { get; private set; }
public TestAsyncOperation(Action<TestAsyncOperation> executeDelegate, ManualResetEventSlim cancelEvent = null)
{
// Create an async operation passing an object as the state so we can
// verify that state is passed properly.
_operationId = new object();
AsyncOperation = AsyncOperationManager.CreateOperation(_operationId);
Assert.Same(_operationId, AsyncOperation.UserSuppliedState);
Assert.Same(AsyncOperationManager.SynchronizationContext, AsyncOperation.SynchronizationContext);
_completeEvent = new ManualResetEventSlim(false);
_cancelEvent = cancelEvent ?? new ManualResetEventSlim(false);
// Post work to the wrapped synchronization context
_executeDelegate = executeDelegate;
AsyncOperation.Post((SendOrPostCallback)ExecuteWorker, _operationId);
}
public void Wait()
{
Assert.True(_completeEvent.Wait(TimeSpan.FromSeconds(SpinTimeoutSeconds)));
if (Exception != null)
{
throw Exception;
}
}
public void Cancel()
{
CompleteOperationAsync(cancelled: true);
}
private void ExecuteWorker(object operationId)
{
Assert.Same(_operationId, operationId);
Exception exception = null;
try
{
_executeDelegate(this);
}
catch (Exception e)
{
exception = e;
}
finally
{
CompleteOperationAsync(exception: exception);
}
}
private void CompleteOperationAsync(Exception exception = null, bool cancelled = false)
{
if (!(Completed || Cancelled))
{
AsyncOperation.PostOperationCompleted(
(SendOrPostCallback)OnOperationCompleted,
new AsyncCompletedEventArgs(
exception,
cancelled,
_operationId));
}
}
private void OnOperationCompleted(object state)
{
AsyncCompletedEventArgs e = Assert.IsType<AsyncCompletedEventArgs>(state);
Assert.Equal(_operationId, e.UserState);
Exception = e.Error;
// Make sure to set _cancelEvent before _completeEvent so that anyone waiting on
// _completeEvent will not be at risk of reading Cancelled before it is set.
if (e.Cancelled)
_cancelEvent.Set();
_completeEvent.Set();
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Configuration.ConfigurationManager/tests/Mono/TimeSpanMinutesConverterTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// System.Configuration.TimeSpanMinutesConverterTest.cs - Unit tests
// for System.Configuration.TimeSpanMinutesConverter.
//
// Author:
// Chris Toshok <[email protected]>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Configuration;
using Xunit;
namespace MonoTests.System.Configuration
{
public class TimeSpanMinutesConverterTest
{
[Fact]
public void CanConvertFrom()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
Assert.True(cv.CanConvertFrom(null, typeof(string)), "A1");
Assert.False(cv.CanConvertFrom(null, typeof(TimeSpan)), "A2");
Assert.False(cv.CanConvertFrom(null, typeof(int)), "A3");
Assert.False(cv.CanConvertFrom(null, typeof(object)), "A4");
}
[Fact]
public void CanConvertTo()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
Assert.True(cv.CanConvertTo(null, typeof(string)), "A1");
Assert.False(cv.CanConvertTo(null, typeof(TimeSpan)), "A2");
Assert.False(cv.CanConvertTo(null, typeof(int)), "A3");
Assert.False(cv.CanConvertTo(null, typeof(object)), "A4");
}
[Fact]
public void ConvertFrom()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
object o;
o = cv.ConvertFrom(null, null, "59");
Assert.Equal(typeof(TimeSpan), o.GetType());
Assert.Equal("00:59:00", o.ToString());
o = cv.ConvertFrom(null, null, "104");
Assert.Equal("01:44:00", o.ToString());
}
[Fact]
public void ConvertFrom_FormatError()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
object o = null;
Assert.Throws<FormatException>(() => o = cv.ConvertFrom(null, null, "100.5"));
Assert.Null(o);
}
[Fact]
public void ConvertFrom_TypeError()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
object o = null;
Assert.Throws<InvalidCastException>(() => o = cv.ConvertFrom(null, null, 59));
Assert.Null(o);
}
[Fact]
public void ConvertTo()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
TimeSpan ts;
ts = TimeSpan.FromMinutes(59);
Assert.Equal("59", cv.ConvertTo(null, null, ts, typeof(string)));
ts = TimeSpan.FromMinutes(144);
Assert.Equal("144", cv.ConvertTo(null, null, ts, typeof(string)));
ts = TimeSpan.FromSeconds(390);
Assert.Equal("6", cv.ConvertTo(null, null, ts, typeof(string)));
}
[Fact]
public void ConvertTo_NullError()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
Assert.Throws<NullReferenceException>(() => cv.ConvertTo(null, null, null, typeof(string)));
}
[Fact]
public void ConvertTo_TypeError1()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
AssertExtensions.Throws<ArgumentException>(null, () => cv.ConvertTo(null, null, 59, typeof(string)));
}
[Fact]
public void ConvertTo_TypeError2()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
TimeSpan ts;
ts = TimeSpan.FromMinutes(59);
Assert.Equal("59", cv.ConvertTo(null, null, ts, typeof(int)));
Assert.Equal("59", cv.ConvertTo(null, null, ts, null));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// System.Configuration.TimeSpanMinutesConverterTest.cs - Unit tests
// for System.Configuration.TimeSpanMinutesConverter.
//
// Author:
// Chris Toshok <[email protected]>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Configuration;
using Xunit;
namespace MonoTests.System.Configuration
{
public class TimeSpanMinutesConverterTest
{
[Fact]
public void CanConvertFrom()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
Assert.True(cv.CanConvertFrom(null, typeof(string)), "A1");
Assert.False(cv.CanConvertFrom(null, typeof(TimeSpan)), "A2");
Assert.False(cv.CanConvertFrom(null, typeof(int)), "A3");
Assert.False(cv.CanConvertFrom(null, typeof(object)), "A4");
}
[Fact]
public void CanConvertTo()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
Assert.True(cv.CanConvertTo(null, typeof(string)), "A1");
Assert.False(cv.CanConvertTo(null, typeof(TimeSpan)), "A2");
Assert.False(cv.CanConvertTo(null, typeof(int)), "A3");
Assert.False(cv.CanConvertTo(null, typeof(object)), "A4");
}
[Fact]
public void ConvertFrom()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
object o;
o = cv.ConvertFrom(null, null, "59");
Assert.Equal(typeof(TimeSpan), o.GetType());
Assert.Equal("00:59:00", o.ToString());
o = cv.ConvertFrom(null, null, "104");
Assert.Equal("01:44:00", o.ToString());
}
[Fact]
public void ConvertFrom_FormatError()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
object o = null;
Assert.Throws<FormatException>(() => o = cv.ConvertFrom(null, null, "100.5"));
Assert.Null(o);
}
[Fact]
public void ConvertFrom_TypeError()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
object o = null;
Assert.Throws<InvalidCastException>(() => o = cv.ConvertFrom(null, null, 59));
Assert.Null(o);
}
[Fact]
public void ConvertTo()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
TimeSpan ts;
ts = TimeSpan.FromMinutes(59);
Assert.Equal("59", cv.ConvertTo(null, null, ts, typeof(string)));
ts = TimeSpan.FromMinutes(144);
Assert.Equal("144", cv.ConvertTo(null, null, ts, typeof(string)));
ts = TimeSpan.FromSeconds(390);
Assert.Equal("6", cv.ConvertTo(null, null, ts, typeof(string)));
}
[Fact]
public void ConvertTo_NullError()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
Assert.Throws<NullReferenceException>(() => cv.ConvertTo(null, null, null, typeof(string)));
}
[Fact]
public void ConvertTo_TypeError1()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
AssertExtensions.Throws<ArgumentException>(null, () => cv.ConvertTo(null, null, 59, typeof(string)));
}
[Fact]
public void ConvertTo_TypeError2()
{
TimeSpanMinutesConverter cv = new TimeSpanMinutesConverter();
TimeSpan ts;
ts = TimeSpan.FromMinutes(59);
Assert.Equal("59", cv.ConvertTo(null, null, ts, typeof(int)));
Assert.Equal("59", cv.ConvertTo(null, null, ts, null));
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Or.Vector128.Byte.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Or_Vector128_Byte()
{
var test = new SimpleBinaryOpTest__Or_Vector128_Byte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__Or_Vector128_Byte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__Or_Vector128_Byte testClass)
{
var result = AdvSimd.Or(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__Or_Vector128_Byte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__Or_Vector128_Byte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__Or_Vector128_Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Or(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(pClsVar1)),
AdvSimd.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__Or_Vector128_Byte();
var result = AdvSimd.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__Or_Vector128_Byte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(&test._fld1)),
AdvSimd.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Or(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Or)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Or_Vector128_Byte()
{
var test = new SimpleBinaryOpTest__Or_Vector128_Byte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__Or_Vector128_Byte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__Or_Vector128_Byte testClass)
{
var result = AdvSimd.Or(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__Or_Vector128_Byte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__Or_Vector128_Byte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__Or_Vector128_Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Or(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(pClsVar1)),
AdvSimd.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__Or_Vector128_Byte();
var result = AdvSimd.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__Or_Vector128_Byte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Or(
AdvSimd.LoadVector128((Byte*)(&test._fld1)),
AdvSimd.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Or(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Or)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/General/Vector64/GreaterThanOrEqual.UInt32.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GreaterThanOrEqualUInt32()
{
var test = new VectorBinaryOpTest__GreaterThanOrEqualUInt32();
// 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__GreaterThanOrEqualUInt32
{
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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<UInt32> _fld1;
public Vector64<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__GreaterThanOrEqualUInt32 testClass)
{
var result = Vector64.GreaterThanOrEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector64<UInt32> _clsVar1;
private static Vector64<UInt32> _clsVar2;
private Vector64<UInt32> _fld1;
private Vector64<UInt32> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__GreaterThanOrEqualUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
}
public VectorBinaryOpTest__GreaterThanOrEqualUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.GreaterThanOrEqual(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.GreaterThanOrEqual), new Type[] {
typeof(Vector64<UInt32>),
typeof(Vector64<UInt32>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.GreaterThanOrEqual), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(UInt32));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.GreaterThanOrEqual(
_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<Vector64<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr);
var result = Vector64.GreaterThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__GreaterThanOrEqualUInt32();
var result = Vector64.GreaterThanOrEqual(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 = Vector64.GreaterThanOrEqual(_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 = Vector64.GreaterThanOrEqual(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(Vector64<UInt32> op1, Vector64<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] >= right[0]) ? uint.MaxValue : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] >= right[i]) ? uint.MaxValue : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.GreaterThanOrEqual)}<UInt32>(Vector64<UInt32>, Vector64<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GreaterThanOrEqualUInt32()
{
var test = new VectorBinaryOpTest__GreaterThanOrEqualUInt32();
// 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__GreaterThanOrEqualUInt32
{
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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<UInt32> _fld1;
public Vector64<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__GreaterThanOrEqualUInt32 testClass)
{
var result = Vector64.GreaterThanOrEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector64<UInt32> _clsVar1;
private static Vector64<UInt32> _clsVar2;
private Vector64<UInt32> _fld1;
private Vector64<UInt32> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__GreaterThanOrEqualUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
}
public VectorBinaryOpTest__GreaterThanOrEqualUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.GreaterThanOrEqual(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.GreaterThanOrEqual), new Type[] {
typeof(Vector64<UInt32>),
typeof(Vector64<UInt32>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.GreaterThanOrEqual), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(UInt32));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.GreaterThanOrEqual(
_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<Vector64<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr);
var result = Vector64.GreaterThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__GreaterThanOrEqualUInt32();
var result = Vector64.GreaterThanOrEqual(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 = Vector64.GreaterThanOrEqual(_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 = Vector64.GreaterThanOrEqual(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(Vector64<UInt32> op1, Vector64<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] >= right[0]) ? uint.MaxValue : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] >= right[i]) ? uint.MaxValue : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.GreaterThanOrEqual)}<UInt32>(Vector64<UInt32>, Vector64<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Linq.Expressions/tests/Lambda/LambdaModuloTests.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.Linq.Expressions.Tests
{
public static class LambdaModuloTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloDecimalTest(bool useInterpreter)
{
decimal[] values = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloDoubleTest(bool useInterpreter)
{
double[] values = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloFloatTest(bool useInterpreter)
{
float[] values = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloIntTest(bool useInterpreter)
{
int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloInt(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloLongTest(bool useInterpreter)
{
long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloLong(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloShortTest(bool useInterpreter)
{
short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloShort(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloUIntTest(bool useInterpreter)
{
uint[] values = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloULongTest(bool useInterpreter)
{
ulong[] values = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloULong(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloUShortTest(bool useInterpreter)
{
ushort[] values = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private enum ResultType
{
Success,
DivideByZero,
Overflow
}
#region Verify decimal
private static void VerifyModuloDecimal(decimal a, decimal b, bool useInterpreter)
{
bool divideByZero;
decimal expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(decimal), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal), "p1");
// verify with parameters supplied
Expression<Func<decimal>> e1 =
Expression.Lambda<Func<decimal>>(
Expression.Invoke(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<decimal, decimal, Func<decimal>>> e2 =
Expression.Lambda<Func<decimal, decimal, Func<decimal>>>(
Expression.Lambda<Func<decimal>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal, decimal, Func<decimal>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<decimal, decimal, decimal>>> e3 =
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal, decimal, decimal> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<decimal, decimal, decimal>>> e4 =
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal, decimal, decimal>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<decimal, Func<decimal, decimal>>> e5 =
Expression.Lambda<Func<decimal, Func<decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal, Func<decimal, decimal>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<decimal, decimal>>> e6 =
Expression.Lambda<Func<Func<decimal, decimal>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal, Func<decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal, decimal> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify double
private static void VerifyModuloDouble(double a, double b, bool useInterpreter)
{
double expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(double), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double), "p1");
// verify with parameters supplied
Expression<Func<double>> e1 =
Expression.Lambda<Func<double>>(
Expression.Invoke(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))
}),
Enumerable.Empty<ParameterExpression>());
Func<double> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<double, double, Func<double>>> e2 =
Expression.Lambda<Func<double, double, Func<double>>>(
Expression.Lambda<Func<double>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double, double, Func<double>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<double, double, double>>> e3 =
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double, double, double> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<double, double, double>>> e4 =
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double, double, double>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<double, Func<double, double>>> e5 =
Expression.Lambda<Func<double, Func<double, double>>>(
Expression.Lambda<Func<double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double, Func<double, double>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<double, double>>> e6 =
Expression.Lambda<Func<Func<double, double>>>(
Expression.Invoke(
Expression.Lambda<Func<double, Func<double, double>>>(
Expression.Lambda<Func<double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double)) }),
Enumerable.Empty<ParameterExpression>());
Func<double, double> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify float
private static void VerifyModuloFloat(float a, float b, bool useInterpreter)
{
float expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(float), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float), "p1");
// verify with parameters supplied
Expression<Func<float>> e1 =
Expression.Lambda<Func<float>>(
Expression.Invoke(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))
}),
Enumerable.Empty<ParameterExpression>());
Func<float> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<float, float, Func<float>>> e2 =
Expression.Lambda<Func<float, float, Func<float>>>(
Expression.Lambda<Func<float>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float, float, Func<float>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<float, float, float>>> e3 =
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float, float, float> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<float, float, float>>> e4 =
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float, float, float>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<float, Func<float, float>>> e5 =
Expression.Lambda<Func<float, Func<float, float>>>(
Expression.Lambda<Func<float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float, Func<float, float>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<float, float>>> e6 =
Expression.Lambda<Func<Func<float, float>>>(
Expression.Invoke(
Expression.Lambda<Func<float, Func<float, float>>>(
Expression.Lambda<Func<float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float)) }),
Enumerable.Empty<ParameterExpression>());
Func<float, float> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify int
private static void VerifyModuloInt(int a, int b, bool useInterpreter)
{
ResultType outcome;
int expected = 0;
if (b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == int.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(int), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int), "p1");
// verify with parameters supplied
Expression<Func<int>> e1 =
Expression.Lambda<Func<int>>(
Expression.Invoke(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))
}),
Enumerable.Empty<ParameterExpression>());
Func<int> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<int, int, Func<int>>> e2 =
Expression.Lambda<Func<int, int, Func<int>>>(
Expression.Lambda<Func<int>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int, int, Func<int>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<int, int, int>>> e3 =
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int, int, int> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<int, int, int>>> e4 =
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int, int, int>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<int, Func<int, int>>> e5 =
Expression.Lambda<Func<int, Func<int, int>>>(
Expression.Lambda<Func<int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int, Func<int, int>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<int, int>>> e6 =
Expression.Lambda<Func<Func<int, int>>>(
Expression.Invoke(
Expression.Lambda<Func<int, Func<int, int>>>(
Expression.Lambda<Func<int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int)) }),
Enumerable.Empty<ParameterExpression>());
Func<int, int> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify long
private static void VerifyModuloLong(long a, long b, bool useInterpreter)
{
ResultType outcome;
long expected = 0;
if (b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == long.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(long), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long), "p1");
// verify with parameters supplied
Expression<Func<long>> e1 =
Expression.Lambda<Func<long>>(
Expression.Invoke(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))
}),
Enumerable.Empty<ParameterExpression>());
Func<long> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<long, long, Func<long>>> e2 =
Expression.Lambda<Func<long, long, Func<long>>>(
Expression.Lambda<Func<long>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long, long, Func<long>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<long, long, long>>> e3 =
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long, long, long> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<long, long, long>>> e4 =
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long, long, long>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<long, Func<long, long>>> e5 =
Expression.Lambda<Func<long, Func<long, long>>>(
Expression.Lambda<Func<long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long, Func<long, long>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<long, long>>> e6 =
Expression.Lambda<Func<Func<long, long>>>(
Expression.Invoke(
Expression.Lambda<Func<long, Func<long, long>>>(
Expression.Lambda<Func<long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long)) }),
Enumerable.Empty<ParameterExpression>());
Func<long, long> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify short
private static void VerifyModuloShort(short a, short b, bool useInterpreter)
{
bool divideByZero;
short expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = (short)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(short), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short), "p1");
// verify with parameters supplied
Expression<Func<short>> e1 =
Expression.Lambda<Func<short>>(
Expression.Invoke(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))
}),
Enumerable.Empty<ParameterExpression>());
Func<short> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<short, short, Func<short>>> e2 =
Expression.Lambda<Func<short, short, Func<short>>>(
Expression.Lambda<Func<short>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short, short, Func<short>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<short, short, short>>> e3 =
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short, short, short> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<short, short, short>>> e4 =
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short, short, short>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<short, Func<short, short>>> e5 =
Expression.Lambda<Func<short, Func<short, short>>>(
Expression.Lambda<Func<short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short, Func<short, short>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<short, short>>> e6 =
Expression.Lambda<Func<Func<short, short>>>(
Expression.Invoke(
Expression.Lambda<Func<short, Func<short, short>>>(
Expression.Lambda<Func<short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short)) }),
Enumerable.Empty<ParameterExpression>());
Func<short, short> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify uint
private static void VerifyModuloUInt(uint a, uint b, bool useInterpreter)
{
bool divideByZero;
uint expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(uint), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint), "p1");
// verify with parameters supplied
Expression<Func<uint>> e1 =
Expression.Lambda<Func<uint>>(
Expression.Invoke(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<uint, uint, Func<uint>>> e2 =
Expression.Lambda<Func<uint, uint, Func<uint>>>(
Expression.Lambda<Func<uint>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint, uint, Func<uint>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<uint, uint, uint>>> e3 =
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint, uint, uint> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<uint, uint, uint>>> e4 =
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint, uint, uint>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<uint, Func<uint, uint>>> e5 =
Expression.Lambda<Func<uint, Func<uint, uint>>>(
Expression.Lambda<Func<uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint, Func<uint, uint>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<uint, uint>>> e6 =
Expression.Lambda<Func<Func<uint, uint>>>(
Expression.Invoke(
Expression.Lambda<Func<uint, Func<uint, uint>>>(
Expression.Lambda<Func<uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint, uint> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ulong
private static void VerifyModuloULong(ulong a, ulong b, bool useInterpreter)
{
bool divideByZero;
ulong expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(ulong), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong), "p1");
// verify with parameters supplied
Expression<Func<ulong>> e1 =
Expression.Lambda<Func<ulong>>(
Expression.Invoke(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ulong, ulong, Func<ulong>>> e2 =
Expression.Lambda<Func<ulong, ulong, Func<ulong>>>(
Expression.Lambda<Func<ulong>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong, ulong, Func<ulong>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ulong, ulong, ulong>>> e3 =
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong, ulong, ulong> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ulong, ulong, ulong>>> e4 =
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong, ulong, ulong>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ulong, Func<ulong, ulong>>> e5 =
Expression.Lambda<Func<ulong, Func<ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong, Func<ulong, ulong>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ulong, ulong>>> e6 =
Expression.Lambda<Func<Func<ulong, ulong>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong, Func<ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong, ulong> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ushort
private static void VerifyModuloUShort(ushort a, ushort b, bool useInterpreter)
{
bool divideByZero;
ushort expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = (ushort)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(ushort), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort), "p1");
// verify with parameters supplied
Expression<Func<ushort>> e1 =
Expression.Lambda<Func<ushort>>(
Expression.Invoke(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ushort, ushort, Func<ushort>>> e2 =
Expression.Lambda<Func<ushort, ushort, Func<ushort>>>(
Expression.Lambda<Func<ushort>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort, ushort, Func<ushort>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ushort, ushort, ushort>>> e3 =
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort, ushort, ushort> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ushort, ushort, ushort>>> e4 =
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort, ushort, ushort>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ushort, Func<ushort, ushort>>> e5 =
Expression.Lambda<Func<ushort, Func<ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort, Func<ushort, ushort>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ushort, ushort>>> e6 =
Expression.Lambda<Func<Func<ushort, ushort>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort, Func<ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort, ushort> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#endregion
}
}
| // 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.Linq.Expressions.Tests
{
public static class LambdaModuloTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloDecimalTest(bool useInterpreter)
{
decimal[] values = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloDoubleTest(bool useInterpreter)
{
double[] values = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloFloatTest(bool useInterpreter)
{
float[] values = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloIntTest(bool useInterpreter)
{
int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloInt(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloLongTest(bool useInterpreter)
{
long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloLong(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloShortTest(bool useInterpreter)
{
short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloShort(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloUIntTest(bool useInterpreter)
{
uint[] values = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloULongTest(bool useInterpreter)
{
ulong[] values = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloULong(values[i], values[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloUShortTest(bool useInterpreter)
{
ushort[] values = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private enum ResultType
{
Success,
DivideByZero,
Overflow
}
#region Verify decimal
private static void VerifyModuloDecimal(decimal a, decimal b, bool useInterpreter)
{
bool divideByZero;
decimal expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(decimal), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal), "p1");
// verify with parameters supplied
Expression<Func<decimal>> e1 =
Expression.Lambda<Func<decimal>>(
Expression.Invoke(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<decimal, decimal, Func<decimal>>> e2 =
Expression.Lambda<Func<decimal, decimal, Func<decimal>>>(
Expression.Lambda<Func<decimal>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal, decimal, Func<decimal>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<decimal, decimal, decimal>>> e3 =
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal, decimal, decimal> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<decimal, decimal, decimal>>> e4 =
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal, decimal, decimal>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<decimal, Func<decimal, decimal>>> e5 =
Expression.Lambda<Func<decimal, Func<decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal, Func<decimal, decimal>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<decimal, decimal>>> e6 =
Expression.Lambda<Func<Func<decimal, decimal>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal, Func<decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal, decimal> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify double
private static void VerifyModuloDouble(double a, double b, bool useInterpreter)
{
double expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(double), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double), "p1");
// verify with parameters supplied
Expression<Func<double>> e1 =
Expression.Lambda<Func<double>>(
Expression.Invoke(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))
}),
Enumerable.Empty<ParameterExpression>());
Func<double> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<double, double, Func<double>>> e2 =
Expression.Lambda<Func<double, double, Func<double>>>(
Expression.Lambda<Func<double>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double, double, Func<double>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<double, double, double>>> e3 =
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double, double, double> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<double, double, double>>> e4 =
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double, double, double>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<double, Func<double, double>>> e5 =
Expression.Lambda<Func<double, Func<double, double>>>(
Expression.Lambda<Func<double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double, Func<double, double>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<double, double>>> e6 =
Expression.Lambda<Func<Func<double, double>>>(
Expression.Invoke(
Expression.Lambda<Func<double, Func<double, double>>>(
Expression.Lambda<Func<double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double)) }),
Enumerable.Empty<ParameterExpression>());
Func<double, double> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify float
private static void VerifyModuloFloat(float a, float b, bool useInterpreter)
{
float expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(float), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float), "p1");
// verify with parameters supplied
Expression<Func<float>> e1 =
Expression.Lambda<Func<float>>(
Expression.Invoke(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))
}),
Enumerable.Empty<ParameterExpression>());
Func<float> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<float, float, Func<float>>> e2 =
Expression.Lambda<Func<float, float, Func<float>>>(
Expression.Lambda<Func<float>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float, float, Func<float>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<float, float, float>>> e3 =
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float, float, float> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<float, float, float>>> e4 =
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float, float, float>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<float, Func<float, float>>> e5 =
Expression.Lambda<Func<float, Func<float, float>>>(
Expression.Lambda<Func<float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float, Func<float, float>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<float, float>>> e6 =
Expression.Lambda<Func<Func<float, float>>>(
Expression.Invoke(
Expression.Lambda<Func<float, Func<float, float>>>(
Expression.Lambda<Func<float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float)) }),
Enumerable.Empty<ParameterExpression>());
Func<float, float> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify int
private static void VerifyModuloInt(int a, int b, bool useInterpreter)
{
ResultType outcome;
int expected = 0;
if (b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == int.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(int), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int), "p1");
// verify with parameters supplied
Expression<Func<int>> e1 =
Expression.Lambda<Func<int>>(
Expression.Invoke(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))
}),
Enumerable.Empty<ParameterExpression>());
Func<int> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<int, int, Func<int>>> e2 =
Expression.Lambda<Func<int, int, Func<int>>>(
Expression.Lambda<Func<int>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int, int, Func<int>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<int, int, int>>> e3 =
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int, int, int> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<int, int, int>>> e4 =
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int, int, int>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<int, Func<int, int>>> e5 =
Expression.Lambda<Func<int, Func<int, int>>>(
Expression.Lambda<Func<int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int, Func<int, int>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<int, int>>> e6 =
Expression.Lambda<Func<Func<int, int>>>(
Expression.Invoke(
Expression.Lambda<Func<int, Func<int, int>>>(
Expression.Lambda<Func<int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int)) }),
Enumerable.Empty<ParameterExpression>());
Func<int, int> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify long
private static void VerifyModuloLong(long a, long b, bool useInterpreter)
{
ResultType outcome;
long expected = 0;
if (b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == long.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(long), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long), "p1");
// verify with parameters supplied
Expression<Func<long>> e1 =
Expression.Lambda<Func<long>>(
Expression.Invoke(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))
}),
Enumerable.Empty<ParameterExpression>());
Func<long> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<long, long, Func<long>>> e2 =
Expression.Lambda<Func<long, long, Func<long>>>(
Expression.Lambda<Func<long>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long, long, Func<long>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<long, long, long>>> e3 =
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long, long, long> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<long, long, long>>> e4 =
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long, long, long>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<long, Func<long, long>>> e5 =
Expression.Lambda<Func<long, Func<long, long>>>(
Expression.Lambda<Func<long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long, Func<long, long>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<long, long>>> e6 =
Expression.Lambda<Func<Func<long, long>>>(
Expression.Invoke(
Expression.Lambda<Func<long, Func<long, long>>>(
Expression.Lambda<Func<long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long)) }),
Enumerable.Empty<ParameterExpression>());
Func<long, long> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify short
private static void VerifyModuloShort(short a, short b, bool useInterpreter)
{
bool divideByZero;
short expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = (short)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(short), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short), "p1");
// verify with parameters supplied
Expression<Func<short>> e1 =
Expression.Lambda<Func<short>>(
Expression.Invoke(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))
}),
Enumerable.Empty<ParameterExpression>());
Func<short> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<short, short, Func<short>>> e2 =
Expression.Lambda<Func<short, short, Func<short>>>(
Expression.Lambda<Func<short>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short, short, Func<short>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<short, short, short>>> e3 =
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short, short, short> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<short, short, short>>> e4 =
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short, short, short>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<short, Func<short, short>>> e5 =
Expression.Lambda<Func<short, Func<short, short>>>(
Expression.Lambda<Func<short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short, Func<short, short>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<short, short>>> e6 =
Expression.Lambda<Func<Func<short, short>>>(
Expression.Invoke(
Expression.Lambda<Func<short, Func<short, short>>>(
Expression.Lambda<Func<short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short)) }),
Enumerable.Empty<ParameterExpression>());
Func<short, short> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify uint
private static void VerifyModuloUInt(uint a, uint b, bool useInterpreter)
{
bool divideByZero;
uint expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(uint), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint), "p1");
// verify with parameters supplied
Expression<Func<uint>> e1 =
Expression.Lambda<Func<uint>>(
Expression.Invoke(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<uint, uint, Func<uint>>> e2 =
Expression.Lambda<Func<uint, uint, Func<uint>>>(
Expression.Lambda<Func<uint>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint, uint, Func<uint>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<uint, uint, uint>>> e3 =
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint, uint, uint> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<uint, uint, uint>>> e4 =
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint, uint, uint>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<uint, Func<uint, uint>>> e5 =
Expression.Lambda<Func<uint, Func<uint, uint>>>(
Expression.Lambda<Func<uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint, Func<uint, uint>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<uint, uint>>> e6 =
Expression.Lambda<Func<Func<uint, uint>>>(
Expression.Invoke(
Expression.Lambda<Func<uint, Func<uint, uint>>>(
Expression.Lambda<Func<uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint, uint> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ulong
private static void VerifyModuloULong(ulong a, ulong b, bool useInterpreter)
{
bool divideByZero;
ulong expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(ulong), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong), "p1");
// verify with parameters supplied
Expression<Func<ulong>> e1 =
Expression.Lambda<Func<ulong>>(
Expression.Invoke(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ulong, ulong, Func<ulong>>> e2 =
Expression.Lambda<Func<ulong, ulong, Func<ulong>>>(
Expression.Lambda<Func<ulong>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong, ulong, Func<ulong>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ulong, ulong, ulong>>> e3 =
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong, ulong, ulong> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ulong, ulong, ulong>>> e4 =
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong, ulong, ulong>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ulong, Func<ulong, ulong>>> e5 =
Expression.Lambda<Func<ulong, Func<ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong, Func<ulong, ulong>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ulong, ulong>>> e6 =
Expression.Lambda<Func<Func<ulong, ulong>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong, Func<ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong, ulong> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ushort
private static void VerifyModuloUShort(ushort a, ushort b, bool useInterpreter)
{
bool divideByZero;
ushort expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = (ushort)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(ushort), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort), "p1");
// verify with parameters supplied
Expression<Func<ushort>> e1 =
Expression.Lambda<Func<ushort>>(
Expression.Invoke(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ushort, ushort, Func<ushort>>> e2 =
Expression.Lambda<Func<ushort, ushort, Func<ushort>>>(
Expression.Lambda<Func<ushort>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort, ushort, Func<ushort>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ushort, ushort, ushort>>> e3 =
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort, ushort, ushort> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ushort, ushort, ushort>>> e4 =
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort, ushort, ushort>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ushort, Func<ushort, ushort>>> e5 =
Expression.Lambda<Func<ushort, Func<ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort, Func<ushort, ushort>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ushort, ushort>>> e6 =
Expression.Lambda<Func<Func<ushort, ushort>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort, Func<ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort, ushort> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#endregion
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/Loader/classloader/regressions/dev10_568786/4_Misc/ConstrainedMethods.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;
interface I<S> { string Method(S param); string Method<M>(S param); }
struct MyStruct : I<string>, I<object>
{
public string Method(string param) { return "string"; }
public string Method(object param) { return "object"; }
public string Method<M>(string param) { return "GEN-string"; }
public string Method<M>(object param) { return "GEN-object"; }
}
class Conversion1<T, U> where U : I<T>, new()
{
public string Caller1(T param)
{
U instance = new U();
return instance.Method(param);
}
public string Caller2(T param)
{
U instance = new U();
return instance.Method<object>(param);
}
}
class Conversion2<U> where U : I<string>, new()
{
public string Caller1()
{
U instance = new U();
return instance.Method("mystring");
}
public string Caller2()
{
U instance = new U();
return instance.Method<object>("mystring");
}
}
class Test_ConstrainedMethods
{
static string Caller1<T, U>(T param) where U : I<T>, new()
{
U instance = new U();
return instance.Method(param);
}
static string Caller2<T, U>(T param) where U : I<T>, new()
{
U instance = new U();
return instance.Method<object>(param);
}
static string Caller3<U>() where U : I<string>, new()
{
U instance = new U();
return instance.Method("mystring");
}
static string Caller4<U>() where U : I<string>, new()
{
U instance = new U();
return instance.Method<object>("mystring");
}
static int Main()
{
int numFailures = 0;
Conversion1<string, MyStruct> c1 = new Conversion1<string, MyStruct>();
Conversion2<MyStruct> c2 = new Conversion2<MyStruct>();
string res1 = Caller1<string, MyStruct>("mystring");
string res2 = Caller2<string, MyStruct>("mystring");
Console.WriteLine(res1);
Console.WriteLine(res2);
if(res1 != "string" && res2 != "GEN-string") numFailures++;
res1 = Caller3<MyStruct>();
res2 = Caller4<MyStruct>();
Console.WriteLine(res1);
Console.WriteLine(res2);
if(res1 != "string" && res2 != "GEN-string") numFailures++;
res1 = c1.Caller1("mystring");
res2 = c1.Caller2("mystring");
Console.WriteLine(res1);
Console.WriteLine(res2);
if(res1 != "string" && res2 != "GEN-string") numFailures++;
res1 = c2.Caller1();
res2 = c2.Caller2();
Console.WriteLine(res1);
Console.WriteLine(res2);
if(res1 != "string" && res2 != "GEN-string") numFailures++;
return ((numFailures == 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;
interface I<S> { string Method(S param); string Method<M>(S param); }
struct MyStruct : I<string>, I<object>
{
public string Method(string param) { return "string"; }
public string Method(object param) { return "object"; }
public string Method<M>(string param) { return "GEN-string"; }
public string Method<M>(object param) { return "GEN-object"; }
}
class Conversion1<T, U> where U : I<T>, new()
{
public string Caller1(T param)
{
U instance = new U();
return instance.Method(param);
}
public string Caller2(T param)
{
U instance = new U();
return instance.Method<object>(param);
}
}
class Conversion2<U> where U : I<string>, new()
{
public string Caller1()
{
U instance = new U();
return instance.Method("mystring");
}
public string Caller2()
{
U instance = new U();
return instance.Method<object>("mystring");
}
}
class Test_ConstrainedMethods
{
static string Caller1<T, U>(T param) where U : I<T>, new()
{
U instance = new U();
return instance.Method(param);
}
static string Caller2<T, U>(T param) where U : I<T>, new()
{
U instance = new U();
return instance.Method<object>(param);
}
static string Caller3<U>() where U : I<string>, new()
{
U instance = new U();
return instance.Method("mystring");
}
static string Caller4<U>() where U : I<string>, new()
{
U instance = new U();
return instance.Method<object>("mystring");
}
static int Main()
{
int numFailures = 0;
Conversion1<string, MyStruct> c1 = new Conversion1<string, MyStruct>();
Conversion2<MyStruct> c2 = new Conversion2<MyStruct>();
string res1 = Caller1<string, MyStruct>("mystring");
string res2 = Caller2<string, MyStruct>("mystring");
Console.WriteLine(res1);
Console.WriteLine(res2);
if(res1 != "string" && res2 != "GEN-string") numFailures++;
res1 = Caller3<MyStruct>();
res2 = Caller4<MyStruct>();
Console.WriteLine(res1);
Console.WriteLine(res2);
if(res1 != "string" && res2 != "GEN-string") numFailures++;
res1 = c1.Caller1("mystring");
res2 = c1.Caller2("mystring");
Console.WriteLine(res1);
Console.WriteLine(res2);
if(res1 != "string" && res2 != "GEN-string") numFailures++;
res1 = c2.Caller1();
res2 = c2.Caller2();
Console.WriteLine(res1);
Console.WriteLine(res2);
if(res1 != "string" && res2 != "GEN-string") numFailures++;
return ((numFailures == 0)?(100):(-1));
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/mono/mono/tests/sgen-new-threads-dont-join-stw.cs | using System;
using System.Timers;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
class T {
static int count = 0;
static object count_lock = new object();
const long N = 500000;
const int num_threads = 8;
static void UseMemory () {
for (int i = 0; i < N; ++i) {
var l1 = new ArrayList ();
l1.Add(""+i);
var l2 = new ArrayList ();
l2.Add(""+(i+1));
var l3 = new ArrayList ();
l3.Add(""+(i+2));
var l4 = new ArrayList ();
l4.Add(""+(i+3));
}
lock (count_lock)
{
count++;
Monitor.PulseAll(count_lock);
}
}
static void Timer_Elapsed(object sender, EventArgs e)
{
HashSet<string> h = new HashSet<string>();
for (int j = 0; j < 10000; j++)
{
h.Add(""+j+""+j);
}
}
static void Main (string[] args) {
int iterations = 0;
for (TestTimeout timeout = TestTimeout.Start(TimeSpan.FromSeconds(TestTimeout.IsStressTest ? 120 : 5)); timeout.HaveTimeLeft;)
{
count = 0;
List<Thread> threads = new List<Thread>();
List<System.Timers.Timer> timers = new List<System.Timers.Timer>();
for (int i = 0; i < num_threads; i++)
{
Thread t3 = new Thread (delegate () {
UseMemory();
});
t3.Start ();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = false;
timer.Interval = 1000;
timer.Start();
timers.Add(timer);
}
for (int i = 0; i < 4000; i++)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = false;
timer.Interval = 500;
timer.Start();
timers.Add(timer);
}
lock (count_lock)
{
while (count < num_threads)
{
Console.Write (".");
Monitor.Wait(count_lock);
}
}
foreach (var t in threads)
{
t.Join();
}
Console.WriteLine ();
iterations += 1;
}
Console.WriteLine ($"done {iterations} iterations");
}
}
| using System;
using System.Timers;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
class T {
static int count = 0;
static object count_lock = new object();
const long N = 500000;
const int num_threads = 8;
static void UseMemory () {
for (int i = 0; i < N; ++i) {
var l1 = new ArrayList ();
l1.Add(""+i);
var l2 = new ArrayList ();
l2.Add(""+(i+1));
var l3 = new ArrayList ();
l3.Add(""+(i+2));
var l4 = new ArrayList ();
l4.Add(""+(i+3));
}
lock (count_lock)
{
count++;
Monitor.PulseAll(count_lock);
}
}
static void Timer_Elapsed(object sender, EventArgs e)
{
HashSet<string> h = new HashSet<string>();
for (int j = 0; j < 10000; j++)
{
h.Add(""+j+""+j);
}
}
static void Main (string[] args) {
int iterations = 0;
for (TestTimeout timeout = TestTimeout.Start(TimeSpan.FromSeconds(TestTimeout.IsStressTest ? 120 : 5)); timeout.HaveTimeLeft;)
{
count = 0;
List<Thread> threads = new List<Thread>();
List<System.Timers.Timer> timers = new List<System.Timers.Timer>();
for (int i = 0; i < num_threads; i++)
{
Thread t3 = new Thread (delegate () {
UseMemory();
});
t3.Start ();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = false;
timer.Interval = 1000;
timer.Start();
timers.Add(timer);
}
for (int i = 0; i < 4000; i++)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = false;
timer.Interval = 500;
timer.Start();
timers.Add(timer);
}
lock (count_lock)
{
while (count < num_threads)
{
Console.Write (".");
Monitor.Wait(count_lock);
}
}
foreach (var t in threads)
{
t.Join();
}
Console.WriteLine ();
iterations += 1;
}
Console.WriteLine ($"done {iterations} iterations");
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Net.Primitives/src/System/Net/NetEventSource.Primitives.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.Tracing;
namespace System.Net
{
[EventSource(Name = "Private.InternalDiagnostics.System.Net.Primitives")]
internal sealed partial class NetEventSource { }
}
| // 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.Tracing;
namespace System.Net
{
[EventSource(Name = "Private.InternalDiagnostics.System.Net.Primitives")]
internal sealed partial class NetEventSource { }
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/mono/mono/tests/recursive-struct-arrays.cs | using System;
/* Test that the runtime can represent value types that have array fields that
* recursively refer to the same value type */
struct S1 {
static S1[][] foo;
}
struct S2 {
static S2[] foo;
}
struct S3a {
static S3b[] foo;
}
struct S3b {
static S3a[][] foo;
}
struct P<X> where X : struct {
static P<X>[][] foo;
}
public struct S4
{
private static S4[][] foo;
public static readonly S4 West = new S4(-1, 0);
public static readonly S4 East = new S4(1, 0);
public static readonly S4 North = new S4(0, 1);
public static readonly S4 South = new S4(0, -1);
public static readonly S4[] Directions = { North, South, East, West };
public readonly int x;
public readonly int z;
public S4(int x, int z)
{
this.x = x;
this.z = z;
}
public override string ToString()
{
return string.Format("[{0}, {1}]", x, z);
}
}
class Program {
static int Main() {
Console.WriteLine (typeof (S1).Name);
Console.WriteLine (typeof (S2).Name);
Console.WriteLine (typeof (S3a).Name);
Console.WriteLine (typeof (S3b).Name);
foreach (var s4 in S4.Directions) {
Console.WriteLine (s4);
}
Console.WriteLine (typeof (P<S1>).Name);
Console.WriteLine (typeof (P<int>).Name);
return 0;
}
}
| using System;
/* Test that the runtime can represent value types that have array fields that
* recursively refer to the same value type */
struct S1 {
static S1[][] foo;
}
struct S2 {
static S2[] foo;
}
struct S3a {
static S3b[] foo;
}
struct S3b {
static S3a[][] foo;
}
struct P<X> where X : struct {
static P<X>[][] foo;
}
public struct S4
{
private static S4[][] foo;
public static readonly S4 West = new S4(-1, 0);
public static readonly S4 East = new S4(1, 0);
public static readonly S4 North = new S4(0, 1);
public static readonly S4 South = new S4(0, -1);
public static readonly S4[] Directions = { North, South, East, West };
public readonly int x;
public readonly int z;
public S4(int x, int z)
{
this.x = x;
this.z = z;
}
public override string ToString()
{
return string.Format("[{0}, {1}]", x, z);
}
}
class Program {
static int Main() {
Console.WriteLine (typeof (S1).Name);
Console.WriteLine (typeof (S2).Name);
Console.WriteLine (typeof (S3a).Name);
Console.WriteLine (typeof (S3b).Name);
foreach (var s4 in S4.Directions) {
Console.WriteLine (s4);
}
Console.WriteLine (typeof (P<S1>).Name);
Console.WriteLine (typeof (P<int>).Name);
return 0;
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.IO.FileSystem/tests/PortedCommon/CommonUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/**
This is meant to contain useful utilities for IO related work
**/
#define TRACE
#define DEBUG
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
//machine information
public static class FileSystemDebugInfo
{
public static string MachineInfo()
{
StringBuilder builder = new StringBuilder(string.Format("{0}/////////Machine Info///////////{0}", Environment.NewLine));
builder.AppendLine(string.Format("CurrentDrive NTFS?: {0}", IsCurrentDriveNTFS()));
builder.AppendLine(string.Format("////////////////////{0}", Environment.NewLine));
return builder.ToString();
}
public static bool IsCurrentDriveNTFS()
{
return IOServices.IsDriveNTFS(IOServices.GetCurrentDrive());
}
public static bool IsPathAdminAccessOnly(string path, bool treatPathAsFilePath)
{
//we leave invalid paths as valid testcase scenarios and don't filter these
//1) We check if the path is root on a system drive
//2) @TODO WinDir?
string systemDrive = Environment.GetEnvironmentVariable("SystemDrive");
char systemDriveLetter = systemDrive.ToLower()[0];
try
{
string dirName = Path.GetFullPath(path);
if (treatPathAsFilePath)
dirName = Path.GetDirectoryName(dirName);
if ((new DirectoryInfo(dirName)).Parent == null)
{
if (Path.GetPathRoot(dirName).StartsWith(systemDriveLetter.ToString(), StringComparison.OrdinalIgnoreCase))
return true;
}
}
catch (Exception) { }
return false;
}
}
/// <summary>
/// Due to the increasing number of context indexing services (mssearch.exe, etrust) operating in our test run machines, Directory operations like Delete and Move
/// are not guaranteed to work in first attempt. This utility class do these operations in a fail safe manner
/// Possible solutions
/// - Set FileAttributes.NotContentIndex on the directory. But there is a race between creating the directory and setting this property. Other than using ACL, can't see a good solution
/// - encourage labs to stop these services before a test run. This is under review by CLRLab but there are lots of other labs that do these too
/// - fail and retry attempt: which is what this class does
/// VSW 446086 and 473287 have more information on this.
/// </summary>
public static class FailSafeDirectoryOperations
{
/// <summary>
/// Deleting
/// </summary>
/// <param name="path"></param>
/// <param name="recursive"></param>
private const int MAX_ATTEMPT = 10;
public static void DeleteDirectory(string path, bool recursive)
{
DeleteDirectoryInfo(new DirectoryInfo(path), recursive);
}
public static void DeleteDirectoryInfo(DirectoryInfo dirInfo, bool recursive)
{
int dirModificationAttemptCount;
bool dirModificationOperationThrew;
dirModificationAttemptCount = 0;
do
{
dirModificationOperationThrew = false;
try
{
if (dirInfo.Exists)
dirInfo.Delete(recursive);
}
catch (IOException)
{
Console.Write("|");
dirModificationOperationThrew = true;
}
catch (UnauthorizedAccessException)
{
Console.Write("}");
dirModificationOperationThrew = true;
}
if (dirModificationOperationThrew)
{
Task.Delay(5000).Wait();
}
} while (dirModificationOperationThrew && dirModificationAttemptCount++ < MAX_ATTEMPT);
EnsureDirectoryNotExist(dirInfo.FullName);
//We want to thrown if the operation failed
if (Directory.Exists(dirInfo.FullName))
throw new ArgumentException("Throwing from FailSafeDirectoryOperations.DeleteDirectoryInfo. Delete unsuccessful");
}
/// <summary>
/// Moving
/// </summary>
/// <param name="sourceName"></param>
/// <param name="destName"></param>
public static void MoveDirectory(string sourceName, string destName)
{
MoveDirectoryInfo(new DirectoryInfo(sourceName), destName);
}
public static DirectoryInfo MoveDirectoryInfo(DirectoryInfo dirInfo, string dirToMove)
{
int dirModificationAttemptCount;
bool dirModificationOperationThrew;
dirModificationAttemptCount = 0;
string originalDirName = dirInfo.FullName;
do
{
dirModificationOperationThrew = false;
try
{
dirInfo.MoveTo(dirToMove);
}
catch (IOException)
{
Console.Write(">");
Task.Delay(5000).Wait();
dirModificationOperationThrew = true;
}
} while (dirModificationOperationThrew && dirModificationAttemptCount++ < MAX_ATTEMPT);
EnsureDirectoryNotExist(originalDirName);
//We want to thrown if the operation failed
if (Directory.Exists(originalDirName))
throw new ArgumentException("Throwing from FailSafeDirectoryOperations.MoveDirectory. Move unsuccessful");
return dirInfo;
}
/// <summary>
/// It can take some time before the Directory.Exists will return false after a directory delete/Move
/// </summary>
/// <param name="path"></param>
private static void EnsureDirectoryNotExist(string path)
{
int dirModificationAttemptCount;
dirModificationAttemptCount = 0;
while (Directory.Exists(path) && dirModificationAttemptCount++ < MAX_ATTEMPT)
{
// This is because something like antivirus software or
// some disk indexing service has a handle to the directory. The directory
// won't be deleted until all of the handles are closed.
Task.Delay(5000).Wait();
Console.Write("<");
}
}
}
/// <summary>
/// This class is meant to create directory and files under it
/// </summary>
public class ManageFileSystem : IDisposable
{
private const int DefaultDirectoryDepth = 3;
private const int DefaultNumberofFiles = 100;
private const int MaxNumberOfSubDirsPerDir = 2;
//@TODO
public const string DirPrefixName = "Laks_";
private int _directoryLevel;
private int _numberOfFiles;
private string _startDir;
private Random _random;
private List<string> _listOfFiles;
private List<string> _listOfAllDirs;
private Dictionary<int, Dictionary<string, List<string>>> _allDirs;
public ManageFileSystem()
{
Init(GetNonExistingDir(Directory.GetCurrentDirectory(), DirPrefixName), DefaultDirectoryDepth, DefaultNumberofFiles);
}
public ManageFileSystem(string startDirName)
: this(startDirName, DefaultDirectoryDepth, DefaultNumberofFiles)
{
}
public ManageFileSystem(string startDirName, int dirDepth, int numFiles)
{
Init(startDirName, dirDepth, numFiles);
}
public static string GetNonExistingDir(string parentDir, string prefix)
{
string tempPath;
while (true)
{
tempPath = Path.Combine(parentDir, string.Format("{0}{1}", prefix, Path.GetFileNameWithoutExtension(Path.GetRandomFileName())));
if (!Directory.Exists(tempPath) && !File.Exists(tempPath))
break;
}
return tempPath;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free other state (managed objects)
// set interesting (large) fields to null
}
// free your own state (unmanaged objects)
FailSafeDirectoryOperations.DeleteDirectory(_startDir, true);
}
~ManageFileSystem()
{
Dispose(false);
}
private void Init(string startDirName, int dirDepth, int numFiles)
{
if (Directory.Exists(Path.GetFullPath(startDirName)))
throw new ArgumentException(string.Format("ERROR: Directory exists : {0}", _startDir));
_startDir = Path.GetFullPath(startDirName);
_directoryLevel = dirDepth;
_numberOfFiles = numFiles;
_random = new Random(-55);
CreateFileSystem();
}
/// <summary>
/// This API creates a file system under m_startDir, m_DirectoryLevel deep with m_numberOfFiles
/// We will store the created information on collections so as to get to them later
/// </summary>
private void CreateFileSystem()
{
_listOfFiles = new List<string>();
_listOfAllDirs = new List<string>();
Directory.CreateDirectory(_startDir);
//we will not include this directory
// m_listOfAllDirs.Add(m_startDir);
_allDirs = new Dictionary<int, Dictionary<string, List<string>>>();
// List<String> dirsForOneLevel = new List<String>();
// List<String> tempDirsForOneLevel;
List<string> filesForThisDir;
Dictionary<string, List<string>> dirsForOneLevel = new Dictionary<string, List<string>>();
Dictionary<string, List<string>> tempDirsForOneLevel;
dirsForOneLevel.Add(_startDir, new List<string>());
_allDirs.Add(0, dirsForOneLevel);
//First we create the directories
for (int i = 0; i < (_directoryLevel - 1); i++)
{
dirsForOneLevel = _allDirs[i];
int numOfDirForThisLevel = _random.Next((MaxNumberOfSubDirsPerDir + 1));
int numOfDirPerDir = numOfDirForThisLevel / dirsForOneLevel.Count;
//@TODO!! we should handle this situation in a better way
if (numOfDirPerDir == 0)
numOfDirPerDir = 1;
// Trace.Assert(numOfDirPerDir > 0, "Err_897324g! @TODO handle this scenario");
tempDirsForOneLevel = new Dictionary<string, List<string>>();
foreach (string dir in dirsForOneLevel.Keys)
// for (int j = 0; j < dirsForOneLevel.Count; j++)
{
for (int k = 0; k < numOfDirPerDir; k++)
{
string dirName = GetNonExistingDir(dir, DirPrefixName);
Debug.Assert(!Directory.Exists(dirName), $"ERR_93472g! Directory exists: {dirName}");
tempDirsForOneLevel.Add(dirName, new List<string>());
_listOfAllDirs.Add(dirName);
Directory.CreateDirectory(dirName);
}
}
_allDirs.Add(i + 1, tempDirsForOneLevel);
}
//Then we add the files
//@TODO!! random or fixed?
int numberOfFilePerDirLevel = _numberOfFiles / _directoryLevel;
byte[] bits;
for (int i = 0; i < _directoryLevel; i++)
{
dirsForOneLevel = _allDirs[i];
int numOfFilesForThisLevel = _random.Next(numberOfFilePerDirLevel + 1);
int numOFilesPerDir = numOfFilesForThisLevel / dirsForOneLevel.Count;
//UPDATE: 2/1/2005, we will add at least 1
if (numOFilesPerDir == 0)
numOFilesPerDir = 1;
// for (int j = 0; j < dirsForOneLevel.Count; j++)
foreach (string dir in dirsForOneLevel.Keys)
{
filesForThisDir = dirsForOneLevel[dir];
for (int k = 0; k < numOFilesPerDir; k++)
{
string fileName = Path.Combine(dir, Path.GetFileName(Path.GetRandomFileName()));
bits = new byte[_random.Next(10)];
_random.NextBytes(bits);
File.WriteAllBytes(fileName, bits);
_listOfFiles.Add(fileName);
filesForThisDir.Add(fileName);
}
}
}
}
public string StartDirectory
{
get { return _startDir; }
}
//some methods to help us
public string[] GetDirectories(int level)
{
Dictionary<string, List<string>> dirsForThisLevel = null;
if (_allDirs.TryGetValue(level, out dirsForThisLevel))
{
// Dictionary<String, List<String>> dirsForThisLevel = m_allDirs[level];
ICollection<string> keys = dirsForThisLevel.Keys;
string[] values = new string[keys.Count];
keys.CopyTo(values, 0);
return values;
}
else
return new string[0];
}
/// <summary>
/// Note that this doesn't return the m_startDir
/// </summary>
/// <returns></returns>
public string[] GetAllDirectories()
{
return _listOfAllDirs.ToArray();
}
public string[] GetFiles(string dirName, int level)
{
string dirFullName = Path.GetFullPath(dirName);
Dictionary<string, List<string>> dirsForThisLevel = _allDirs[level];
foreach (string dir in dirsForThisLevel.Keys)
{
if (dir.Equals(dirFullName, StringComparison.CurrentCultureIgnoreCase))
return dirsForThisLevel[dir].ToArray();
}
return null;
}
public string[] GetAllFiles()
{
return _listOfFiles.ToArray();
}
}
public class TestInfo
{
static TestInfo()
{
CurrentDirectory = Directory.GetCurrentDirectory();
}
public static string CurrentDirectory { get; set; }
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/**
This is meant to contain useful utilities for IO related work
**/
#define TRACE
#define DEBUG
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
//machine information
public static class FileSystemDebugInfo
{
public static string MachineInfo()
{
StringBuilder builder = new StringBuilder(string.Format("{0}/////////Machine Info///////////{0}", Environment.NewLine));
builder.AppendLine(string.Format("CurrentDrive NTFS?: {0}", IsCurrentDriveNTFS()));
builder.AppendLine(string.Format("////////////////////{0}", Environment.NewLine));
return builder.ToString();
}
public static bool IsCurrentDriveNTFS()
{
return IOServices.IsDriveNTFS(IOServices.GetCurrentDrive());
}
public static bool IsPathAdminAccessOnly(string path, bool treatPathAsFilePath)
{
//we leave invalid paths as valid testcase scenarios and don't filter these
//1) We check if the path is root on a system drive
//2) @TODO WinDir?
string systemDrive = Environment.GetEnvironmentVariable("SystemDrive");
char systemDriveLetter = systemDrive.ToLower()[0];
try
{
string dirName = Path.GetFullPath(path);
if (treatPathAsFilePath)
dirName = Path.GetDirectoryName(dirName);
if ((new DirectoryInfo(dirName)).Parent == null)
{
if (Path.GetPathRoot(dirName).StartsWith(systemDriveLetter.ToString(), StringComparison.OrdinalIgnoreCase))
return true;
}
}
catch (Exception) { }
return false;
}
}
/// <summary>
/// Due to the increasing number of context indexing services (mssearch.exe, etrust) operating in our test run machines, Directory operations like Delete and Move
/// are not guaranteed to work in first attempt. This utility class do these operations in a fail safe manner
/// Possible solutions
/// - Set FileAttributes.NotContentIndex on the directory. But there is a race between creating the directory and setting this property. Other than using ACL, can't see a good solution
/// - encourage labs to stop these services before a test run. This is under review by CLRLab but there are lots of other labs that do these too
/// - fail and retry attempt: which is what this class does
/// VSW 446086 and 473287 have more information on this.
/// </summary>
public static class FailSafeDirectoryOperations
{
/// <summary>
/// Deleting
/// </summary>
/// <param name="path"></param>
/// <param name="recursive"></param>
private const int MAX_ATTEMPT = 10;
public static void DeleteDirectory(string path, bool recursive)
{
DeleteDirectoryInfo(new DirectoryInfo(path), recursive);
}
public static void DeleteDirectoryInfo(DirectoryInfo dirInfo, bool recursive)
{
int dirModificationAttemptCount;
bool dirModificationOperationThrew;
dirModificationAttemptCount = 0;
do
{
dirModificationOperationThrew = false;
try
{
if (dirInfo.Exists)
dirInfo.Delete(recursive);
}
catch (IOException)
{
Console.Write("|");
dirModificationOperationThrew = true;
}
catch (UnauthorizedAccessException)
{
Console.Write("}");
dirModificationOperationThrew = true;
}
if (dirModificationOperationThrew)
{
Task.Delay(5000).Wait();
}
} while (dirModificationOperationThrew && dirModificationAttemptCount++ < MAX_ATTEMPT);
EnsureDirectoryNotExist(dirInfo.FullName);
//We want to thrown if the operation failed
if (Directory.Exists(dirInfo.FullName))
throw new ArgumentException("Throwing from FailSafeDirectoryOperations.DeleteDirectoryInfo. Delete unsuccessful");
}
/// <summary>
/// Moving
/// </summary>
/// <param name="sourceName"></param>
/// <param name="destName"></param>
public static void MoveDirectory(string sourceName, string destName)
{
MoveDirectoryInfo(new DirectoryInfo(sourceName), destName);
}
public static DirectoryInfo MoveDirectoryInfo(DirectoryInfo dirInfo, string dirToMove)
{
int dirModificationAttemptCount;
bool dirModificationOperationThrew;
dirModificationAttemptCount = 0;
string originalDirName = dirInfo.FullName;
do
{
dirModificationOperationThrew = false;
try
{
dirInfo.MoveTo(dirToMove);
}
catch (IOException)
{
Console.Write(">");
Task.Delay(5000).Wait();
dirModificationOperationThrew = true;
}
} while (dirModificationOperationThrew && dirModificationAttemptCount++ < MAX_ATTEMPT);
EnsureDirectoryNotExist(originalDirName);
//We want to thrown if the operation failed
if (Directory.Exists(originalDirName))
throw new ArgumentException("Throwing from FailSafeDirectoryOperations.MoveDirectory. Move unsuccessful");
return dirInfo;
}
/// <summary>
/// It can take some time before the Directory.Exists will return false after a directory delete/Move
/// </summary>
/// <param name="path"></param>
private static void EnsureDirectoryNotExist(string path)
{
int dirModificationAttemptCount;
dirModificationAttemptCount = 0;
while (Directory.Exists(path) && dirModificationAttemptCount++ < MAX_ATTEMPT)
{
// This is because something like antivirus software or
// some disk indexing service has a handle to the directory. The directory
// won't be deleted until all of the handles are closed.
Task.Delay(5000).Wait();
Console.Write("<");
}
}
}
/// <summary>
/// This class is meant to create directory and files under it
/// </summary>
public class ManageFileSystem : IDisposable
{
private const int DefaultDirectoryDepth = 3;
private const int DefaultNumberofFiles = 100;
private const int MaxNumberOfSubDirsPerDir = 2;
//@TODO
public const string DirPrefixName = "Laks_";
private int _directoryLevel;
private int _numberOfFiles;
private string _startDir;
private Random _random;
private List<string> _listOfFiles;
private List<string> _listOfAllDirs;
private Dictionary<int, Dictionary<string, List<string>>> _allDirs;
public ManageFileSystem()
{
Init(GetNonExistingDir(Directory.GetCurrentDirectory(), DirPrefixName), DefaultDirectoryDepth, DefaultNumberofFiles);
}
public ManageFileSystem(string startDirName)
: this(startDirName, DefaultDirectoryDepth, DefaultNumberofFiles)
{
}
public ManageFileSystem(string startDirName, int dirDepth, int numFiles)
{
Init(startDirName, dirDepth, numFiles);
}
public static string GetNonExistingDir(string parentDir, string prefix)
{
string tempPath;
while (true)
{
tempPath = Path.Combine(parentDir, string.Format("{0}{1}", prefix, Path.GetFileNameWithoutExtension(Path.GetRandomFileName())));
if (!Directory.Exists(tempPath) && !File.Exists(tempPath))
break;
}
return tempPath;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free other state (managed objects)
// set interesting (large) fields to null
}
// free your own state (unmanaged objects)
FailSafeDirectoryOperations.DeleteDirectory(_startDir, true);
}
~ManageFileSystem()
{
Dispose(false);
}
private void Init(string startDirName, int dirDepth, int numFiles)
{
if (Directory.Exists(Path.GetFullPath(startDirName)))
throw new ArgumentException(string.Format("ERROR: Directory exists : {0}", _startDir));
_startDir = Path.GetFullPath(startDirName);
_directoryLevel = dirDepth;
_numberOfFiles = numFiles;
_random = new Random(-55);
CreateFileSystem();
}
/// <summary>
/// This API creates a file system under m_startDir, m_DirectoryLevel deep with m_numberOfFiles
/// We will store the created information on collections so as to get to them later
/// </summary>
private void CreateFileSystem()
{
_listOfFiles = new List<string>();
_listOfAllDirs = new List<string>();
Directory.CreateDirectory(_startDir);
//we will not include this directory
// m_listOfAllDirs.Add(m_startDir);
_allDirs = new Dictionary<int, Dictionary<string, List<string>>>();
// List<String> dirsForOneLevel = new List<String>();
// List<String> tempDirsForOneLevel;
List<string> filesForThisDir;
Dictionary<string, List<string>> dirsForOneLevel = new Dictionary<string, List<string>>();
Dictionary<string, List<string>> tempDirsForOneLevel;
dirsForOneLevel.Add(_startDir, new List<string>());
_allDirs.Add(0, dirsForOneLevel);
//First we create the directories
for (int i = 0; i < (_directoryLevel - 1); i++)
{
dirsForOneLevel = _allDirs[i];
int numOfDirForThisLevel = _random.Next((MaxNumberOfSubDirsPerDir + 1));
int numOfDirPerDir = numOfDirForThisLevel / dirsForOneLevel.Count;
//@TODO!! we should handle this situation in a better way
if (numOfDirPerDir == 0)
numOfDirPerDir = 1;
// Trace.Assert(numOfDirPerDir > 0, "Err_897324g! @TODO handle this scenario");
tempDirsForOneLevel = new Dictionary<string, List<string>>();
foreach (string dir in dirsForOneLevel.Keys)
// for (int j = 0; j < dirsForOneLevel.Count; j++)
{
for (int k = 0; k < numOfDirPerDir; k++)
{
string dirName = GetNonExistingDir(dir, DirPrefixName);
Debug.Assert(!Directory.Exists(dirName), $"ERR_93472g! Directory exists: {dirName}");
tempDirsForOneLevel.Add(dirName, new List<string>());
_listOfAllDirs.Add(dirName);
Directory.CreateDirectory(dirName);
}
}
_allDirs.Add(i + 1, tempDirsForOneLevel);
}
//Then we add the files
//@TODO!! random or fixed?
int numberOfFilePerDirLevel = _numberOfFiles / _directoryLevel;
byte[] bits;
for (int i = 0; i < _directoryLevel; i++)
{
dirsForOneLevel = _allDirs[i];
int numOfFilesForThisLevel = _random.Next(numberOfFilePerDirLevel + 1);
int numOFilesPerDir = numOfFilesForThisLevel / dirsForOneLevel.Count;
//UPDATE: 2/1/2005, we will add at least 1
if (numOFilesPerDir == 0)
numOFilesPerDir = 1;
// for (int j = 0; j < dirsForOneLevel.Count; j++)
foreach (string dir in dirsForOneLevel.Keys)
{
filesForThisDir = dirsForOneLevel[dir];
for (int k = 0; k < numOFilesPerDir; k++)
{
string fileName = Path.Combine(dir, Path.GetFileName(Path.GetRandomFileName()));
bits = new byte[_random.Next(10)];
_random.NextBytes(bits);
File.WriteAllBytes(fileName, bits);
_listOfFiles.Add(fileName);
filesForThisDir.Add(fileName);
}
}
}
}
public string StartDirectory
{
get { return _startDir; }
}
//some methods to help us
public string[] GetDirectories(int level)
{
Dictionary<string, List<string>> dirsForThisLevel = null;
if (_allDirs.TryGetValue(level, out dirsForThisLevel))
{
// Dictionary<String, List<String>> dirsForThisLevel = m_allDirs[level];
ICollection<string> keys = dirsForThisLevel.Keys;
string[] values = new string[keys.Count];
keys.CopyTo(values, 0);
return values;
}
else
return new string[0];
}
/// <summary>
/// Note that this doesn't return the m_startDir
/// </summary>
/// <returns></returns>
public string[] GetAllDirectories()
{
return _listOfAllDirs.ToArray();
}
public string[] GetFiles(string dirName, int level)
{
string dirFullName = Path.GetFullPath(dirName);
Dictionary<string, List<string>> dirsForThisLevel = _allDirs[level];
foreach (string dir in dirsForThisLevel.Keys)
{
if (dir.Equals(dirFullName, StringComparison.CurrentCultureIgnoreCase))
return dirsForThisLevel[dir].ToArray();
}
return null;
}
public string[] GetAllFiles()
{
return _listOfFiles.ToArray();
}
}
public class TestInfo
{
static TestInfo()
{
CurrentDirectory = Directory.GetCurrentDirectory();
}
public static string CurrentDirectory { get; set; }
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/mono/mono/tests/assembly-load-dir1/LibStrongName.cs |
using System.Reflection;
[assembly:AssemblyVersion("1.0.0.0")]
public class LibClass {
public int OnlyInVersion1;
public int InAllVersions;
public LibClass () {}
}
|
using System.Reflection;
[assembly:AssemblyVersion("1.0.0.0")]
public class LibClass {
public int OnlyInVersion1;
public int InAllVersions;
public LibClass () {}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/X86/Avx2/Add.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;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddUInt16()
{
var test = new SimpleBinaryOpTest__AddUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddUInt16
{
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 * 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 Vector256<UInt16> _fld1;
public Vector256<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<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddUInt16 testClass)
{
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddUInt16 testClass)
{
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public SimpleBinaryOpTest__AddUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Add(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Add(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(pClsVar1)),
Avx.LoadVector256((UInt16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddUInt16();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddUInt16();
fixed (Vector256<UInt16>* pFld1 = &test._fld1)
fixed (Vector256<UInt16>* pFld2 = &test._fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(&test._fld1)),
Avx.LoadVector256((UInt16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<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<Vector256<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<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ushort)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ushort)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Add)}<UInt16>(Vector256<UInt16>, Vector256<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;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddUInt16()
{
var test = new SimpleBinaryOpTest__AddUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddUInt16
{
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 * 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 Vector256<UInt16> _fld1;
public Vector256<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<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddUInt16 testClass)
{
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddUInt16 testClass)
{
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public SimpleBinaryOpTest__AddUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Add(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Add(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(pClsVar1)),
Avx.LoadVector256((UInt16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddUInt16();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddUInt16();
fixed (Vector256<UInt16>* pFld1 = &test._fld1)
fixed (Vector256<UInt16>* pFld2 = &test._fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(&test._fld1)),
Avx.LoadVector256((UInt16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<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<Vector256<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<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ushort)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ushort)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Add)}<UInt16>(Vector256<UInt16>, Vector256<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,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.Runtime.InteropServices.JavaScript/tests/System/Runtime/InteropServices/JavaScript/Http/HttpRequestMessageTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;
using System.Runtime.InteropServices.JavaScript.Tests;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Runtime.InteropServices.JavaScript.Http.Tests
{
public class HttpRequestMessageTest
{
private readonly Version _expectedRequestMessageVersion = HttpVersion.Version11;
private HttpRequestOptionsKey<bool> EnableStreamingResponse = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse");
#nullable enable
private HttpRequestOptionsKey<IDictionary<string, object?>> FetchOptions = new HttpRequestOptionsKey<IDictionary<string, object?>>("WebAssemblyFetchOptions");
#nullable disable
[Fact]
public void Ctor_Default_CorrectDefaults()
{
var rm = new HttpRequestMessage();
Assert.Equal(HttpMethod.Get, rm.Method);
Assert.Null(rm.Content);
Assert.Null(rm.RequestUri);
}
[Fact]
public void Ctor_RelativeStringUri_CorrectValues()
{
var rm = new HttpRequestMessage(HttpMethod.Post, "/relative");
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(new Uri("/relative", UriKind.Relative), rm.RequestUri);
}
[Theory]
[InlineData("http://host/absolute/")]
[InlineData("blob:http://host/absolute/")]
[InlineData("foo://host/absolute")]
public void Ctor_AbsoluteStringUri_CorrectValues(string uri)
{
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(new Uri(uri), rm.RequestUri);
}
[Fact]
public void Ctor_NullStringUri_Accepted()
{
var rm = new HttpRequestMessage(HttpMethod.Put, (string)null);
Assert.Null(rm.RequestUri);
Assert.Equal(HttpMethod.Put, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
}
[Fact]
public void Ctor_RelativeUri_CorrectValues()
{
var uri = new Uri("/relative", UriKind.Relative);
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(uri, rm.RequestUri);
}
[Theory]
[InlineData("http://host/absolute/")]
[InlineData("blob:http://host/absolute/")]
[InlineData("foo://host/absolute")]
public void Ctor_AbsoluteUri_CorrectValues(string uriData)
{
var uri = new Uri(uriData);
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(uri, rm.RequestUri);
}
[Fact]
public void Ctor_NullUri_Accepted()
{
var rm = new HttpRequestMessage(HttpMethod.Put, (Uri)null);
Assert.Null(rm.RequestUri);
Assert.Equal(HttpMethod.Put, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
}
[Theory]
[InlineData("http://example.com")]
[InlineData("blob:http://example.com")]
public void Ctor_NullMethod_ThrowsArgumentNullException(string uriData)
{
Assert.Throws<ArgumentNullException>(() => new HttpRequestMessage(null, uriData));
}
[Theory]
[InlineData("http://example.com")]
[InlineData("blob:http://example.com")]
public void Dispose_DisposeObject_ContentGetsDisposedAndSettersWillThrowButGettersStillWork(string uriData)
{
var rm = new HttpRequestMessage(HttpMethod.Get, uriData);
var content = new MockContent();
rm.Content = content;
Assert.False(content.IsDisposed);
rm.Dispose();
rm.Dispose(); // Multiple calls don't throw.
Assert.True(content.IsDisposed);
Assert.Throws<ObjectDisposedException>(() => { rm.Method = HttpMethod.Put; });
Assert.Throws<ObjectDisposedException>(() => { rm.RequestUri = null; });
Assert.Throws<ObjectDisposedException>(() => { rm.Version = new Version(1, 0); });
Assert.Throws<ObjectDisposedException>(() => { rm.Content = null; });
// Property getters should still work after disposing.
Assert.Equal(HttpMethod.Get, rm.Method);
Assert.Equal(new Uri(uriData), rm.RequestUri);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(content, rm.Content);
}
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_MatchingValues(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
}
#nullable enable
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_Set_FetchOptions(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
var fetchme = new Dictionary<string, object?>();
fetchme.Add("hic", null);
fetchme.Add("sunt", 4444);
fetchme.Add("dracones", new List<string>());
rm.Options.Set(FetchOptions, fetchme);
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
rm.Options.TryGetValue(FetchOptions, out IDictionary<string, object?>? fetchOptionsValue);
Assert.NotNull(fetchOptionsValue);
if (fetchOptionsValue != null)
{
foreach (var item in fetchOptionsValue)
{
Assert.True(fetchme.ContainsKey(item.Key));
}
}
}
#nullable disable
#nullable enable
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_NotSet_FetchOptions(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
rm.Options.TryGetValue(FetchOptions, out IDictionary<string, object?>? fetchOptionsValue);
Assert.Null(fetchOptionsValue);
}
#nullable disable
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_Set_EnableStreamingResponse(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
rm.Options.Set(EnableStreamingResponse, true);
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
rm.Options.TryGetValue(EnableStreamingResponse, out bool streamingEnabledValue);
Assert.True(streamingEnabledValue);
}
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_NotSet_EnableStreamingResponse(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
rm.Options.TryGetValue(EnableStreamingResponse, out bool streamingEnabledValue);
Assert.False(streamingEnabledValue);
}
[Fact]
public void Version_SetToNull_ThrowsArgumentNullException()
{
var rm = new HttpRequestMessage();
Assert.Throws<ArgumentNullException>(() => { rm.Version = null; });
}
[Fact]
public void Method_SetToNull_ThrowsArgumentNullException()
{
var rm = new HttpRequestMessage();
Assert.Throws<ArgumentNullException>(() => { rm.Method = null; });
}
[Fact]
public void ToString_DefaultInstance_DumpAllFields()
{
var rm = new HttpRequestMessage();
string expected =
"Method: GET, RequestUri: '<null>', Version: " +
_expectedRequestMessageVersion.ToString(2) +
$", Content: <null>, Headers:{Environment.NewLine}{{{Environment.NewLine}}}";
Assert.Equal(expected, rm.ToString());
}
[Theory]
[InlineData("http://a.com/")]
[InlineData("blob:http://a.com/")]
public void ToString_NonDefaultInstanceWithNoCustomHeaders_DumpAllFields(string uriData)
{
var rm = new HttpRequestMessage();
rm.Method = HttpMethod.Put;
rm.RequestUri = new Uri(uriData);
rm.Version = new Version(1, 0);
rm.Content = new StringContent("content");
// Note that there is no Content-Length header: The reason is that the value for Content-Length header
// doesn't get set by StringContent..ctor, but only if someone actually accesses the ContentLength property.
Assert.Equal(
$"Method: PUT, RequestUri: '{uriData}', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:" + Environment.NewLine +
$"{{{Environment.NewLine}" +
" Content-Type: text/plain; charset=utf-8" + Environment.NewLine +
"}", rm.ToString());
}
[Theory]
[InlineData("http://a.com/")]
[InlineData("blob:http://a.com/")]
public void ToString_NonDefaultInstanceWithCustomHeaders_DumpAllFields(string uriData)
{
var rm = new HttpRequestMessage();
rm.Method = HttpMethod.Put;
rm.RequestUri = new Uri(uriData);
rm.Version = new Version(1, 0);
rm.Content = new StringContent("content");
rm.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain", 0.2));
rm.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml", 0.1));
rm.Headers.Add("Custom-Request-Header", "value1");
rm.Content.Headers.Add("Custom-Content-Header", "value2");
Assert.Equal(
$"Method: PUT, RequestUri: '{uriData}', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:" + Environment.NewLine +
"{" + Environment.NewLine +
" Accept: text/plain; q=0.2" + Environment.NewLine +
" Accept: text/xml; q=0.1" + Environment.NewLine +
" Custom-Request-Header: value1" + Environment.NewLine +
" Content-Type: text/plain; charset=utf-8" + Environment.NewLine +
" Custom-Content-Header: value2" + Environment.NewLine +
"}", rm.ToString());
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBrowserDomSupported))]
public async Task BlobUri_Marshal_CorrectValues_Browser()
{
Runtime.InvokeJS(@"
function typedArrayToURL(typedArray, mimeType) {
return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
}
const bytes = new Uint8Array(59);
for(let i = 0; i < 59; i++) {
bytes[i] = 32 + i;
}
const url = typedArrayToURL(bytes, 'text/plain');
// Calls method with string that will be marshaled as valid URI
App.call_test_method (""InvokeString"", [ url ]);
");
var client = new HttpClient ();
Assert.StartsWith ("blob:", HelperMarshal._stringResource);
HttpRequestMessage rm = new HttpRequestMessage(HttpMethod.Get, new Uri (HelperMarshal._stringResource));
HttpResponseMessage resp = await client.SendAsync (rm);
Assert.NotNull (resp.Content);
string content = await resp.Content.ReadAsStringAsync();
Assert.Equal (59, content.Length);
}
[Fact]
public void BlobStringUri_Marshal_CorrectValues()
{
Runtime.InvokeJS(@"
function typedArrayToURL(typedArray, mimeType) {
// URL.createObjectURL does not work outside of browser but since this was actual
// test code from https://developer.mozilla.org/en-US/docs/Web/API/Blob
// left it in to show what this should do if the test code were to actually run
//return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
return 'blob:https://mdn.mozillademos.org/ca45b575-6348-4d3e-908a-3dbf3d146ea7';
}
const bytes = new Uint8Array(59);
for(let i = 0; i < 59; i++) {
bytes[i] = 32 + i;
}
const url = typedArrayToURL(bytes, 'text/plain');
// Calls method with string that will be converted to a valid Uri
// within the method
App.call_test_method (""SetBlobUrl"", [ url ]);
");
var rm = new HttpRequestMessage(HttpMethod.Post, HelperMarshal._blobURL);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(new Uri("blob:https://mdn.mozillademos.org/ca45b575-6348-4d3e-908a-3dbf3d146ea7"), rm.RequestUri);
}
[Fact]
public void BlobUri_Marshal_CorrectValues()
{
Runtime.InvokeJS(@"
function typedArrayToURL(typedArray, mimeType) {
// URL.createObjectURL does not work outside of browser but since this was actual
// test code from https://developer.mozilla.org/en-US/docs/Web/API/Blob
// left it in to show what this should do if the test code were to actually run
//return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
return 'blob:https://mdn.mozillademos.org/ca45b575-6348-4d3e-908a-3dbf3d146ea7';
}
const bytes = new Uint8Array(59);
for(let i = 0; i < 59; i++) {
bytes[i] = 32 + i;
}
const url = typedArrayToURL(bytes, 'text/plain');
// Calls method with string that will be marshaled as valid URI
App.call_test_method (""SetBlobAsUri"", [ url ]);
");
var rm = new HttpRequestMessage(HttpMethod.Post, HelperMarshal._blobURI);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(new Uri("blob:https://mdn.mozillademos.org/ca45b575-6348-4d3e-908a-3dbf3d146ea7"), rm.RequestUri);
}
#region Helper methods
private class MockContent : HttpContent
{
public bool IsDisposed { get; private set; }
protected override bool TryComputeLength(out long length)
{
throw new NotImplementedException();
}
#nullable enable
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context)
{
#nullable disable
throw new NotImplementedException();
}
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;
using System.Runtime.InteropServices.JavaScript.Tests;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Runtime.InteropServices.JavaScript.Http.Tests
{
public class HttpRequestMessageTest
{
private readonly Version _expectedRequestMessageVersion = HttpVersion.Version11;
private HttpRequestOptionsKey<bool> EnableStreamingResponse = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse");
#nullable enable
private HttpRequestOptionsKey<IDictionary<string, object?>> FetchOptions = new HttpRequestOptionsKey<IDictionary<string, object?>>("WebAssemblyFetchOptions");
#nullable disable
[Fact]
public void Ctor_Default_CorrectDefaults()
{
var rm = new HttpRequestMessage();
Assert.Equal(HttpMethod.Get, rm.Method);
Assert.Null(rm.Content);
Assert.Null(rm.RequestUri);
}
[Fact]
public void Ctor_RelativeStringUri_CorrectValues()
{
var rm = new HttpRequestMessage(HttpMethod.Post, "/relative");
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(new Uri("/relative", UriKind.Relative), rm.RequestUri);
}
[Theory]
[InlineData("http://host/absolute/")]
[InlineData("blob:http://host/absolute/")]
[InlineData("foo://host/absolute")]
public void Ctor_AbsoluteStringUri_CorrectValues(string uri)
{
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(new Uri(uri), rm.RequestUri);
}
[Fact]
public void Ctor_NullStringUri_Accepted()
{
var rm = new HttpRequestMessage(HttpMethod.Put, (string)null);
Assert.Null(rm.RequestUri);
Assert.Equal(HttpMethod.Put, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
}
[Fact]
public void Ctor_RelativeUri_CorrectValues()
{
var uri = new Uri("/relative", UriKind.Relative);
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(uri, rm.RequestUri);
}
[Theory]
[InlineData("http://host/absolute/")]
[InlineData("blob:http://host/absolute/")]
[InlineData("foo://host/absolute")]
public void Ctor_AbsoluteUri_CorrectValues(string uriData)
{
var uri = new Uri(uriData);
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(uri, rm.RequestUri);
}
[Fact]
public void Ctor_NullUri_Accepted()
{
var rm = new HttpRequestMessage(HttpMethod.Put, (Uri)null);
Assert.Null(rm.RequestUri);
Assert.Equal(HttpMethod.Put, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
}
[Theory]
[InlineData("http://example.com")]
[InlineData("blob:http://example.com")]
public void Ctor_NullMethod_ThrowsArgumentNullException(string uriData)
{
Assert.Throws<ArgumentNullException>(() => new HttpRequestMessage(null, uriData));
}
[Theory]
[InlineData("http://example.com")]
[InlineData("blob:http://example.com")]
public void Dispose_DisposeObject_ContentGetsDisposedAndSettersWillThrowButGettersStillWork(string uriData)
{
var rm = new HttpRequestMessage(HttpMethod.Get, uriData);
var content = new MockContent();
rm.Content = content;
Assert.False(content.IsDisposed);
rm.Dispose();
rm.Dispose(); // Multiple calls don't throw.
Assert.True(content.IsDisposed);
Assert.Throws<ObjectDisposedException>(() => { rm.Method = HttpMethod.Put; });
Assert.Throws<ObjectDisposedException>(() => { rm.RequestUri = null; });
Assert.Throws<ObjectDisposedException>(() => { rm.Version = new Version(1, 0); });
Assert.Throws<ObjectDisposedException>(() => { rm.Content = null; });
// Property getters should still work after disposing.
Assert.Equal(HttpMethod.Get, rm.Method);
Assert.Equal(new Uri(uriData), rm.RequestUri);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(content, rm.Content);
}
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_MatchingValues(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
}
#nullable enable
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_Set_FetchOptions(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
var fetchme = new Dictionary<string, object?>();
fetchme.Add("hic", null);
fetchme.Add("sunt", 4444);
fetchme.Add("dracones", new List<string>());
rm.Options.Set(FetchOptions, fetchme);
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
rm.Options.TryGetValue(FetchOptions, out IDictionary<string, object?>? fetchOptionsValue);
Assert.NotNull(fetchOptionsValue);
if (fetchOptionsValue != null)
{
foreach (var item in fetchOptionsValue)
{
Assert.True(fetchme.ContainsKey(item.Key));
}
}
}
#nullable disable
#nullable enable
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_NotSet_FetchOptions(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
rm.Options.TryGetValue(FetchOptions, out IDictionary<string, object?>? fetchOptionsValue);
Assert.Null(fetchOptionsValue);
}
#nullable disable
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_Set_EnableStreamingResponse(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
rm.Options.Set(EnableStreamingResponse, true);
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
rm.Options.TryGetValue(EnableStreamingResponse, out bool streamingEnabledValue);
Assert.True(streamingEnabledValue);
}
[Theory]
[InlineData("https://example.com")]
[InlineData("blob:https://example.com")]
public void Properties_SetOptionsAndGetTheirValue_NotSet_EnableStreamingResponse(string uriData)
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri(uriData);
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Options);
rm.Options.TryGetValue(EnableStreamingResponse, out bool streamingEnabledValue);
Assert.False(streamingEnabledValue);
}
[Fact]
public void Version_SetToNull_ThrowsArgumentNullException()
{
var rm = new HttpRequestMessage();
Assert.Throws<ArgumentNullException>(() => { rm.Version = null; });
}
[Fact]
public void Method_SetToNull_ThrowsArgumentNullException()
{
var rm = new HttpRequestMessage();
Assert.Throws<ArgumentNullException>(() => { rm.Method = null; });
}
[Fact]
public void ToString_DefaultInstance_DumpAllFields()
{
var rm = new HttpRequestMessage();
string expected =
"Method: GET, RequestUri: '<null>', Version: " +
_expectedRequestMessageVersion.ToString(2) +
$", Content: <null>, Headers:{Environment.NewLine}{{{Environment.NewLine}}}";
Assert.Equal(expected, rm.ToString());
}
[Theory]
[InlineData("http://a.com/")]
[InlineData("blob:http://a.com/")]
public void ToString_NonDefaultInstanceWithNoCustomHeaders_DumpAllFields(string uriData)
{
var rm = new HttpRequestMessage();
rm.Method = HttpMethod.Put;
rm.RequestUri = new Uri(uriData);
rm.Version = new Version(1, 0);
rm.Content = new StringContent("content");
// Note that there is no Content-Length header: The reason is that the value for Content-Length header
// doesn't get set by StringContent..ctor, but only if someone actually accesses the ContentLength property.
Assert.Equal(
$"Method: PUT, RequestUri: '{uriData}', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:" + Environment.NewLine +
$"{{{Environment.NewLine}" +
" Content-Type: text/plain; charset=utf-8" + Environment.NewLine +
"}", rm.ToString());
}
[Theory]
[InlineData("http://a.com/")]
[InlineData("blob:http://a.com/")]
public void ToString_NonDefaultInstanceWithCustomHeaders_DumpAllFields(string uriData)
{
var rm = new HttpRequestMessage();
rm.Method = HttpMethod.Put;
rm.RequestUri = new Uri(uriData);
rm.Version = new Version(1, 0);
rm.Content = new StringContent("content");
rm.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain", 0.2));
rm.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml", 0.1));
rm.Headers.Add("Custom-Request-Header", "value1");
rm.Content.Headers.Add("Custom-Content-Header", "value2");
Assert.Equal(
$"Method: PUT, RequestUri: '{uriData}', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:" + Environment.NewLine +
"{" + Environment.NewLine +
" Accept: text/plain; q=0.2" + Environment.NewLine +
" Accept: text/xml; q=0.1" + Environment.NewLine +
" Custom-Request-Header: value1" + Environment.NewLine +
" Content-Type: text/plain; charset=utf-8" + Environment.NewLine +
" Custom-Content-Header: value2" + Environment.NewLine +
"}", rm.ToString());
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBrowserDomSupported))]
public async Task BlobUri_Marshal_CorrectValues_Browser()
{
Runtime.InvokeJS(@"
function typedArrayToURL(typedArray, mimeType) {
return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
}
const bytes = new Uint8Array(59);
for(let i = 0; i < 59; i++) {
bytes[i] = 32 + i;
}
const url = typedArrayToURL(bytes, 'text/plain');
// Calls method with string that will be marshaled as valid URI
App.call_test_method (""InvokeString"", [ url ]);
");
var client = new HttpClient ();
Assert.StartsWith ("blob:", HelperMarshal._stringResource);
HttpRequestMessage rm = new HttpRequestMessage(HttpMethod.Get, new Uri (HelperMarshal._stringResource));
HttpResponseMessage resp = await client.SendAsync (rm);
Assert.NotNull (resp.Content);
string content = await resp.Content.ReadAsStringAsync();
Assert.Equal (59, content.Length);
}
[Fact]
public void BlobStringUri_Marshal_CorrectValues()
{
Runtime.InvokeJS(@"
function typedArrayToURL(typedArray, mimeType) {
// URL.createObjectURL does not work outside of browser but since this was actual
// test code from https://developer.mozilla.org/en-US/docs/Web/API/Blob
// left it in to show what this should do if the test code were to actually run
//return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
return 'blob:https://mdn.mozillademos.org/ca45b575-6348-4d3e-908a-3dbf3d146ea7';
}
const bytes = new Uint8Array(59);
for(let i = 0; i < 59; i++) {
bytes[i] = 32 + i;
}
const url = typedArrayToURL(bytes, 'text/plain');
// Calls method with string that will be converted to a valid Uri
// within the method
App.call_test_method (""SetBlobUrl"", [ url ]);
");
var rm = new HttpRequestMessage(HttpMethod.Post, HelperMarshal._blobURL);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(new Uri("blob:https://mdn.mozillademos.org/ca45b575-6348-4d3e-908a-3dbf3d146ea7"), rm.RequestUri);
}
[Fact]
public void BlobUri_Marshal_CorrectValues()
{
Runtime.InvokeJS(@"
function typedArrayToURL(typedArray, mimeType) {
// URL.createObjectURL does not work outside of browser but since this was actual
// test code from https://developer.mozilla.org/en-US/docs/Web/API/Blob
// left it in to show what this should do if the test code were to actually run
//return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
return 'blob:https://mdn.mozillademos.org/ca45b575-6348-4d3e-908a-3dbf3d146ea7';
}
const bytes = new Uint8Array(59);
for(let i = 0; i < 59; i++) {
bytes[i] = 32 + i;
}
const url = typedArrayToURL(bytes, 'text/plain');
// Calls method with string that will be marshaled as valid URI
App.call_test_method (""SetBlobAsUri"", [ url ]);
");
var rm = new HttpRequestMessage(HttpMethod.Post, HelperMarshal._blobURI);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Null(rm.Content);
Assert.Equal(new Uri("blob:https://mdn.mozillademos.org/ca45b575-6348-4d3e-908a-3dbf3d146ea7"), rm.RequestUri);
}
#region Helper methods
private class MockContent : HttpContent
{
public bool IsDisposed { get; private set; }
protected override bool TryComputeLength(out long length)
{
throw new NotImplementedException();
}
#nullable enable
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context)
{
#nullable disable
throw new NotImplementedException();
}
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/coreclr/System.Private.CoreLib/src/System/Diagnostics/EditAndContinueHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=============================================================================
**
**
**
** Purpose: Helper for EditAndContinue
**
**
=============================================================================*/
namespace System.Diagnostics
{
internal sealed class EditAndContinueHelper
{
#pragma warning disable CA1823, 169, 414 // field is not used from managed.
private object? _objectReference;
#pragma warning restore CA1823, 169, 414
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=============================================================================
**
**
**
** Purpose: Helper for EditAndContinue
**
**
=============================================================================*/
namespace System.Diagnostics
{
internal sealed class EditAndContinueHelper
{
#pragma warning disable CA1823, 169, 414 // field is not used from managed.
private object? _objectReference;
#pragma warning restore CA1823, 169, 414
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/General/Vector256/ConvertToInt32.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 ConvertToInt32Single()
{
var test = new VectorUnaryOpTest__ConvertToInt32Single();
// 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__ConvertToInt32Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(VectorUnaryOpTest__ConvertToInt32Single testClass)
{
var result = Vector256.ConvertToInt32(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector256<Single> _clsVar1;
private Vector256<Single> _fld1;
private DataTable _dataTable;
static VectorUnaryOpTest__ConvertToInt32Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public VectorUnaryOpTest__ConvertToInt32Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.ConvertToInt32(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.ConvertToInt32), new Type[] {
typeof(Vector256<Single>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.ConvertToInt32), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int32));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.ConvertToInt32(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var result = Vector256.ConvertToInt32(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__ConvertToInt32Single();
var result = Vector256.ConvertToInt32(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.ConvertToInt32(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.ConvertToInt32(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (int)(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (int)(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.ConvertToInt32)}<Int32>(Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void ConvertToInt32Single()
{
var test = new VectorUnaryOpTest__ConvertToInt32Single();
// 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__ConvertToInt32Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(VectorUnaryOpTest__ConvertToInt32Single testClass)
{
var result = Vector256.ConvertToInt32(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector256<Single> _clsVar1;
private Vector256<Single> _fld1;
private DataTable _dataTable;
static VectorUnaryOpTest__ConvertToInt32Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public VectorUnaryOpTest__ConvertToInt32Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.ConvertToInt32(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.ConvertToInt32), new Type[] {
typeof(Vector256<Single>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.ConvertToInt32), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int32));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.ConvertToInt32(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var result = Vector256.ConvertToInt32(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__ConvertToInt32Single();
var result = Vector256.ConvertToInt32(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.ConvertToInt32(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.ConvertToInt32(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (int)(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (int)(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.ConvertToInt32)}<Int32>(Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/installer/tests/Assets/TestProjects/ComponentWithNoDependencies/Component.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 Component
{
public class Component
{
private static int componentCallCount = 0;
private static int entryPoint1CallCount = 0;
private static int entryPoint2CallCount = 0;
private static int unmanagedEntryPoint1CallCount = 0;
private static void PrintComponentCallLog(string name, IntPtr arg, int size)
{
Console.WriteLine($"Called {name}(0x{arg.ToString("x")}, {size}) - component call count: {componentCallCount}");
}
public static int ComponentEntryPoint1(IntPtr arg, int size)
{
componentCallCount++;
entryPoint1CallCount++;
PrintComponentCallLog(nameof(ComponentEntryPoint1), arg, size);
return entryPoint1CallCount;
}
public static int ComponentEntryPoint2(IntPtr arg, int size)
{
componentCallCount++;
entryPoint2CallCount++;
PrintComponentCallLog(nameof(ComponentEntryPoint2), arg, size);
return entryPoint2CallCount;
}
public static int ThrowException(IntPtr arg, int size)
{
componentCallCount++;
PrintComponentCallLog(nameof(ThrowException), arg, size);
throw new InvalidOperationException(nameof(ThrowException));
}
[UnmanagedCallersOnly]
public static int UnmanagedComponentEntryPoint1(IntPtr arg, int size)
{
componentCallCount++;
unmanagedEntryPoint1CallCount++;
PrintComponentCallLog(nameof(UnmanagedComponentEntryPoint1), arg, size);
return unmanagedEntryPoint1CallCount;
}
}
}
| // 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 Component
{
public class Component
{
private static int componentCallCount = 0;
private static int entryPoint1CallCount = 0;
private static int entryPoint2CallCount = 0;
private static int unmanagedEntryPoint1CallCount = 0;
private static void PrintComponentCallLog(string name, IntPtr arg, int size)
{
Console.WriteLine($"Called {name}(0x{arg.ToString("x")}, {size}) - component call count: {componentCallCount}");
}
public static int ComponentEntryPoint1(IntPtr arg, int size)
{
componentCallCount++;
entryPoint1CallCount++;
PrintComponentCallLog(nameof(ComponentEntryPoint1), arg, size);
return entryPoint1CallCount;
}
public static int ComponentEntryPoint2(IntPtr arg, int size)
{
componentCallCount++;
entryPoint2CallCount++;
PrintComponentCallLog(nameof(ComponentEntryPoint2), arg, size);
return entryPoint2CallCount;
}
public static int ThrowException(IntPtr arg, int size)
{
componentCallCount++;
PrintComponentCallLog(nameof(ThrowException), arg, size);
throw new InvalidOperationException(nameof(ThrowException));
}
[UnmanagedCallersOnly]
public static int UnmanagedComponentEntryPoint1(IntPtr arg, int size)
{
componentCallCount++;
unmanagedEntryPoint1CallCount++;
PrintComponentCallLog(nameof(UnmanagedComponentEntryPoint1), arg, size);
return unmanagedEntryPoint1CallCount;
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/Common/src/Interop/OSX/Interop.libc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class @libc
{
[StructLayout(LayoutKind.Sequential)]
internal struct AttrList
{
public ushort bitmapCount;
public ushort reserved;
public uint commonAttr;
public uint volAttr;
public uint dirAttr;
public uint fileAttr;
public uint forkAttr;
public const ushort ATTR_BIT_MAP_COUNT = 5;
public const uint ATTR_CMN_CRTIME = 0x00000200;
}
[GeneratedDllImport(Libraries.libc, EntryPoint = "setattrlist", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)]
internal static unsafe partial int setattrlist(string path, AttrList* attrList, void* attrBuf, nint attrBufSize, CULong options);
internal const uint FSOPT_NOFOLLOW = 0x00000001;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class @libc
{
[StructLayout(LayoutKind.Sequential)]
internal struct AttrList
{
public ushort bitmapCount;
public ushort reserved;
public uint commonAttr;
public uint volAttr;
public uint dirAttr;
public uint fileAttr;
public uint forkAttr;
public const ushort ATTR_BIT_MAP_COUNT = 5;
public const uint ATTR_CMN_CRTIME = 0x00000200;
}
[GeneratedDllImport(Libraries.libc, EntryPoint = "setattrlist", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)]
internal static unsafe partial int setattrlist(string path, AttrList* attrList, void* attrBuf, nint attrBufSize, CULong options);
internal const uint FSOPT_NOFOLLOW = 0x00000001;
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/Common/src/System/Collections/Generic/BidirectionalDictionary.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;
namespace System.Collections.Generic
{
internal sealed class BidirectionalDictionary<T1, T2> : IEnumerable<KeyValuePair<T1, T2>>
where T1 : notnull
where T2 : notnull
{
private readonly Dictionary<T1, T2> _forward;
private readonly Dictionary<T2, T1> _backward;
public BidirectionalDictionary(int capacity)
{
_forward = new Dictionary<T1, T2>(capacity);
_backward = new Dictionary<T2, T1>(capacity);
}
public int Count
{
get
{
Debug.Assert(_forward.Count == _backward.Count, "both the dictionaries must have the same number of elements");
return _forward.Count;
}
}
public void Add(T1 item1, T2 item2)
{
Debug.Assert(!_backward.ContainsKey(item2), "No added item1 should ever have existing item2");
_forward.Add(item1, item2);
_backward.Add(item2, item1);
}
public bool TryGetForward(T1 item1, [MaybeNullWhen(false)] out T2 item2)
{
return _forward.TryGetValue(item1, out item2);
}
public bool TryGetBackward(T2 item2, [MaybeNullWhen(false)] out T1 item1)
{
return _backward.TryGetValue(item2, out item1);
}
public Dictionary<T1, T2>.Enumerator GetEnumerator()
{
return _forward.GetEnumerator();
}
IEnumerator<KeyValuePair<T1, T2>> IEnumerable<KeyValuePair<T1, T2>>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| // 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;
namespace System.Collections.Generic
{
internal sealed class BidirectionalDictionary<T1, T2> : IEnumerable<KeyValuePair<T1, T2>>
where T1 : notnull
where T2 : notnull
{
private readonly Dictionary<T1, T2> _forward;
private readonly Dictionary<T2, T1> _backward;
public BidirectionalDictionary(int capacity)
{
_forward = new Dictionary<T1, T2>(capacity);
_backward = new Dictionary<T2, T1>(capacity);
}
public int Count
{
get
{
Debug.Assert(_forward.Count == _backward.Count, "both the dictionaries must have the same number of elements");
return _forward.Count;
}
}
public void Add(T1 item1, T2 item2)
{
Debug.Assert(!_backward.ContainsKey(item2), "No added item1 should ever have existing item2");
_forward.Add(item1, item2);
_backward.Add(item2, item1);
}
public bool TryGetForward(T1 item1, [MaybeNullWhen(false)] out T2 item2)
{
return _forward.TryGetValue(item1, out item2);
}
public bool TryGetBackward(T2 item2, [MaybeNullWhen(false)] out T1 item1)
{
return _backward.TryGetValue(item2, out item1);
}
public Dictionary<T1, T2>.Enumerator GetEnumerator()
{
return _forward.GetEnumerator();
}
IEnumerator<KeyValuePair<T1, T2>> IEnumerable<KeyValuePair<T1, T2>>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.Xml/tests/XmlReaderLib/CGenericTestModule.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;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
////////////////////////////////////////////////////////////////
// All test module cases should inherit from CUniTestModule
// Encapsulates the notion of a "Backend" which each test
// needs to respect
//
////////////////////////////////////////////////////////////////
public class CGenericTestModule : CTestModule
{
public CGenericTestModule()
: base()
{
}
private string _TestData = null;
public string TestData
{
get
{
return _TestData;
}
}
private string _standardpath = null;
public string StandardPath
{
get
{
return _standardpath;
}
}
private ReaderFactory _ReaderFactory = null;
public ReaderFactory ReaderFactory
{
get
{
return _ReaderFactory;
}
set
{
_ReaderFactory = value;
}
}
private DateTime _StartTime;
public override int Init(object objParam)
{
_TestData = Path.Combine(FilePathUtil.GetTestDataPath(), @"XmlReader");
_TestData = _TestData.ToLowerInvariant();
_standardpath = FilePathUtil.GetStandardPath();
_standardpath = _standardpath.ToLowerInvariant();
int ret = base.Init(objParam);
_StartTime = DateTime.Now;
return ret;
}
public override int Terminate(object objParam)
{
CError.WriteLine("Total running time = {0}", DateTime.Now - _StartTime);
base.Terminate(objParam);
return TEST_PASS;
}
}
////////////////////////////////////////////////////////////////
// TestCase
//
////////////////////////////////////////////////////////////////
public class CGenericTestCase : CTestCase
{
public CGenericTestCase()
: base()
{
}
public string TestData
{
get
{
return TestModule.TestData;
}
}
public string StandardPath
{
get
{
return TestModule.StandardPath;
}
}
public virtual new CGenericTestModule TestModule
{
get { return (CGenericTestModule)base.TestModule; }
set { base.TestModule = value; }
}
}
////////////////////////////////////////////////////////////////
// InheritRequired attribute
//
// This attribute is used to mark test case classes (TCxxx). A check
// is performed at startup to ensure that each InheritRequired class
// actually has at least one derived class
// The attribute is applied to all classes that require implementation
// for both XmlxxxReader and XmlValidatingReader and its only purpose is
// to avoid to forgot implementation of some test in one or both
// of the suites (Reader and ValidatingReader)
////////////////////////////////////////////////////////////////
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class InheritRequired : Attribute
{
}
////////////////////////////////////////////////////////////////
// Common interface for creating different readers in derived
// modules
////////////////////////////////////////////////////////////////
public abstract class ReaderFactory
{
public static string HT_FILENAME = "FILENAME";
public static string HT_VALIDATIONTYPE = "VT";
public static string HT_READERTYPE = "READERTYPE";
public static string HT_STREAM = "STREAM";
public static string HT_CURVAR = "CURVAR";
public static string HT_CURDESC = "CURDESC";
public static string HT_FRAGMENT = "FRAGMENT";
public static string HT_SCHEMASET = "SCHEMASET";
public static string HT_SCHEMACOLLECTION = "SCHEMACOLLECTION";
public static string HT_VALIDATIONHANDLER = "VH";
public static string HT_READERSETTINGS = "READERSETTINGS";
public static string HT_STRINGREADER = "STRINGREADER";
public abstract XmlReader Create(MyDict<string, object> options);
private int _validationErrorCount = 0;
private int _validationWarningCount = 0;
private int _validationCallbackCount = 0;
public int ValidationErrorCount
{
get { return _validationErrorCount; }
set { _validationErrorCount = value; }
}
public int ValidationWarningCount
{
get { return _validationWarningCount; }
set { _validationWarningCount = value; }
}
public int ValidationCallbackCount
{
get { return _validationCallbackCount; }
set { _validationCallbackCount = value; }
}
public virtual void Initialize()
{
//To manage the Factory class.
}
public virtual void Terminate()
{
//To manage the Factory class.
}
}
}
| // 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;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
////////////////////////////////////////////////////////////////
// All test module cases should inherit from CUniTestModule
// Encapsulates the notion of a "Backend" which each test
// needs to respect
//
////////////////////////////////////////////////////////////////
public class CGenericTestModule : CTestModule
{
public CGenericTestModule()
: base()
{
}
private string _TestData = null;
public string TestData
{
get
{
return _TestData;
}
}
private string _standardpath = null;
public string StandardPath
{
get
{
return _standardpath;
}
}
private ReaderFactory _ReaderFactory = null;
public ReaderFactory ReaderFactory
{
get
{
return _ReaderFactory;
}
set
{
_ReaderFactory = value;
}
}
private DateTime _StartTime;
public override int Init(object objParam)
{
_TestData = Path.Combine(FilePathUtil.GetTestDataPath(), @"XmlReader");
_TestData = _TestData.ToLowerInvariant();
_standardpath = FilePathUtil.GetStandardPath();
_standardpath = _standardpath.ToLowerInvariant();
int ret = base.Init(objParam);
_StartTime = DateTime.Now;
return ret;
}
public override int Terminate(object objParam)
{
CError.WriteLine("Total running time = {0}", DateTime.Now - _StartTime);
base.Terminate(objParam);
return TEST_PASS;
}
}
////////////////////////////////////////////////////////////////
// TestCase
//
////////////////////////////////////////////////////////////////
public class CGenericTestCase : CTestCase
{
public CGenericTestCase()
: base()
{
}
public string TestData
{
get
{
return TestModule.TestData;
}
}
public string StandardPath
{
get
{
return TestModule.StandardPath;
}
}
public virtual new CGenericTestModule TestModule
{
get { return (CGenericTestModule)base.TestModule; }
set { base.TestModule = value; }
}
}
////////////////////////////////////////////////////////////////
// InheritRequired attribute
//
// This attribute is used to mark test case classes (TCxxx). A check
// is performed at startup to ensure that each InheritRequired class
// actually has at least one derived class
// The attribute is applied to all classes that require implementation
// for both XmlxxxReader and XmlValidatingReader and its only purpose is
// to avoid to forgot implementation of some test in one or both
// of the suites (Reader and ValidatingReader)
////////////////////////////////////////////////////////////////
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class InheritRequired : Attribute
{
}
////////////////////////////////////////////////////////////////
// Common interface for creating different readers in derived
// modules
////////////////////////////////////////////////////////////////
public abstract class ReaderFactory
{
public static string HT_FILENAME = "FILENAME";
public static string HT_VALIDATIONTYPE = "VT";
public static string HT_READERTYPE = "READERTYPE";
public static string HT_STREAM = "STREAM";
public static string HT_CURVAR = "CURVAR";
public static string HT_CURDESC = "CURDESC";
public static string HT_FRAGMENT = "FRAGMENT";
public static string HT_SCHEMASET = "SCHEMASET";
public static string HT_SCHEMACOLLECTION = "SCHEMACOLLECTION";
public static string HT_VALIDATIONHANDLER = "VH";
public static string HT_READERSETTINGS = "READERSETTINGS";
public static string HT_STRINGREADER = "STRINGREADER";
public abstract XmlReader Create(MyDict<string, object> options);
private int _validationErrorCount = 0;
private int _validationWarningCount = 0;
private int _validationCallbackCount = 0;
public int ValidationErrorCount
{
get { return _validationErrorCount; }
set { _validationErrorCount = value; }
}
public int ValidationWarningCount
{
get { return _validationWarningCount; }
set { _validationWarningCount = value; }
}
public int ValidationCallbackCount
{
get { return _validationCallbackCount; }
set { _validationCallbackCount = value; }
}
public virtual void Initialize()
{
//To manage the Factory class.
}
public virtual void Terminate()
{
//To manage the Factory class.
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Diagnostics.Process/src/Microsoft/Win32/SafeHandles/SafeProcessHandle.Unix.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
** Class: SafeProcessHandle
**
** A wrapper for a process handle
**
**
===========================================================*/
using System;
using System.Diagnostics;
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// On Windows, SafeProcessHandle represents the actual OS handle for the process.
// On Unix, there's no such concept. Instead, the implementation manufactures
// a WaitHandle that it manually sets when the process completes; SafeProcessHandle
// then just wraps that same WaitHandle instance. This allows consumers that use
// Process.{Safe}Handle to initalize and use a WaitHandle to successfully use it on
// Unix as well to wait for the process to complete.
private readonly SafeWaitHandle? _handle;
private readonly bool _releaseRef;
internal SafeProcessHandle(int processId, SafeWaitHandle handle) :
this(handle.DangerousGetHandle(), ownsHandle: true)
{
ProcessId = processId;
_handle = handle;
handle.DangerousAddRef(ref _releaseRef);
}
internal int ProcessId { get; }
protected override bool ReleaseHandle()
{
if (_releaseRef)
{
Debug.Assert(_handle != null);
_handle.DangerousRelease();
}
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
** Class: SafeProcessHandle
**
** A wrapper for a process handle
**
**
===========================================================*/
using System;
using System.Diagnostics;
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// On Windows, SafeProcessHandle represents the actual OS handle for the process.
// On Unix, there's no such concept. Instead, the implementation manufactures
// a WaitHandle that it manually sets when the process completes; SafeProcessHandle
// then just wraps that same WaitHandle instance. This allows consumers that use
// Process.{Safe}Handle to initalize and use a WaitHandle to successfully use it on
// Unix as well to wait for the process to complete.
private readonly SafeWaitHandle? _handle;
private readonly bool _releaseRef;
internal SafeProcessHandle(int processId, SafeWaitHandle handle) :
this(handle.DangerousGetHandle(), ownsHandle: true)
{
ProcessId = processId;
_handle = handle;
handle.DangerousAddRef(ref _releaseRef);
}
internal int ProcessId { get; }
protected override bool ReleaseHandle()
{
if (_releaseRef)
{
Debug.Assert(_handle != null);
_handle.DangerousRelease();
}
return true;
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/Common/src/Interop/Windows/Kernel32/Interop.LoadLibraryEx.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;
internal static partial class Interop
{
internal static partial class Kernel32
{
public const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
public const int LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800;
[GeneratedDllImport(Libraries.Kernel32, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial SafeLibraryHandle LoadLibraryExW(string lpwLibFileName, IntPtr hFile, uint dwFlags);
}
}
| // 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;
internal static partial class Interop
{
internal static partial class Kernel32
{
public const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
public const int LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800;
[GeneratedDllImport(Libraries.Kernel32, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial SafeLibraryHandle LoadLibraryExW(string lpwLibFileName, IntPtr hFile, uint dwFlags);
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/opt/Devirtualization/constructor.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;
class Test_constructor
{
static string s;
public override string ToString()
{
return "Test";
}
[MethodImpl(MethodImplOptions.NoInlining)]
public Test_constructor()
{
s = ToString(); // cannot be devirtualized
}
static int Main()
{
new Child();
return (s == "Child" ? 100 : 0);
}
}
class Child : Test_constructor
{
[MethodImpl(MethodImplOptions.NoInlining)]
public Child() { }
public override string ToString()
{
return "Child";
}
}
| // 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;
class Test_constructor
{
static string s;
public override string ToString()
{
return "Test";
}
[MethodImpl(MethodImplOptions.NoInlining)]
public Test_constructor()
{
s = ToString(); // cannot be devirtualized
}
static int Main()
{
new Child();
return (s == "Child" ? 100 : 0);
}
}
class Child : Test_constructor
{
[MethodImpl(MethodImplOptions.NoInlining)]
public Child() { }
public override string ToString()
{
return "Child";
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/NetEventSource.Ping.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.Tracing;
namespace System.Net
{
[EventSource(Name = "Private.InternalDiagnostics.System.Net.Ping")]
internal sealed partial class NetEventSource { }
}
| // 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.Tracing;
namespace System.Net
{
[EventSource(Name = "Private.InternalDiagnostics.System.Net.Ping")]
internal sealed partial class NetEventSource { }
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/CodeGenBringUpTests/FPDist.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
public class BringUpTest_FPDist
{
const int Pass = 100;
const int Fail = -1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static float FPDist(float x1, float y1, float x2, float y2)
{
float z = (float) Math.Sqrt((double)((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)));
return z;
}
public static int Main()
{
float y = FPDist(5f, 7f, 2f, 3f);
Console.WriteLine(y);
if (System.Math.Abs(y-5f) <= Single.Epsilon) return Pass;
else return Fail;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
public class BringUpTest_FPDist
{
const int Pass = 100;
const int Fail = -1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static float FPDist(float x1, float y1, float x2, float y2)
{
float z = (float) Math.Sqrt((double)((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)));
return z;
}
public static int Main()
{
float y = FPDist(5f, 7f, 2f, 3f);
Console.WriteLine(y);
if (System.Math.Abs(y-5f) <= Single.Epsilon) return Pass;
else return Fail;
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/Common/src/Interop/Unix/System.Native/Interop.Sync.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
/// <summary>
/// Forces a write of all modified I/O buffers to their storage mediums.
/// </summary>
[GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Sync")]
internal static partial void Sync();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
/// <summary>
/// Forces a write of all modified I/O buffers to their storage mediums.
/// </summary>
[GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Sync")]
internal static partial void Sync();
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/SIMD/Sums.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 Point = System.Numerics.Vector4;
namespace VectorMathTests
{
class Program
{
public const int DefaultSeed = 20010415;
public static int Seed = Environment.GetEnvironmentVariable("CORECLR_SEED") switch
{
string seedStr when seedStr.Equals("random", StringComparison.OrdinalIgnoreCase) => new Random().Next(),
string seedStr when int.TryParse(seedStr, out int envSeed) => envSeed,
_ => DefaultSeed
};
static float NextFloat(Random random)
{
double mantissa = (random.NextDouble() * 2.0) - 1.0;
double exponent = Math.Pow(2.0, random.Next(-32, 32));
return (float)(mantissa * exponent);
}
static float sum(Point[] arr)
{
int n = arr.Length;
Point s = new Point(0);
for (int i = 0; i < n; ++i)
{
arr[i] += new Point(1);
arr[i] *= 2;
arr[i] -= (i == 0) ? new Point(0) : arr[i - 1];
arr[i] += (i == n - 1) ? new Point(0) : arr[i + 1];
s += arr[i];
}
return s.X;
}
static int Main(string[] args)
{
System.Diagnostics.Stopwatch clock = new System.Diagnostics.Stopwatch();
clock.Start();
Random random = new Random(Seed);
int N = 10000;
Point[] arr = new Point[N];
for (int i = 0; i < N; ++i)
{
arr[i].X = NextFloat(random);
arr[i].Y = NextFloat(random);
arr[i].Z = NextFloat(random);
arr[i].W = NextFloat(random);
}
for (int i = 0; i < 1000; ++i)
{
sum(arr);
}
return 100;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Point = System.Numerics.Vector4;
namespace VectorMathTests
{
class Program
{
public const int DefaultSeed = 20010415;
public static int Seed = Environment.GetEnvironmentVariable("CORECLR_SEED") switch
{
string seedStr when seedStr.Equals("random", StringComparison.OrdinalIgnoreCase) => new Random().Next(),
string seedStr when int.TryParse(seedStr, out int envSeed) => envSeed,
_ => DefaultSeed
};
static float NextFloat(Random random)
{
double mantissa = (random.NextDouble() * 2.0) - 1.0;
double exponent = Math.Pow(2.0, random.Next(-32, 32));
return (float)(mantissa * exponent);
}
static float sum(Point[] arr)
{
int n = arr.Length;
Point s = new Point(0);
for (int i = 0; i < n; ++i)
{
arr[i] += new Point(1);
arr[i] *= 2;
arr[i] -= (i == 0) ? new Point(0) : arr[i - 1];
arr[i] += (i == n - 1) ? new Point(0) : arr[i + 1];
s += arr[i];
}
return s.X;
}
static int Main(string[] args)
{
System.Diagnostics.Stopwatch clock = new System.Diagnostics.Stopwatch();
clock.Start();
Random random = new Random(Seed);
int N = 10000;
Point[] arr = new Point[N];
for (int i = 0; i < N; ++i)
{
arr[i].X = NextFloat(random);
arr[i].Y = NextFloat(random);
arr[i].Z = NextFloat(random);
arr[i].W = NextFloat(random);
}
for (int i = 0; i < 1000; ++i)
{
sum(arr);
}
return 100;
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/General/Vector128_1/op_BitwiseAnd.Int16.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_BitwiseAndInt16()
{
var test = new VectorBinaryOpTest__op_BitwiseAndInt16();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__op_BitwiseAndInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__op_BitwiseAndInt16 testClass)
{
var result = _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<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__op_BitwiseAndInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public VectorBinaryOpTest__op_BitwiseAndInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr) & Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector128<Int16>).GetMethod("op_BitwiseAnd", new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 & _clsVar2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = op1 & op2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__op_BitwiseAndInt16();
var result = test._fld1 & test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 & _fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 & test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (short)(left[0] & right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (short)(left[i] & right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_BitwiseAnd<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_BitwiseAndInt16()
{
var test = new VectorBinaryOpTest__op_BitwiseAndInt16();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__op_BitwiseAndInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__op_BitwiseAndInt16 testClass)
{
var result = _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<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__op_BitwiseAndInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public VectorBinaryOpTest__op_BitwiseAndInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr) & Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector128<Int16>).GetMethod("op_BitwiseAnd", new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 & _clsVar2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = op1 & op2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__op_BitwiseAndInt16();
var result = test._fld1 & test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 & _fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 & test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (short)(left[0] & right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (short)(left[i] & right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_BitwiseAnd<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/BuildWasmApps/Wasm.Build.Tests/EnvironmentVariables.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;
#nullable enable
namespace Wasm.Build.Tests
{
internal static class EnvironmentVariables
{
internal static readonly string? SdkForWorkloadTestingPath = Environment.GetEnvironmentVariable("SDK_FOR_WORKLOAD_TESTING_PATH");
internal static readonly string? SdkHasWorkloadInstalled = Environment.GetEnvironmentVariable("SDK_HAS_WORKLOAD_INSTALLED");
internal static readonly string? WorkloadPacksVersion = Environment.GetEnvironmentVariable("WORKLOAD_PACKS_VER");
internal static readonly string? AppRefDir = Environment.GetEnvironmentVariable("AppRefDir");
internal static readonly string? WasmBuildSupportDir = Environment.GetEnvironmentVariable("WasmBuildSupportDir");
internal static readonly string? EMSDK_PATH = Environment.GetEnvironmentVariable("EMSDK_PATH");
internal static readonly string? TestLogPath = Environment.GetEnvironmentVariable("TEST_LOG_PATH");
internal static readonly string? SkipProjectCleanup = Environment.GetEnvironmentVariable("SKIP_PROJECT_CLEANUP");
internal static readonly string? XHarnessCliPath = Environment.GetEnvironmentVariable("XHARNESS_CLI_PATH");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
#nullable enable
namespace Wasm.Build.Tests
{
internal static class EnvironmentVariables
{
internal static readonly string? SdkForWorkloadTestingPath = Environment.GetEnvironmentVariable("SDK_FOR_WORKLOAD_TESTING_PATH");
internal static readonly string? SdkHasWorkloadInstalled = Environment.GetEnvironmentVariable("SDK_HAS_WORKLOAD_INSTALLED");
internal static readonly string? WorkloadPacksVersion = Environment.GetEnvironmentVariable("WORKLOAD_PACKS_VER");
internal static readonly string? AppRefDir = Environment.GetEnvironmentVariable("AppRefDir");
internal static readonly string? WasmBuildSupportDir = Environment.GetEnvironmentVariable("WasmBuildSupportDir");
internal static readonly string? EMSDK_PATH = Environment.GetEnvironmentVariable("EMSDK_PATH");
internal static readonly string? TestLogPath = Environment.GetEnvironmentVariable("TEST_LOG_PATH");
internal static readonly string? SkipProjectCleanup = Environment.GetEnvironmentVariable("SKIP_PROJECT_CLEANUP");
internal static readonly string? XHarnessCliPath = Environment.GetEnvironmentVariable("XHARNESS_CLI_PATH");
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Threading.Tasks.Extensions/ref/System.Threading.Tasks.Extensions.Forwards.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncMethodBuilderAttribute))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder<>))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<>))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.ValueTaskAwaiter))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.ValueTaskAwaiter<>))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.Sources.IValueTaskSource))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.Sources.IValueTaskSource<>))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.Sources.ValueTaskSourceOnCompletedFlags))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.Sources.ValueTaskSourceStatus))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.ValueTask))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.ValueTask<>))]
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncMethodBuilderAttribute))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder<>))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<>))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.ValueTaskAwaiter))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.ValueTaskAwaiter<>))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.Sources.IValueTaskSource))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.Sources.IValueTaskSource<>))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.Sources.ValueTaskSourceOnCompletedFlags))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.Sources.ValueTaskSourceStatus))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.ValueTask))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Tasks.ValueTask<>))]
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.ComponentModel.TypeConverter/tests/Drawing/RectangleConverterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class RectangleConverterTests : StringTypeConverterTestBase<Rectangle>
{
protected override TypeConverter Converter { get; } = new RectangleConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override Rectangle Default => new Rectangle(0, 0, 100, 100);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<Rectangle, Dictionary<string, object>>> CreateInstancePairs {
get
{
yield return Tuple.Create(new Rectangle(10, 10, 20, 30), new Dictionary<string, object>
{
["X"] = 10,
["Y"] = 10,
["Width"] = 20,
["Height"] = 30,
});
yield return Tuple.Create(new Rectangle(-10, -10, 20, 30), new Dictionary<string, object>
{
["X"] = -10,
["Y"] = -10,
["Width"] = 20,
["Height"] = 30,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> RectangleData =>
new[]
{
new object[] {0, 0, 0, 0},
new object[] {1, 1, 1, 1},
new object[] {-1, 1, 1, 1},
new object[] {1, -1, 1, 1},
new object[] {-1, -1, 1, 1},
new object[] {int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue},
new object[] {int.MinValue, int.MaxValue, int.MaxValue, int.MaxValue},
new object[] {int.MaxValue, int.MinValue, int.MaxValue, int.MaxValue},
new object[] {int.MinValue, int.MinValue, int.MaxValue, int.MaxValue},
};
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertFrom(int x, int y, int width, int height)
{
TestConvertFromString(new Rectangle(x, y, width, height), $"{x}, {y}, {width}, {height}");
}
[Theory]
[InlineData("10, 10")]
[InlineData("1, 1, 1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1, 1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(10, 10)},
new object[] {new PointF(10, 10)},
new object[] {new Size(10, 10)},
new object[] {new SizeF(10, 10)},
new object[] {new object()},
new object[] {1001},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertTo(int x, int y, int width, int height)
{
TestConvertToString(new Rectangle(x, y, width, height), $"{x}, {y}, {width}, {height}");
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void CreateInstance_CaseSensitive()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["x"] = -10,
["Y"] = -10,
["Width"] = 20,
["Height"] = 30,
});
});
}
[Fact]
public void TestGetProperties()
{
var rect = new Rectangle(10, 10, 20, 30);
var propsColl = Converter.GetProperties(rect);
Assert.Equal(4, propsColl.Count);
Assert.Equal(rect.X, propsColl["X"].GetValue(rect));
Assert.Equal(rect.Y, propsColl["Y"].GetValue(rect));
Assert.Equal(rect.Width, propsColl["Width"].GetValue(rect));
Assert.Equal(rect.Height, propsColl["Height"].GetValue(rect));
rect = new Rectangle(-10, -10, 20, 30);
propsColl = Converter.GetProperties(null, rect);
Assert.Equal(4, propsColl.Count);
Assert.Equal(rect.X, propsColl["X"].GetValue(rect));
Assert.Equal(rect.Y, propsColl["Y"].GetValue(rect));
Assert.Equal(rect.Width, propsColl["Width"].GetValue(rect));
Assert.Equal(rect.Height, propsColl["Height"].GetValue(rect));
rect = new Rectangle(10, 10, 20, 30);
propsColl = Converter.GetProperties(null, rect, null);
Assert.Equal(11, propsColl.Count);
Assert.Equal(rect.X, propsColl["X"].GetValue(rect));
Assert.Equal(rect.Y, propsColl["Y"].GetValue(rect));
Assert.Equal(rect.Width, propsColl["Width"].GetValue(rect));
Assert.Equal(rect.Height, propsColl["Height"].GetValue(rect));
Assert.Equal(rect.IsEmpty, propsColl["IsEmpty"].GetValue(rect));
Assert.Equal(rect.Top, propsColl["Top"].GetValue(rect));
Assert.Equal(rect.Bottom, propsColl["Bottom"].GetValue(rect));
Assert.Equal(rect.Left, propsColl["Left"].GetValue(rect));
Assert.Equal(rect.Right, propsColl["Right"].GetValue(rect));
Assert.Equal(rect.Location, propsColl["Location"].GetValue(rect));
Assert.Equal(rect.Size, propsColl["Size"].GetValue(rect));
Assert.Equal(rect.IsEmpty, propsColl["IsEmpty"].GetValue(rect));
// Pick an attribute that cannot be applied to properties to make sure everything gets filtered
propsColl = Converter.GetProperties(null, new Rectangle(10, 10, 20, 30), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")});
Assert.Equal(0, propsColl.Count);
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertFromInvariantString(int x, int y, int width, int height)
{
var rect = (Rectangle)Converter.ConvertFromInvariantString($"{x}, {y}, {width}, {height}");
Assert.Equal(x, rect.X);
Assert.Equal(y, rect.Y);
Assert.Equal(width, rect.Width);
Assert.Equal(height, rect.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1, 2, 3");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertFromString(int x, int y, int width, int height)
{
var rect =
(Rectangle)Converter.ConvertFromString(string.Format("{0}{4} {1}{4} {2}{4} {3}", x, y, width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(x, rect.X);
Assert.Equal(y, rect.Y);
Assert.Equal(width, rect.Width);
Assert.Equal(height, rect.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException(string.Format("1{0} 1{0} 1{0} 1{0} 1",
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertToInvariantString(int x, int y, int width, int height)
{
var str = Converter.ConvertToInvariantString(new Rectangle(x, y, width, height));
Assert.Equal($"{x}, {y}, {width}, {height}", str);
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertToString(int x, int y, int width, int height)
{
var str = Converter.ConvertToString(new Rectangle(x, y, width, height));
Assert.Equal(
string.Format("{0}{4} {1}{4} {2}{4} {3}", x, y, width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class RectangleConverterTests : StringTypeConverterTestBase<Rectangle>
{
protected override TypeConverter Converter { get; } = new RectangleConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override Rectangle Default => new Rectangle(0, 0, 100, 100);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<Rectangle, Dictionary<string, object>>> CreateInstancePairs {
get
{
yield return Tuple.Create(new Rectangle(10, 10, 20, 30), new Dictionary<string, object>
{
["X"] = 10,
["Y"] = 10,
["Width"] = 20,
["Height"] = 30,
});
yield return Tuple.Create(new Rectangle(-10, -10, 20, 30), new Dictionary<string, object>
{
["X"] = -10,
["Y"] = -10,
["Width"] = 20,
["Height"] = 30,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> RectangleData =>
new[]
{
new object[] {0, 0, 0, 0},
new object[] {1, 1, 1, 1},
new object[] {-1, 1, 1, 1},
new object[] {1, -1, 1, 1},
new object[] {-1, -1, 1, 1},
new object[] {int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue},
new object[] {int.MinValue, int.MaxValue, int.MaxValue, int.MaxValue},
new object[] {int.MaxValue, int.MinValue, int.MaxValue, int.MaxValue},
new object[] {int.MinValue, int.MinValue, int.MaxValue, int.MaxValue},
};
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertFrom(int x, int y, int width, int height)
{
TestConvertFromString(new Rectangle(x, y, width, height), $"{x}, {y}, {width}, {height}");
}
[Theory]
[InlineData("10, 10")]
[InlineData("1, 1, 1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1, 1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(10, 10)},
new object[] {new PointF(10, 10)},
new object[] {new Size(10, 10)},
new object[] {new SizeF(10, 10)},
new object[] {new object()},
new object[] {1001},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertTo(int x, int y, int width, int height)
{
TestConvertToString(new Rectangle(x, y, width, height), $"{x}, {y}, {width}, {height}");
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void CreateInstance_CaseSensitive()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["x"] = -10,
["Y"] = -10,
["Width"] = 20,
["Height"] = 30,
});
});
}
[Fact]
public void TestGetProperties()
{
var rect = new Rectangle(10, 10, 20, 30);
var propsColl = Converter.GetProperties(rect);
Assert.Equal(4, propsColl.Count);
Assert.Equal(rect.X, propsColl["X"].GetValue(rect));
Assert.Equal(rect.Y, propsColl["Y"].GetValue(rect));
Assert.Equal(rect.Width, propsColl["Width"].GetValue(rect));
Assert.Equal(rect.Height, propsColl["Height"].GetValue(rect));
rect = new Rectangle(-10, -10, 20, 30);
propsColl = Converter.GetProperties(null, rect);
Assert.Equal(4, propsColl.Count);
Assert.Equal(rect.X, propsColl["X"].GetValue(rect));
Assert.Equal(rect.Y, propsColl["Y"].GetValue(rect));
Assert.Equal(rect.Width, propsColl["Width"].GetValue(rect));
Assert.Equal(rect.Height, propsColl["Height"].GetValue(rect));
rect = new Rectangle(10, 10, 20, 30);
propsColl = Converter.GetProperties(null, rect, null);
Assert.Equal(11, propsColl.Count);
Assert.Equal(rect.X, propsColl["X"].GetValue(rect));
Assert.Equal(rect.Y, propsColl["Y"].GetValue(rect));
Assert.Equal(rect.Width, propsColl["Width"].GetValue(rect));
Assert.Equal(rect.Height, propsColl["Height"].GetValue(rect));
Assert.Equal(rect.IsEmpty, propsColl["IsEmpty"].GetValue(rect));
Assert.Equal(rect.Top, propsColl["Top"].GetValue(rect));
Assert.Equal(rect.Bottom, propsColl["Bottom"].GetValue(rect));
Assert.Equal(rect.Left, propsColl["Left"].GetValue(rect));
Assert.Equal(rect.Right, propsColl["Right"].GetValue(rect));
Assert.Equal(rect.Location, propsColl["Location"].GetValue(rect));
Assert.Equal(rect.Size, propsColl["Size"].GetValue(rect));
Assert.Equal(rect.IsEmpty, propsColl["IsEmpty"].GetValue(rect));
// Pick an attribute that cannot be applied to properties to make sure everything gets filtered
propsColl = Converter.GetProperties(null, new Rectangle(10, 10, 20, 30), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")});
Assert.Equal(0, propsColl.Count);
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertFromInvariantString(int x, int y, int width, int height)
{
var rect = (Rectangle)Converter.ConvertFromInvariantString($"{x}, {y}, {width}, {height}");
Assert.Equal(x, rect.X);
Assert.Equal(y, rect.Y);
Assert.Equal(width, rect.Width);
Assert.Equal(height, rect.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1, 2, 3");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertFromString(int x, int y, int width, int height)
{
var rect =
(Rectangle)Converter.ConvertFromString(string.Format("{0}{4} {1}{4} {2}{4} {3}", x, y, width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(x, rect.X);
Assert.Equal(y, rect.Y);
Assert.Equal(width, rect.Width);
Assert.Equal(height, rect.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException(string.Format("1{0} 1{0} 1{0} 1{0} 1",
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertToInvariantString(int x, int y, int width, int height)
{
var str = Converter.ConvertToInvariantString(new Rectangle(x, y, width, height));
Assert.Equal($"{x}, {y}, {width}, {height}", str);
}
[Theory]
[MemberData(nameof(RectangleData))]
public void ConvertToString(int x, int y, int width, int height)
{
var str = Converter.ConvertToString(new Rectangle(x, y, width, height));
Assert.Equal(
string.Format("{0}{4} {1}{4} {2}{4} {3}", x, y, width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.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;
using System.Diagnostics;
namespace System.Collections.Immutable
{
public sealed partial class ImmutableList<T>
{
/// <summary>
/// Enumerates the contents of a binary tree.
/// </summary>
/// <remarks>
/// This struct can and should be kept in exact sync with the other binary tree enumerators:
/// <see cref="ImmutableList{T}.Enumerator"/>, <see cref="ImmutableSortedDictionary{TKey, TValue}.Enumerator"/>, and <see cref="ImmutableSortedSet{T}.Enumerator"/>.
///
/// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable
/// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool,
/// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk
/// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data
/// corruption and/or exceptions.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public struct Enumerator : IEnumerator<T>, ISecurePooledObjectUser, IStrongEnumerator<T>
{
/// <summary>
/// The resource pool of reusable mutable stacks for purposes of enumeration.
/// </summary>
/// <remarks>
/// We utilize this resource pool to make "allocation free" enumeration achievable.
/// </remarks>
private static readonly SecureObjectPool<Stack<RefAsValueType<Node>>, Enumerator> s_EnumeratingStacks =
new SecureObjectPool<Stack<RefAsValueType<Node>>, Enumerator>();
/// <summary>
/// The builder being enumerated, if applicable.
/// </summary>
private readonly Builder? _builder;
/// <summary>
/// A unique ID for this instance of this enumerator.
/// Used to protect pooled objects from use after they are recycled.
/// </summary>
private readonly int _poolUserId;
/// <summary>
/// The starting index of the collection at which to begin enumeration.
/// </summary>
private readonly int _startIndex;
/// <summary>
/// The number of elements to include in the enumeration.
/// </summary>
private readonly int _count;
/// <summary>
/// The number of elements left in the enumeration.
/// </summary>
private int _remainingCount;
/// <summary>
/// A value indicating whether this enumerator walks in reverse order.
/// </summary>
private readonly bool _reversed;
/// <summary>
/// The set being enumerated.
/// </summary>
private Node _root;
/// <summary>
/// The stack to use for enumerating the binary tree.
/// </summary>
private SecurePooledObject<Stack<RefAsValueType<Node>>>? _stack;
/// <summary>
/// The node currently selected.
/// </summary>
private Node? _current;
/// <summary>
/// The version of the builder (when applicable) that is being enumerated.
/// </summary>
private int _enumeratingBuilderVersion;
/// <summary>
/// Initializes an <see cref="Enumerator"/> structure.
/// </summary>
/// <param name="root">The root of the set to be enumerated.</param>
/// <param name="builder">The builder, if applicable.</param>
/// <param name="startIndex">The index of the first element to enumerate.</param>
/// <param name="count">The number of elements in this collection.</param>
/// <param name="reversed"><c>true</c> if the list should be enumerated in reverse order.</param>
internal Enumerator(Node root, Builder? builder = null, int startIndex = -1, int count = -1, bool reversed = false)
{
Requires.NotNull(root, nameof(root));
Requires.Range(startIndex >= -1, nameof(startIndex));
Requires.Range(count >= -1, nameof(count));
Requires.Argument(reversed || count == -1 || (startIndex == -1 ? 0 : startIndex) + count <= root.Count);
Requires.Argument(!reversed || count == -1 || (startIndex == -1 ? root.Count - 1 : startIndex) - count + 1 >= 0);
_root = root;
_builder = builder;
_current = null;
_startIndex = startIndex >= 0 ? startIndex : (reversed ? root.Count - 1 : 0);
_count = count == -1 ? root.Count : count;
_remainingCount = _count;
_reversed = reversed;
_enumeratingBuilderVersion = builder != null ? builder.Version : -1;
_poolUserId = SecureObjectPool.NewId();
_stack = null;
if (_count > 0)
{
if (!s_EnumeratingStacks.TryTake(this, out _stack))
{
_stack = s_EnumeratingStacks.PrepNew(this, new Stack<RefAsValueType<Node>>(root.Height));
}
this.ResetStack();
}
}
/// <inheritdoc/>
int ISecurePooledObjectUser.PoolUserId => _poolUserId;
/// <summary>
/// The current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
if (_current != null)
{
return _current.Value;
}
throw new InvalidOperationException();
}
}
/// <summary>
/// The current element.
/// </summary>
object? System.Collections.IEnumerator.Current => this.Current;
/// <summary>
/// Disposes of this enumerator and returns the stack reference to the resource pool.
/// </summary>
public void Dispose()
{
_root = null!;
_current = null;
if (_stack != null && _stack.TryUse(ref this, out Stack<RefAsValueType<Node>>? stack))
{
stack.ClearFastWhenEmpty();
s_EnumeratingStacks.TryAdd(this, _stack!);
}
_stack = null;
}
/// <summary>
/// Advances enumeration to the next element.
/// </summary>
/// <returns>A value indicating whether there is another element in the enumeration.</returns>
public bool MoveNext()
{
this.ThrowIfDisposed();
this.ThrowIfChanged();
if (_stack != null)
{
var stack = _stack.Use(ref this);
if (_remainingCount > 0 && stack.Count > 0)
{
Node n = stack.Pop().Value;
_current = n;
this.PushNext(this.NextBranch(n)!);
_remainingCount--;
return true;
}
}
_current = null;
return false;
}
/// <summary>
/// Restarts enumeration.
/// </summary>
public void Reset()
{
this.ThrowIfDisposed();
_enumeratingBuilderVersion = _builder != null ? _builder.Version : -1;
_remainingCount = _count;
if (_stack != null)
{
this.ResetStack();
}
}
/// <summary>Resets the stack used for enumeration.</summary>
private void ResetStack()
{
Debug.Assert(_stack != null);
var stack = _stack.Use(ref this);
stack.ClearFastWhenEmpty();
var node = _root;
var skipNodes = _reversed ? _root.Count - _startIndex - 1 : _startIndex;
while (!node.IsEmpty && skipNodes != this.PreviousBranch(node)!.Count)
{
if (skipNodes < this.PreviousBranch(node)!.Count)
{
stack.Push(new RefAsValueType<Node>(node));
node = this.PreviousBranch(node)!;
}
else
{
skipNodes -= this.PreviousBranch(node)!.Count + 1;
node = this.NextBranch(node)!;
}
}
if (!node.IsEmpty)
{
stack.Push(new RefAsValueType<Node>(node));
}
}
/// <summary>
/// Obtains the right branch of the given node (or the left, if walking in reverse).
/// </summary>
private Node? NextBranch(Node node) => _reversed ? node.Left : node.Right;
/// <summary>
/// Obtains the left branch of the given node (or the right, if walking in reverse).
/// </summary>
private Node? PreviousBranch(Node node) => _reversed ? node.Right : node.Left;
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed.
/// </summary>
private void ThrowIfDisposed()
{
// Since this is a struct, copies might not have been marked as disposed.
// But the stack we share across those copies would know.
// This trick only works when we have a non-null stack.
// For enumerators of empty collections, there isn't any natural
// way to know when a copy of the struct has been disposed of.
if (_root == null || (_stack != null && !_stack.IsOwned(ref this)))
{
Requires.FailObjectDisposed(this);
}
}
/// <summary>
/// Throws an exception if the underlying builder's contents have been changed since enumeration started.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown if the collection has changed.</exception>
private void ThrowIfChanged()
{
if (_builder != null && _builder.Version != _enumeratingBuilderVersion)
{
throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration);
}
}
/// <summary>
/// Pushes this node and all its Left descendants onto the stack.
/// </summary>
/// <param name="node">The starting node to push onto the stack.</param>
private void PushNext(Node node)
{
Requires.NotNull(node, nameof(node));
if (!node.IsEmpty)
{
Debug.Assert(_stack != null);
var stack = _stack.Use(ref this);
while (!node.IsEmpty)
{
stack.Push(new RefAsValueType<Node>(node));
node = this.PreviousBranch(node)!;
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
namespace System.Collections.Immutable
{
public sealed partial class ImmutableList<T>
{
/// <summary>
/// Enumerates the contents of a binary tree.
/// </summary>
/// <remarks>
/// This struct can and should be kept in exact sync with the other binary tree enumerators:
/// <see cref="ImmutableList{T}.Enumerator"/>, <see cref="ImmutableSortedDictionary{TKey, TValue}.Enumerator"/>, and <see cref="ImmutableSortedSet{T}.Enumerator"/>.
///
/// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable
/// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool,
/// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk
/// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data
/// corruption and/or exceptions.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public struct Enumerator : IEnumerator<T>, ISecurePooledObjectUser, IStrongEnumerator<T>
{
/// <summary>
/// The resource pool of reusable mutable stacks for purposes of enumeration.
/// </summary>
/// <remarks>
/// We utilize this resource pool to make "allocation free" enumeration achievable.
/// </remarks>
private static readonly SecureObjectPool<Stack<RefAsValueType<Node>>, Enumerator> s_EnumeratingStacks =
new SecureObjectPool<Stack<RefAsValueType<Node>>, Enumerator>();
/// <summary>
/// The builder being enumerated, if applicable.
/// </summary>
private readonly Builder? _builder;
/// <summary>
/// A unique ID for this instance of this enumerator.
/// Used to protect pooled objects from use after they are recycled.
/// </summary>
private readonly int _poolUserId;
/// <summary>
/// The starting index of the collection at which to begin enumeration.
/// </summary>
private readonly int _startIndex;
/// <summary>
/// The number of elements to include in the enumeration.
/// </summary>
private readonly int _count;
/// <summary>
/// The number of elements left in the enumeration.
/// </summary>
private int _remainingCount;
/// <summary>
/// A value indicating whether this enumerator walks in reverse order.
/// </summary>
private readonly bool _reversed;
/// <summary>
/// The set being enumerated.
/// </summary>
private Node _root;
/// <summary>
/// The stack to use for enumerating the binary tree.
/// </summary>
private SecurePooledObject<Stack<RefAsValueType<Node>>>? _stack;
/// <summary>
/// The node currently selected.
/// </summary>
private Node? _current;
/// <summary>
/// The version of the builder (when applicable) that is being enumerated.
/// </summary>
private int _enumeratingBuilderVersion;
/// <summary>
/// Initializes an <see cref="Enumerator"/> structure.
/// </summary>
/// <param name="root">The root of the set to be enumerated.</param>
/// <param name="builder">The builder, if applicable.</param>
/// <param name="startIndex">The index of the first element to enumerate.</param>
/// <param name="count">The number of elements in this collection.</param>
/// <param name="reversed"><c>true</c> if the list should be enumerated in reverse order.</param>
internal Enumerator(Node root, Builder? builder = null, int startIndex = -1, int count = -1, bool reversed = false)
{
Requires.NotNull(root, nameof(root));
Requires.Range(startIndex >= -1, nameof(startIndex));
Requires.Range(count >= -1, nameof(count));
Requires.Argument(reversed || count == -1 || (startIndex == -1 ? 0 : startIndex) + count <= root.Count);
Requires.Argument(!reversed || count == -1 || (startIndex == -1 ? root.Count - 1 : startIndex) - count + 1 >= 0);
_root = root;
_builder = builder;
_current = null;
_startIndex = startIndex >= 0 ? startIndex : (reversed ? root.Count - 1 : 0);
_count = count == -1 ? root.Count : count;
_remainingCount = _count;
_reversed = reversed;
_enumeratingBuilderVersion = builder != null ? builder.Version : -1;
_poolUserId = SecureObjectPool.NewId();
_stack = null;
if (_count > 0)
{
if (!s_EnumeratingStacks.TryTake(this, out _stack))
{
_stack = s_EnumeratingStacks.PrepNew(this, new Stack<RefAsValueType<Node>>(root.Height));
}
this.ResetStack();
}
}
/// <inheritdoc/>
int ISecurePooledObjectUser.PoolUserId => _poolUserId;
/// <summary>
/// The current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
if (_current != null)
{
return _current.Value;
}
throw new InvalidOperationException();
}
}
/// <summary>
/// The current element.
/// </summary>
object? System.Collections.IEnumerator.Current => this.Current;
/// <summary>
/// Disposes of this enumerator and returns the stack reference to the resource pool.
/// </summary>
public void Dispose()
{
_root = null!;
_current = null;
if (_stack != null && _stack.TryUse(ref this, out Stack<RefAsValueType<Node>>? stack))
{
stack.ClearFastWhenEmpty();
s_EnumeratingStacks.TryAdd(this, _stack!);
}
_stack = null;
}
/// <summary>
/// Advances enumeration to the next element.
/// </summary>
/// <returns>A value indicating whether there is another element in the enumeration.</returns>
public bool MoveNext()
{
this.ThrowIfDisposed();
this.ThrowIfChanged();
if (_stack != null)
{
var stack = _stack.Use(ref this);
if (_remainingCount > 0 && stack.Count > 0)
{
Node n = stack.Pop().Value;
_current = n;
this.PushNext(this.NextBranch(n)!);
_remainingCount--;
return true;
}
}
_current = null;
return false;
}
/// <summary>
/// Restarts enumeration.
/// </summary>
public void Reset()
{
this.ThrowIfDisposed();
_enumeratingBuilderVersion = _builder != null ? _builder.Version : -1;
_remainingCount = _count;
if (_stack != null)
{
this.ResetStack();
}
}
/// <summary>Resets the stack used for enumeration.</summary>
private void ResetStack()
{
Debug.Assert(_stack != null);
var stack = _stack.Use(ref this);
stack.ClearFastWhenEmpty();
var node = _root;
var skipNodes = _reversed ? _root.Count - _startIndex - 1 : _startIndex;
while (!node.IsEmpty && skipNodes != this.PreviousBranch(node)!.Count)
{
if (skipNodes < this.PreviousBranch(node)!.Count)
{
stack.Push(new RefAsValueType<Node>(node));
node = this.PreviousBranch(node)!;
}
else
{
skipNodes -= this.PreviousBranch(node)!.Count + 1;
node = this.NextBranch(node)!;
}
}
if (!node.IsEmpty)
{
stack.Push(new RefAsValueType<Node>(node));
}
}
/// <summary>
/// Obtains the right branch of the given node (or the left, if walking in reverse).
/// </summary>
private Node? NextBranch(Node node) => _reversed ? node.Left : node.Right;
/// <summary>
/// Obtains the left branch of the given node (or the right, if walking in reverse).
/// </summary>
private Node? PreviousBranch(Node node) => _reversed ? node.Right : node.Left;
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed.
/// </summary>
private void ThrowIfDisposed()
{
// Since this is a struct, copies might not have been marked as disposed.
// But the stack we share across those copies would know.
// This trick only works when we have a non-null stack.
// For enumerators of empty collections, there isn't any natural
// way to know when a copy of the struct has been disposed of.
if (_root == null || (_stack != null && !_stack.IsOwned(ref this)))
{
Requires.FailObjectDisposed(this);
}
}
/// <summary>
/// Throws an exception if the underlying builder's contents have been changed since enumeration started.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown if the collection has changed.</exception>
private void ThrowIfChanged()
{
if (_builder != null && _builder.Version != _enumeratingBuilderVersion)
{
throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration);
}
}
/// <summary>
/// Pushes this node and all its Left descendants onto the stack.
/// </summary>
/// <param name="node">The starting node to push onto the stack.</param>
private void PushNext(Node node)
{
Requires.NotNull(node, nameof(node));
if (!node.IsEmpty)
{
Debug.Assert(_stack != null);
var stack = _stack.Use(ref this);
while (!node.IsEmpty)
{
stack.Push(new RefAsValueType<Node>(node));
node = this.PreviousBranch(node)!;
}
}
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityCreationOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace System.Diagnostics
{
/// <summary>
/// ActivityCreationOptions is encapsulating all needed information which will be sent to the ActivityListener to decide about creating the Activity object and with what state.
/// The possible generic type parameters is <see cref="ActivityContext"/> or <see cref="string"/>
/// </summary>
public readonly struct ActivityCreationOptions<T>
{
private readonly ActivityTagsCollection? _samplerTags;
private readonly ActivityContext _context;
private readonly string? _traceState;
/// <summary>
/// Construct a new <see cref="ActivityCreationOptions{T}"/> object.
/// </summary>
/// <param name="source">The trace Activity source<see cref="ActivitySource"/> used to request creating the Activity object.</param>
/// <param name="name">The operation name of the Activity.</param>
/// <param name="parent">The requested parent to create the Activity object with. The parent either be a parent Id represented as string or it can be a parent context <see cref="ActivityContext"/>.</param>
/// <param name="kind"><see cref="ActivityKind"/> to create the Activity object with.</param>
/// <param name="tags">Key-value pairs list for the tags to create the Activity object with.<see cref="ActivityContext"/></param>
/// <param name="links"><see cref="ActivityLink"/> list to create the Activity object with.</param>
/// <param name="idFormat">The default Id format to use.</param>
internal ActivityCreationOptions(ActivitySource source, string name, T parent, ActivityKind kind, IEnumerable<KeyValuePair<string, object?>>? tags, IEnumerable<ActivityLink>? links, ActivityIdFormat idFormat)
{
Source = source;
Name = name;
Kind = kind;
Parent = parent;
Tags = tags;
Links = links;
IdFormat = idFormat;
if (IdFormat == ActivityIdFormat.Unknown && Activity.ForceDefaultIdFormat)
{
IdFormat = Activity.DefaultIdFormat;
}
_samplerTags = null;
_traceState = null;
if (parent is ActivityContext ac && ac != default)
{
_context = ac;
if (IdFormat == ActivityIdFormat.Unknown)
{
IdFormat = ActivityIdFormat.W3C;
}
_traceState = ac.TraceState;
}
else if (parent is string p && p != null)
{
if (IdFormat != ActivityIdFormat.Hierarchical)
{
if (ActivityContext.TryParse(p, null, out _context))
{
IdFormat = ActivityIdFormat.W3C;
}
if (IdFormat == ActivityIdFormat.Unknown)
{
IdFormat =ActivityIdFormat.Hierarchical;
}
}
else
{
_context = default;
}
}
else
{
_context = default;
if (IdFormat == ActivityIdFormat.Unknown)
{
IdFormat = Activity.Current != null ? Activity.Current.IdFormat : Activity.DefaultIdFormat;
}
}
}
/// <summary>
/// Retrieve the <see cref="ActivitySource"/> object.
/// </summary>
public ActivitySource Source { get; }
/// <summary>
/// Retrieve the name which requested to create the Activity object with.
/// </summary>
public string Name { get; }
/// <summary>
/// Retrieve the <see cref="ActivityKind"/> which requested to create the Activity object with.
/// </summary>
public ActivityKind Kind { get; }
/// <summary>
/// Retrieve the parent which requested to create the Activity object with. Parent will be either in form of string or <see cref="ActivityContext"/>.
/// </summary>
public T Parent { get; }
/// <summary>
/// Retrieve the tags which requested to create the Activity object with.
/// </summary>
public IEnumerable<KeyValuePair<string, object?>>? Tags { get; }
/// <summary>
/// Retrieve the list of <see cref="ActivityLink"/> which requested to create the Activity object with.
/// </summary>
public IEnumerable<ActivityLink>? Links { get; }
public ActivityTagsCollection SamplingTags
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
if (_samplerTags == null)
{
// Because the struct is readonly, we cannot directly assign _samplerTags. We have to workaround it by calling Unsafe.AsRef
Unsafe.AsRef(in _samplerTags) = new ActivityTagsCollection();
}
return _samplerTags!;
}
}
public ActivityTraceId TraceId
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
if (Parent is ActivityContext && IdFormat == ActivityIdFormat.W3C && _context == default)
{
Func<ActivityTraceId>? traceIdGenerator = Activity.TraceIdGenerator;
ActivityTraceId id = traceIdGenerator == null ? ActivityTraceId.CreateRandom() : traceIdGenerator();
// Because the struct is readonly, we cannot directly assign _context. We have to workaround it by calling Unsafe.AsRef
Unsafe.AsRef(in _context) = new ActivityContext(id, default, ActivityTraceFlags.None);
}
return _context.TraceId;
}
}
/// <summary>
/// Retrieve or initialize the trace state to use for the Activity we may create.
/// </summary>
public string? TraceState
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get => _traceState;
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
init
{
_traceState = value;
}
}
// SetTraceState is to set the _traceState without the need of copying the whole structure.
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
internal void SetTraceState(string? traceState) => Unsafe.AsRef(in _traceState) = traceState;
/// <summary>
/// Retrieve Id format of to use for the Activity we may create.
/// </summary>
internal ActivityIdFormat IdFormat { get; }
// Helper to access the sampling tags. The SamplingTags Getter can allocate when not necessary.
internal ActivityTagsCollection? GetSamplingTags() => _samplerTags;
internal ActivityContext GetContext() => _context;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace System.Diagnostics
{
/// <summary>
/// ActivityCreationOptions is encapsulating all needed information which will be sent to the ActivityListener to decide about creating the Activity object and with what state.
/// The possible generic type parameters is <see cref="ActivityContext"/> or <see cref="string"/>
/// </summary>
public readonly struct ActivityCreationOptions<T>
{
private readonly ActivityTagsCollection? _samplerTags;
private readonly ActivityContext _context;
private readonly string? _traceState;
/// <summary>
/// Construct a new <see cref="ActivityCreationOptions{T}"/> object.
/// </summary>
/// <param name="source">The trace Activity source<see cref="ActivitySource"/> used to request creating the Activity object.</param>
/// <param name="name">The operation name of the Activity.</param>
/// <param name="parent">The requested parent to create the Activity object with. The parent either be a parent Id represented as string or it can be a parent context <see cref="ActivityContext"/>.</param>
/// <param name="kind"><see cref="ActivityKind"/> to create the Activity object with.</param>
/// <param name="tags">Key-value pairs list for the tags to create the Activity object with.<see cref="ActivityContext"/></param>
/// <param name="links"><see cref="ActivityLink"/> list to create the Activity object with.</param>
/// <param name="idFormat">The default Id format to use.</param>
internal ActivityCreationOptions(ActivitySource source, string name, T parent, ActivityKind kind, IEnumerable<KeyValuePair<string, object?>>? tags, IEnumerable<ActivityLink>? links, ActivityIdFormat idFormat)
{
Source = source;
Name = name;
Kind = kind;
Parent = parent;
Tags = tags;
Links = links;
IdFormat = idFormat;
if (IdFormat == ActivityIdFormat.Unknown && Activity.ForceDefaultIdFormat)
{
IdFormat = Activity.DefaultIdFormat;
}
_samplerTags = null;
_traceState = null;
if (parent is ActivityContext ac && ac != default)
{
_context = ac;
if (IdFormat == ActivityIdFormat.Unknown)
{
IdFormat = ActivityIdFormat.W3C;
}
_traceState = ac.TraceState;
}
else if (parent is string p && p != null)
{
if (IdFormat != ActivityIdFormat.Hierarchical)
{
if (ActivityContext.TryParse(p, null, out _context))
{
IdFormat = ActivityIdFormat.W3C;
}
if (IdFormat == ActivityIdFormat.Unknown)
{
IdFormat =ActivityIdFormat.Hierarchical;
}
}
else
{
_context = default;
}
}
else
{
_context = default;
if (IdFormat == ActivityIdFormat.Unknown)
{
IdFormat = Activity.Current != null ? Activity.Current.IdFormat : Activity.DefaultIdFormat;
}
}
}
/// <summary>
/// Retrieve the <see cref="ActivitySource"/> object.
/// </summary>
public ActivitySource Source { get; }
/// <summary>
/// Retrieve the name which requested to create the Activity object with.
/// </summary>
public string Name { get; }
/// <summary>
/// Retrieve the <see cref="ActivityKind"/> which requested to create the Activity object with.
/// </summary>
public ActivityKind Kind { get; }
/// <summary>
/// Retrieve the parent which requested to create the Activity object with. Parent will be either in form of string or <see cref="ActivityContext"/>.
/// </summary>
public T Parent { get; }
/// <summary>
/// Retrieve the tags which requested to create the Activity object with.
/// </summary>
public IEnumerable<KeyValuePair<string, object?>>? Tags { get; }
/// <summary>
/// Retrieve the list of <see cref="ActivityLink"/> which requested to create the Activity object with.
/// </summary>
public IEnumerable<ActivityLink>? Links { get; }
public ActivityTagsCollection SamplingTags
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
if (_samplerTags == null)
{
// Because the struct is readonly, we cannot directly assign _samplerTags. We have to workaround it by calling Unsafe.AsRef
Unsafe.AsRef(in _samplerTags) = new ActivityTagsCollection();
}
return _samplerTags!;
}
}
public ActivityTraceId TraceId
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
if (Parent is ActivityContext && IdFormat == ActivityIdFormat.W3C && _context == default)
{
Func<ActivityTraceId>? traceIdGenerator = Activity.TraceIdGenerator;
ActivityTraceId id = traceIdGenerator == null ? ActivityTraceId.CreateRandom() : traceIdGenerator();
// Because the struct is readonly, we cannot directly assign _context. We have to workaround it by calling Unsafe.AsRef
Unsafe.AsRef(in _context) = new ActivityContext(id, default, ActivityTraceFlags.None);
}
return _context.TraceId;
}
}
/// <summary>
/// Retrieve or initialize the trace state to use for the Activity we may create.
/// </summary>
public string? TraceState
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get => _traceState;
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
init
{
_traceState = value;
}
}
// SetTraceState is to set the _traceState without the need of copying the whole structure.
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
internal void SetTraceState(string? traceState) => Unsafe.AsRef(in _traceState) = traceState;
/// <summary>
/// Retrieve Id format of to use for the Activity we may create.
/// </summary>
internal ActivityIdFormat IdFormat { get; }
// Helper to access the sampling tags. The SamplingTags Getter can allocate when not necessary.
internal ActivityTagsCollection? GetSamplingTags() => _samplerTags;
internal ActivityContext GetContext() => _context;
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.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.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public readonly struct MethodDefinition
{
private readonly MetadataReader _reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint _treatmentAndRowId;
internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
_reader = reader;
_treatmentAndRowId = treatmentAndRowId;
}
private int RowId
{
get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); }
}
private MethodDefTreatment Treatment
{
get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
private MethodDefinitionHandle Handle
{
get { return MethodDefinitionHandle.FromRowId(RowId); }
}
public StringHandle Name
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetName(Handle);
}
return GetProjectedName();
}
}
public BlobHandle Signature
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetSignature(Handle);
}
return GetProjectedSignature();
}
}
public MethodSignature<TType> DecodeSignature<TType, TGenericContext>(ISignatureTypeProvider<TType, TGenericContext> provider, TGenericContext genericContext)
{
var decoder = new SignatureDecoder<TType, TGenericContext>(provider, _reader, genericContext);
var blobReader = _reader.GetBlobReader(Signature);
return decoder.DecodeMethodSignature(ref blobReader);
}
public int RelativeVirtualAddress
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetRva(Handle);
}
return GetProjectedRelativeVirtualAddress();
}
}
public MethodAttributes Attributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetFlags(Handle);
}
return GetProjectedFlags();
}
}
public MethodImplAttributes ImplAttributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetImplFlags(Handle);
}
return GetProjectedImplFlags();
}
}
public TypeDefinitionHandle GetDeclaringType()
{
return _reader.GetDeclaringType(Handle);
}
public ParameterHandleCollection GetParameters()
{
return new ParameterHandleCollection(_reader, Handle);
}
public GenericParameterHandleCollection GetGenericParameters()
{
return _reader.GenericParamTable.FindGenericParametersForMethod(Handle);
}
public MethodImport GetImport()
{
int implMapRid = _reader.ImplMapTable.FindImplForMethod(Handle);
if (implMapRid == 0)
{
return default(MethodImport);
}
return _reader.ImplMapTable.GetImport(implMapRid);
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
return new CustomAttributeHandleCollection(_reader, Handle);
}
public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes()
{
return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle);
}
#region Projections
private StringHandle GetProjectedName()
{
if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod)
{
return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose);
}
return _reader.MethodDefTable.GetName(Handle);
}
private MethodAttributes GetProjectedFlags()
{
MethodAttributes flags = _reader.MethodDefTable.GetFlags(Handle);
MethodDefTreatment treatment = Treatment;
if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private;
}
if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0)
{
flags |= MethodAttributes.Abstract;
}
if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public;
}
return flags | MethodAttributes.HideBySig;
}
private MethodImplAttributes GetProjectedImplFlags()
{
MethodImplAttributes flags = _reader.MethodDefTable.GetImplFlags(Handle);
switch (Treatment & MethodDefTreatment.KindMask)
{
case MethodDefTreatment.DelegateMethod:
flags |= MethodImplAttributes.Runtime;
break;
case MethodDefTreatment.DisposeMethod:
case MethodDefTreatment.AttributeMethod:
case MethodDefTreatment.InterfaceMethod:
case MethodDefTreatment.HiddenInterfaceImplementation:
case MethodDefTreatment.Other:
flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall;
break;
}
return flags;
}
private BlobHandle GetProjectedSignature()
{
return _reader.MethodDefTable.GetSignature(Handle);
}
private int GetProjectedRelativeVirtualAddress()
{
return 0;
}
#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.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public readonly struct MethodDefinition
{
private readonly MetadataReader _reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint _treatmentAndRowId;
internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
_reader = reader;
_treatmentAndRowId = treatmentAndRowId;
}
private int RowId
{
get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); }
}
private MethodDefTreatment Treatment
{
get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
private MethodDefinitionHandle Handle
{
get { return MethodDefinitionHandle.FromRowId(RowId); }
}
public StringHandle Name
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetName(Handle);
}
return GetProjectedName();
}
}
public BlobHandle Signature
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetSignature(Handle);
}
return GetProjectedSignature();
}
}
public MethodSignature<TType> DecodeSignature<TType, TGenericContext>(ISignatureTypeProvider<TType, TGenericContext> provider, TGenericContext genericContext)
{
var decoder = new SignatureDecoder<TType, TGenericContext>(provider, _reader, genericContext);
var blobReader = _reader.GetBlobReader(Signature);
return decoder.DecodeMethodSignature(ref blobReader);
}
public int RelativeVirtualAddress
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetRva(Handle);
}
return GetProjectedRelativeVirtualAddress();
}
}
public MethodAttributes Attributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetFlags(Handle);
}
return GetProjectedFlags();
}
}
public MethodImplAttributes ImplAttributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetImplFlags(Handle);
}
return GetProjectedImplFlags();
}
}
public TypeDefinitionHandle GetDeclaringType()
{
return _reader.GetDeclaringType(Handle);
}
public ParameterHandleCollection GetParameters()
{
return new ParameterHandleCollection(_reader, Handle);
}
public GenericParameterHandleCollection GetGenericParameters()
{
return _reader.GenericParamTable.FindGenericParametersForMethod(Handle);
}
public MethodImport GetImport()
{
int implMapRid = _reader.ImplMapTable.FindImplForMethod(Handle);
if (implMapRid == 0)
{
return default(MethodImport);
}
return _reader.ImplMapTable.GetImport(implMapRid);
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
return new CustomAttributeHandleCollection(_reader, Handle);
}
public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes()
{
return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle);
}
#region Projections
private StringHandle GetProjectedName()
{
if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod)
{
return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose);
}
return _reader.MethodDefTable.GetName(Handle);
}
private MethodAttributes GetProjectedFlags()
{
MethodAttributes flags = _reader.MethodDefTable.GetFlags(Handle);
MethodDefTreatment treatment = Treatment;
if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private;
}
if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0)
{
flags |= MethodAttributes.Abstract;
}
if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public;
}
return flags | MethodAttributes.HideBySig;
}
private MethodImplAttributes GetProjectedImplFlags()
{
MethodImplAttributes flags = _reader.MethodDefTable.GetImplFlags(Handle);
switch (Treatment & MethodDefTreatment.KindMask)
{
case MethodDefTreatment.DelegateMethod:
flags |= MethodImplAttributes.Runtime;
break;
case MethodDefTreatment.DisposeMethod:
case MethodDefTreatment.AttributeMethod:
case MethodDefTreatment.InterfaceMethod:
case MethodDefTreatment.HiddenInterfaceImplementation:
case MethodDefTreatment.Other:
flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall;
break;
}
return flags;
}
private BlobHandle GetProjectedSignature()
{
return _reader.MethodDefTable.GetSignature(Handle);
}
private int GetProjectedRelativeVirtualAddress()
{
return 0;
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Formats.Cbor/src/Resources/Strings.resx | <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Argument_EncodeDestinationTooSmall" xml:space="preserve">
<value>The destination is too small to hold the encoded value.</value>
</data>
<data name="Cbor_PopMajorTypeMismatch" xml:space="preserve">
<value>Cannot perform the requested operation, the current major type context is '{0}'.</value>
</data>
<data name="Cbor_NotAtEndOfDefiniteLengthDataItem" xml:space="preserve">
<value>Not at end of the definite-length data item.</value>
</data>
<data name="Cbor_NotAtEndOfIndefiniteLengthDataItem" xml:space="preserve">
<value>Not at end of the indefinite-length data item.</value>
</data>
<data name="Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support indefinite-length data items.</value>
</data>
<data name="Cbor_ConformanceMode_NonCanonicalIntegerRepresentation" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support non-canonical integer representations.</value>
</data>
<data name="Cbor_ConformanceMode_RequiresDefiniteLengthItems" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support indefinite-length items.</value>
</data>
<data name="Cbor_ConformanceMode_ContainsDuplicateKeys" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support duplicate keys.</value>
</data>
<data name="Cbor_ConformanceMode_KeysNotInSortedOrder" xml:space="preserve">
<value>CBOR keys not sorted in accordance with conformance mode '{0}'.</value>
</data>
<data name="Cbor_ConformanceMode_TagsNotSupported" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support tagged values.</value>
</data>
<data name="Cbor_Reader_DefiniteLengthExceedsBufferSize" xml:space="preserve">
<value>Declared definite length of CBOR data item exceeds available buffer size.</value>
</data>
<data name="Cbor_Reader_NoMoreDataItemsToRead" xml:space="preserve">
<value>No more CBOR data items to read in the current context.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_UnexpectedEndOfBuffer" xml:space="preserve">
<value>Unexpected end of CBOR encoding data.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_IndefiniteLengthStringContainsInvalidDataItem" xml:space="preserve">
<value>Indefinite-length CBOR string nests an invalid data item of major type {0}.</value>
</data>
<data name="Cbor_Reader_MajorTypeMismatch" xml:space="preserve">
<value>Cannot perform the requested operation, the next CBOR data item is of major type '{0}'.</value>
</data>
<data name="Cbor_Reader_IsAtRootContext" xml:space="preserve">
<value>CBOR reader is already at the root data item context.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_TagNotFollowedByValue" xml:space="preserve">
<value>A CBOR tag should always be followed by a data item.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_InvalidIntegerEncoding" xml:space="preserve">
<value>CBOR initial byte contains invalid integer encoding</value>
</data>
<data name="Cbor_Reader_InvalidCbor_KeyMissingValue" xml:space="preserve">
<value>The current CBOR map contains an incomplete key/value pair.</value>
</data>
<data name="Cbor_Reader_NotAFloatEncoding" xml:space="preserve">
<value>Data item does not encode a floating point number.</value>
</data>
<data name="Cbor_Reader_ReadingAsLowerPrecision" xml:space="preserve">
<value>Attempting to read floating point encoding as a lower-precision value.</value>
</data>
<data name="Cbor_Reader_NotABooleanEncoding" xml:space="preserve">
<value>CBOR simple value does not encode a boolean value.</value>
</data>
<data name="Cbor_Reader_NotASimpleValueEncoding" xml:space="preserve">
<value>CBOR data item does not encode a simple value.</value>
</data>
<data name="Cbor_Reader_NotANullEncoding" xml:space="preserve">
<value>CBOR simple value does not encode null.</value>
</data>
<data name="Cbor_ConformanceMode_InvalidSimpleValueEncoding" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support simple values in the range 24-31 and must be encoded as small as possible.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_UnexpectedBreakByte" xml:space="preserve">
<value>CBOR definite-length data items contains unexpected break byte.</value>
</data>
<data name="Cbor_Reader_Skip_InvalidState" xml:space="preserve">
<value>Reader state '{0}' is not at the start of a data item.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_InvalidUtf8StringEncoding" xml:space="preserve">
<value>CBOR text string payload is not valid a UTF-8 encoding.</value>
</data>
<data name="Cbor_Reader_NotIndefiniteLengthString" xml:space="preserve">
<value>CBOR string is not of indefinite length.</value>
</data>
<data name="Cbor_Reader_TagMismatch" xml:space="preserve">
<value>CBOR tag does not match expected value.</value>
</data>
<data name="Cbor_Reader_InvalidDateTimeEncoding" xml:space="preserve">
<value>Not a valid tagged RFC3339 DateTime encoding.</value>
</data>
<data name="Cbor_Reader_InvalidUnixTimeEncoding" xml:space="preserve">
<value>Not a valid tagged unix time encoding.</value>
</data>
<data name="Cbor_Reader_InvalidBigNumEncoding" xml:space="preserve">
<value>Not a valid tagged bignum encoding.</value>
</data>
<data name="Cbor_Reader_InvalidDecimalEncoding" xml:space="preserve">
<value>Not a valid tagged decimal encoding.</value>
</data>
<data name="Cbor_Writer_PayloadIsNotValidCbor" xml:space="preserve">
<value>Not a valid CBOR value encoding.</value>
</data>
<data name="Cbor_Writer_IncompleteCborDocument" xml:space="preserve">
<value>Writer contains an incomplete CBOR document.</value>
</data>
<data name="Cbor_Writer_DefiniteLengthExceeded" xml:space="preserve">
<value>Adding a CBOR data item to the current context exceeds its definite length.</value>
</data>
<data name="Cbor_Writer_CannotNestDataItemsInIndefiniteLengthStrings" xml:space="preserve">
<value>Cannot nest data items in indefinite-length CBOR string contexts.</value>
</data>
<data name="Cbor_Writer_MapIncompleteKeyValuePair" xml:space="preserve">
<value>CBOR map incomplete; each key must be followed by a corresponding value.</value>
</data>
<data name="Cbor_Writer_InvalidUtf8String" xml:space="preserve">
<value>Not a valid UTF-8 encoding.</value>
</data>
<data name="Cbor_Writer_ValueCannotBeInfiniteOrNaN" xml:space="preserve">
<value>Value cannot be infinite or NaN.</value>
</data>
<data name="Cbor_Writer_DecimalOverflow" xml:space="preserve">
<value>Value was either too large or too small for a Decimal.</value>
</data>
<data name="CborContentException_DefaultMessage" xml:space="preserve">
<value>The CBOR encoding is invalid.</value>
</data>
</root>
| <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Argument_EncodeDestinationTooSmall" xml:space="preserve">
<value>The destination is too small to hold the encoded value.</value>
</data>
<data name="Cbor_PopMajorTypeMismatch" xml:space="preserve">
<value>Cannot perform the requested operation, the current major type context is '{0}'.</value>
</data>
<data name="Cbor_NotAtEndOfDefiniteLengthDataItem" xml:space="preserve">
<value>Not at end of the definite-length data item.</value>
</data>
<data name="Cbor_NotAtEndOfIndefiniteLengthDataItem" xml:space="preserve">
<value>Not at end of the indefinite-length data item.</value>
</data>
<data name="Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support indefinite-length data items.</value>
</data>
<data name="Cbor_ConformanceMode_NonCanonicalIntegerRepresentation" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support non-canonical integer representations.</value>
</data>
<data name="Cbor_ConformanceMode_RequiresDefiniteLengthItems" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support indefinite-length items.</value>
</data>
<data name="Cbor_ConformanceMode_ContainsDuplicateKeys" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support duplicate keys.</value>
</data>
<data name="Cbor_ConformanceMode_KeysNotInSortedOrder" xml:space="preserve">
<value>CBOR keys not sorted in accordance with conformance mode '{0}'.</value>
</data>
<data name="Cbor_ConformanceMode_TagsNotSupported" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support tagged values.</value>
</data>
<data name="Cbor_Reader_DefiniteLengthExceedsBufferSize" xml:space="preserve">
<value>Declared definite length of CBOR data item exceeds available buffer size.</value>
</data>
<data name="Cbor_Reader_NoMoreDataItemsToRead" xml:space="preserve">
<value>No more CBOR data items to read in the current context.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_UnexpectedEndOfBuffer" xml:space="preserve">
<value>Unexpected end of CBOR encoding data.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_IndefiniteLengthStringContainsInvalidDataItem" xml:space="preserve">
<value>Indefinite-length CBOR string nests an invalid data item of major type {0}.</value>
</data>
<data name="Cbor_Reader_MajorTypeMismatch" xml:space="preserve">
<value>Cannot perform the requested operation, the next CBOR data item is of major type '{0}'.</value>
</data>
<data name="Cbor_Reader_IsAtRootContext" xml:space="preserve">
<value>CBOR reader is already at the root data item context.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_TagNotFollowedByValue" xml:space="preserve">
<value>A CBOR tag should always be followed by a data item.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_InvalidIntegerEncoding" xml:space="preserve">
<value>CBOR initial byte contains invalid integer encoding</value>
</data>
<data name="Cbor_Reader_InvalidCbor_KeyMissingValue" xml:space="preserve">
<value>The current CBOR map contains an incomplete key/value pair.</value>
</data>
<data name="Cbor_Reader_NotAFloatEncoding" xml:space="preserve">
<value>Data item does not encode a floating point number.</value>
</data>
<data name="Cbor_Reader_ReadingAsLowerPrecision" xml:space="preserve">
<value>Attempting to read floating point encoding as a lower-precision value.</value>
</data>
<data name="Cbor_Reader_NotABooleanEncoding" xml:space="preserve">
<value>CBOR simple value does not encode a boolean value.</value>
</data>
<data name="Cbor_Reader_NotASimpleValueEncoding" xml:space="preserve">
<value>CBOR data item does not encode a simple value.</value>
</data>
<data name="Cbor_Reader_NotANullEncoding" xml:space="preserve">
<value>CBOR simple value does not encode null.</value>
</data>
<data name="Cbor_ConformanceMode_InvalidSimpleValueEncoding" xml:space="preserve">
<value>CBOR Conformance mode '{0}' does not support simple values in the range 24-31 and must be encoded as small as possible.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_UnexpectedBreakByte" xml:space="preserve">
<value>CBOR definite-length data items contains unexpected break byte.</value>
</data>
<data name="Cbor_Reader_Skip_InvalidState" xml:space="preserve">
<value>Reader state '{0}' is not at the start of a data item.</value>
</data>
<data name="Cbor_Reader_InvalidCbor_InvalidUtf8StringEncoding" xml:space="preserve">
<value>CBOR text string payload is not valid a UTF-8 encoding.</value>
</data>
<data name="Cbor_Reader_NotIndefiniteLengthString" xml:space="preserve">
<value>CBOR string is not of indefinite length.</value>
</data>
<data name="Cbor_Reader_TagMismatch" xml:space="preserve">
<value>CBOR tag does not match expected value.</value>
</data>
<data name="Cbor_Reader_InvalidDateTimeEncoding" xml:space="preserve">
<value>Not a valid tagged RFC3339 DateTime encoding.</value>
</data>
<data name="Cbor_Reader_InvalidUnixTimeEncoding" xml:space="preserve">
<value>Not a valid tagged unix time encoding.</value>
</data>
<data name="Cbor_Reader_InvalidBigNumEncoding" xml:space="preserve">
<value>Not a valid tagged bignum encoding.</value>
</data>
<data name="Cbor_Reader_InvalidDecimalEncoding" xml:space="preserve">
<value>Not a valid tagged decimal encoding.</value>
</data>
<data name="Cbor_Writer_PayloadIsNotValidCbor" xml:space="preserve">
<value>Not a valid CBOR value encoding.</value>
</data>
<data name="Cbor_Writer_IncompleteCborDocument" xml:space="preserve">
<value>Writer contains an incomplete CBOR document.</value>
</data>
<data name="Cbor_Writer_DefiniteLengthExceeded" xml:space="preserve">
<value>Adding a CBOR data item to the current context exceeds its definite length.</value>
</data>
<data name="Cbor_Writer_CannotNestDataItemsInIndefiniteLengthStrings" xml:space="preserve">
<value>Cannot nest data items in indefinite-length CBOR string contexts.</value>
</data>
<data name="Cbor_Writer_MapIncompleteKeyValuePair" xml:space="preserve">
<value>CBOR map incomplete; each key must be followed by a corresponding value.</value>
</data>
<data name="Cbor_Writer_InvalidUtf8String" xml:space="preserve">
<value>Not a valid UTF-8 encoding.</value>
</data>
<data name="Cbor_Writer_ValueCannotBeInfiniteOrNaN" xml:space="preserve">
<value>Value cannot be infinite or NaN.</value>
</data>
<data name="Cbor_Writer_DecimalOverflow" xml:space="preserve">
<value>Value was either too large or too small for a Decimal.</value>
</data>
<data name="CborContentException_DefaultMessage" xml:space="preserve">
<value>The CBOR encoding is invalid.</value>
</data>
</root>
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/Performance/CodeQuality/Math/Functions/Double/TanDouble.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
namespace Functions
{
public static partial class MathTests
{
// Tests Math.Tan(double) over 5000 iterations for the domain -PI/2, +PI/2
private const double tanDoubleDelta = 0.0004;
private const double tanDoubleExpectedResult = 1.5574077243051505;
public static void TanDoubleTest()
{
var result = 0.0; var value = -1.0;
for (var iteration = 0; iteration < iterations; iteration++)
{
value += tanDoubleDelta;
result += Math.Tan(value);
}
var diff = Math.Abs(tanDoubleExpectedResult - result);
if (diff > doubleEpsilon)
{
throw new Exception($"Expected Result {tanDoubleExpectedResult,20:g17}; Actual Result {result,20:g17}");
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
namespace Functions
{
public static partial class MathTests
{
// Tests Math.Tan(double) over 5000 iterations for the domain -PI/2, +PI/2
private const double tanDoubleDelta = 0.0004;
private const double tanDoubleExpectedResult = 1.5574077243051505;
public static void TanDoubleTest()
{
var result = 0.0; var value = -1.0;
for (var iteration = 0; iteration < iterations; iteration++)
{
value += tanDoubleDelta;
result += Math.Tan(value);
}
var diff = Math.Abs(tanDoubleExpectedResult - result);
if (diff > doubleEpsilon)
{
throw new Exception($"Expected Result {tanDoubleExpectedResult,20:g17}; Actual Result {result,20:g17}");
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.ComponentModel.TypeConverter/tests/Drawing/SizeConverterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class SizeConverterTests : StringTypeConverterTestBase<Size>
{
protected override TypeConverter Converter { get; } = new SizeConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override Size Default => new Size(1, 1);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<Size, Dictionary<string, object>>> CreateInstancePairs
{
get
{
yield return Tuple.Create(new Size(10, 20), new Dictionary<string, object>
{
["Width"] = 10,
["Height"] = 20,
});
yield return Tuple.Create(new Size(-2, 3), new Dictionary<string, object>
{
["Width"] = -2,
["Height"] = 3,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> SizeData =>
new[]
{
new object[] {0, 0},
new object[] {1, 1},
new object[] {-1, 1},
new object[] {1, -1},
new object[] {-1, -1},
new object[] {int.MaxValue, int.MaxValue},
new object[] {int.MinValue, int.MaxValue},
new object[] {int.MaxValue, int.MinValue},
new object[] {int.MinValue, int.MinValue},
};
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFrom(int width, int height)
{
TestConvertFromString(new Size(width, height), $"{width}, {height}");
}
[Theory]
[InlineData("1")]
[InlineData("1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(1, 1)},
new object[] {new PointF(1, 1)},
new object[] {new Size(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {0x10},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertTo(int width, int height)
{
TestConvertToString(new Size(width, height), $"{width}, {height}");
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void ConvertTo_NullCulture()
{
string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new Size(1, 1), typeof(string)));
}
[Fact]
public void CreateInstance_CaseSensitive()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["width"] = 1,
["Height"] = 1,
});
});
}
[Fact]
public void GetProperties()
{
var pt = new Size(1, 1);
var props = Converter.GetProperties(new Size(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1), null);
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal((object)false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1), new Attribute[0]);
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal((object)false, props["IsEmpty"].GetValue(pt));
// Pick an attribute that cannot be applied to properties to make sure everything gets filtered
props = Converter.GetProperties(null, new Size(1, 1), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")});
Assert.Equal(0, props.Count);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFromInvariantString(int width, int height)
{
var point = (Size)Converter.ConvertFromInvariantString($"{width}, {height}");
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFromString(int width, int height)
{
var point =
(Size)Converter.ConvertFromString(string.Format("{0}{2} {1}", width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertToInvariantString(int width, int height)
{
var str = Converter.ConvertToInvariantString(new Size(width, height));
Assert.Equal($"{width}, {height}", str);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertToString(int width, int height)
{
var str = Converter.ConvertToString(new Size(width, height));
Assert.Equal(string.Format("{0}{2} {1}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class SizeConverterTests : StringTypeConverterTestBase<Size>
{
protected override TypeConverter Converter { get; } = new SizeConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override Size Default => new Size(1, 1);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<Size, Dictionary<string, object>>> CreateInstancePairs
{
get
{
yield return Tuple.Create(new Size(10, 20), new Dictionary<string, object>
{
["Width"] = 10,
["Height"] = 20,
});
yield return Tuple.Create(new Size(-2, 3), new Dictionary<string, object>
{
["Width"] = -2,
["Height"] = 3,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> SizeData =>
new[]
{
new object[] {0, 0},
new object[] {1, 1},
new object[] {-1, 1},
new object[] {1, -1},
new object[] {-1, -1},
new object[] {int.MaxValue, int.MaxValue},
new object[] {int.MinValue, int.MaxValue},
new object[] {int.MaxValue, int.MinValue},
new object[] {int.MinValue, int.MinValue},
};
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFrom(int width, int height)
{
TestConvertFromString(new Size(width, height), $"{width}, {height}");
}
[Theory]
[InlineData("1")]
[InlineData("1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(1, 1)},
new object[] {new PointF(1, 1)},
new object[] {new Size(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {0x10},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertTo(int width, int height)
{
TestConvertToString(new Size(width, height), $"{width}, {height}");
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void ConvertTo_NullCulture()
{
string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new Size(1, 1), typeof(string)));
}
[Fact]
public void CreateInstance_CaseSensitive()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["width"] = 1,
["Height"] = 1,
});
});
}
[Fact]
public void GetProperties()
{
var pt = new Size(1, 1);
var props = Converter.GetProperties(new Size(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1), null);
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal((object)false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1), new Attribute[0]);
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal((object)false, props["IsEmpty"].GetValue(pt));
// Pick an attribute that cannot be applied to properties to make sure everything gets filtered
props = Converter.GetProperties(null, new Size(1, 1), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")});
Assert.Equal(0, props.Count);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFromInvariantString(int width, int height)
{
var point = (Size)Converter.ConvertFromInvariantString($"{width}, {height}");
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFromString(int width, int height)
{
var point =
(Size)Converter.ConvertFromString(string.Format("{0}{2} {1}", width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertToInvariantString(int width, int height)
{
var str = Converter.ConvertToInvariantString(new Size(width, height));
Assert.Equal($"{width}, {height}", str);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertToString(int width, int height)
{
var str = Converter.ConvertToString(new Size(width, height));
Assert.Equal(string.Format("{0}{2} {1}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/General/Vector256/CreateScalarUnsafe.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\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 CreateScalarUnsafeInt32()
{
var test = new VectorCreate__CreateScalarUnsafeInt32();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateScalarUnsafeInt32
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Int32 value = TestLibrary.Generator.GetInt32();
Vector256<Int32> result = Vector256.CreateScalarUnsafe(value);
ValidateResult(result, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Int32 value = TestLibrary.Generator.GetInt32();
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.CreateScalarUnsafe), new Type[] { typeof(Int32) })
.Invoke(null, new object[] { value });
ValidateResult((Vector256<Int32>)(result), value);
}
private void ValidateResult(Vector256<Int32> result, Int32 expectedValue, [CallerMemberName] string method = "")
{
Int32[] resultElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValue, method);
}
private void ValidateResult(Int32[] resultElements, Int32 expectedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements[0] != expectedValue)
{
succeeded = false;
}
else
{
for (var i = 1; i < ElementCount; i++)
{
if (false /* value is uninitialized */)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256.CreateScalarUnsafe(Int32): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: {expectedValue}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void CreateScalarUnsafeInt32()
{
var test = new VectorCreate__CreateScalarUnsafeInt32();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateScalarUnsafeInt32
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Int32 value = TestLibrary.Generator.GetInt32();
Vector256<Int32> result = Vector256.CreateScalarUnsafe(value);
ValidateResult(result, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Int32 value = TestLibrary.Generator.GetInt32();
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.CreateScalarUnsafe), new Type[] { typeof(Int32) })
.Invoke(null, new object[] { value });
ValidateResult((Vector256<Int32>)(result), value);
}
private void ValidateResult(Vector256<Int32> result, Int32 expectedValue, [CallerMemberName] string method = "")
{
Int32[] resultElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValue, method);
}
private void ValidateResult(Int32[] resultElements, Int32 expectedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements[0] != expectedValue)
{
succeeded = false;
}
else
{
for (var i = 1; i < ElementCount; i++)
{
if (false /* value is uninitialized */)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256.CreateScalarUnsafe(Int32): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: {expectedValue}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.Xml/tests/XmlReaderLib/TCReadContentAsBase64.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 TCReadContentAsBase64 : TCXMLReaderBaseGeneral
{
// Type is System.Xml.Tests.TCReadContentAsBase64
// Test Case
public override void AddChildren()
{
// for function TestReadBase64_1
{
this.AddChild(new CVariation(TestReadBase64_1) { Attribute = new Variation("ReadBase64 Element with all valid value") });
}
// for function TestReadBase64_2
{
this.AddChild(new CVariation(TestReadBase64_2) { Attribute = new Variation("ReadBase64 Element with all valid Num value") { Pri = 0 } });
}
// for function TestReadBase64_3
{
this.AddChild(new CVariation(TestReadBase64_3) { Attribute = new Variation("ReadBase64 Element with all valid Text value") });
}
// for function TestReadBase64_5
{
this.AddChild(new CVariation(TestReadBase64_5) { Attribute = new Variation("ReadBase64 Element with all valid value (from concatenation), Pri=0") });
}
// for function TestReadBase64_6
{
this.AddChild(new CVariation(TestReadBase64_6) { Attribute = new Variation("ReadBase64 Element with Long valid value (from concatenation), Pri=0") });
}
// for function ReadBase64_7
{
this.AddChild(new CVariation(ReadBase64_7) { Attribute = new Variation("ReadBase64 with count > buffer size") });
}
// for function ReadBase64_8
{
this.AddChild(new CVariation(ReadBase64_8) { Attribute = new Variation("ReadBase64 with count < 0") });
}
// for function ReadBase64_9
{
this.AddChild(new CVariation(ReadBase64_9) { Attribute = new Variation("ReadBase64 with index > buffer size") });
}
// for function ReadBase64_10
{
this.AddChild(new CVariation(ReadBase64_10) { Attribute = new Variation("ReadBase64 with index < 0") });
}
// for function ReadBase64_11
{
this.AddChild(new CVariation(ReadBase64_11) { Attribute = new Variation("ReadBase64 with index + count exceeds buffer") });
}
// for function ReadBase64_12
{
this.AddChild(new CVariation(ReadBase64_12) { Attribute = new Variation("ReadBase64 index & count =0") });
}
// for function TestReadBase64_13
{
this.AddChild(new CVariation(TestReadBase64_13) { Attribute = new Variation("ReadBase64 Element multiple into same buffer (using offset), Pri=0") });
}
// for function TestReadBase64_14
{
this.AddChild(new CVariation(TestReadBase64_14) { Attribute = new Variation("ReadBase64 with buffer == null") });
}
// for function TestReadBase64_15
{
this.AddChild(new CVariation(TestReadBase64_15) { Attribute = new Variation("ReadBase64 after failure") });
}
// for function TestReadBase64_16
{
this.AddChild(new CVariation(TestReadBase64_16) { Attribute = new Variation("Read after partial ReadBase64") { Pri = 0 } });
}
// for function TestReadBase64_17
{
this.AddChild(new CVariation(TestReadBase64_17) { Attribute = new Variation("Current node on multiple calls") });
}
// for function TestTextReadBase64_23
{
this.AddChild(new CVariation(TestTextReadBase64_23) { Attribute = new Variation("ReadBase64 with incomplete sequence") });
}
// for function TestTextReadBase64_24
{
this.AddChild(new CVariation(TestTextReadBase64_24) { Attribute = new Variation("ReadBase64 when end tag doesn't exist") });
}
// for function TestTextReadBase64_26
{
this.AddChild(new CVariation(TestTextReadBase64_26) { Attribute = new Variation("ReadBase64 with whitespace in the middle") });
}
// for function TestTextReadBase64_27
{
this.AddChild(new CVariation(TestTextReadBase64_27) { Attribute = new Variation("ReadBase64 with = in the middle") });
}
// for function ReadBase64BufferOverflowWorksProperly
{
this.AddChild(new CVariation(ReadBase64BufferOverflowWorksProperly) { Attribute = new Variation("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "10000" } } });
this.AddChild(new CVariation(ReadBase64BufferOverflowWorksProperly) { Attribute = new Variation("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "10000000" } } });
this.AddChild(new CVariation(ReadBase64BufferOverflowWorksProperly) { Attribute = new Variation("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "1000000" } } });
}
}
}
}
| // 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 TCReadContentAsBase64 : TCXMLReaderBaseGeneral
{
// Type is System.Xml.Tests.TCReadContentAsBase64
// Test Case
public override void AddChildren()
{
// for function TestReadBase64_1
{
this.AddChild(new CVariation(TestReadBase64_1) { Attribute = new Variation("ReadBase64 Element with all valid value") });
}
// for function TestReadBase64_2
{
this.AddChild(new CVariation(TestReadBase64_2) { Attribute = new Variation("ReadBase64 Element with all valid Num value") { Pri = 0 } });
}
// for function TestReadBase64_3
{
this.AddChild(new CVariation(TestReadBase64_3) { Attribute = new Variation("ReadBase64 Element with all valid Text value") });
}
// for function TestReadBase64_5
{
this.AddChild(new CVariation(TestReadBase64_5) { Attribute = new Variation("ReadBase64 Element with all valid value (from concatenation), Pri=0") });
}
// for function TestReadBase64_6
{
this.AddChild(new CVariation(TestReadBase64_6) { Attribute = new Variation("ReadBase64 Element with Long valid value (from concatenation), Pri=0") });
}
// for function ReadBase64_7
{
this.AddChild(new CVariation(ReadBase64_7) { Attribute = new Variation("ReadBase64 with count > buffer size") });
}
// for function ReadBase64_8
{
this.AddChild(new CVariation(ReadBase64_8) { Attribute = new Variation("ReadBase64 with count < 0") });
}
// for function ReadBase64_9
{
this.AddChild(new CVariation(ReadBase64_9) { Attribute = new Variation("ReadBase64 with index > buffer size") });
}
// for function ReadBase64_10
{
this.AddChild(new CVariation(ReadBase64_10) { Attribute = new Variation("ReadBase64 with index < 0") });
}
// for function ReadBase64_11
{
this.AddChild(new CVariation(ReadBase64_11) { Attribute = new Variation("ReadBase64 with index + count exceeds buffer") });
}
// for function ReadBase64_12
{
this.AddChild(new CVariation(ReadBase64_12) { Attribute = new Variation("ReadBase64 index & count =0") });
}
// for function TestReadBase64_13
{
this.AddChild(new CVariation(TestReadBase64_13) { Attribute = new Variation("ReadBase64 Element multiple into same buffer (using offset), Pri=0") });
}
// for function TestReadBase64_14
{
this.AddChild(new CVariation(TestReadBase64_14) { Attribute = new Variation("ReadBase64 with buffer == null") });
}
// for function TestReadBase64_15
{
this.AddChild(new CVariation(TestReadBase64_15) { Attribute = new Variation("ReadBase64 after failure") });
}
// for function TestReadBase64_16
{
this.AddChild(new CVariation(TestReadBase64_16) { Attribute = new Variation("Read after partial ReadBase64") { Pri = 0 } });
}
// for function TestReadBase64_17
{
this.AddChild(new CVariation(TestReadBase64_17) { Attribute = new Variation("Current node on multiple calls") });
}
// for function TestTextReadBase64_23
{
this.AddChild(new CVariation(TestTextReadBase64_23) { Attribute = new Variation("ReadBase64 with incomplete sequence") });
}
// for function TestTextReadBase64_24
{
this.AddChild(new CVariation(TestTextReadBase64_24) { Attribute = new Variation("ReadBase64 when end tag doesn't exist") });
}
// for function TestTextReadBase64_26
{
this.AddChild(new CVariation(TestTextReadBase64_26) { Attribute = new Variation("ReadBase64 with whitespace in the middle") });
}
// for function TestTextReadBase64_27
{
this.AddChild(new CVariation(TestTextReadBase64_27) { Attribute = new Variation("ReadBase64 with = in the middle") });
}
// for function ReadBase64BufferOverflowWorksProperly
{
this.AddChild(new CVariation(ReadBase64BufferOverflowWorksProperly) { Attribute = new Variation("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "10000" } } });
this.AddChild(new CVariation(ReadBase64BufferOverflowWorksProperly) { Attribute = new Variation("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "10000000" } } });
this.AddChild(new CVariation(ReadBase64BufferOverflowWorksProperly) { Attribute = new Variation("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "1000000" } } });
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniStreamConfigurationSource.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.Configuration.Ini
{
/// <summary>
/// Represents an INI file as an <see cref="IConfigurationSource"/>.
/// Files are simple line structures (<a href="https://en.wikipedia.org/wiki/INI_file">INI Files on Wikipedia</a>)
/// </summary>
/// <examples>
/// [Section:Header]
/// key1=value1
/// key2 = " value2 "
/// ; comment
/// # comment
/// / comment
/// </examples>
public class IniStreamConfigurationSource : StreamConfigurationSource
{
/// <summary>
/// Builds the <see cref="IniConfigurationProvider"/> for this source.
/// </summary>
/// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
/// <returns>An <see cref="IniConfigurationProvider"/></returns>
public override IConfigurationProvider Build(IConfigurationBuilder builder)
=> new IniStreamConfigurationProvider(this);
}
}
| // 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.Configuration.Ini
{
/// <summary>
/// Represents an INI file as an <see cref="IConfigurationSource"/>.
/// Files are simple line structures (<a href="https://en.wikipedia.org/wiki/INI_file">INI Files on Wikipedia</a>)
/// </summary>
/// <examples>
/// [Section:Header]
/// key1=value1
/// key2 = " value2 "
/// ; comment
/// # comment
/// / comment
/// </examples>
public class IniStreamConfigurationSource : StreamConfigurationSource
{
/// <summary>
/// Builds the <see cref="IniConfigurationProvider"/> for this source.
/// </summary>
/// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
/// <returns>An <see cref="IniConfigurationProvider"/></returns>
public override IConfigurationProvider Build(IConfigurationBuilder builder)
=> new IniStreamConfigurationProvider(this);
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/baseservices/compilerservices/dynamicobjectproperties/testapis.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.Collections.Generic;
public class Driver<K, V>
where K : class
where V : class
{
public void BasicAdd(K[] keys, V[] values)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure TryGetValues return true, since the key should be in the table
Test.Eval(tbl.TryGetValue(keys[i], out val), "Err_001 Expected TryGetValue to return true");
if ( val == null && values[i] == null )
{
Test.Eval(true);
}
else if (val != null && values[i] != null && val.Equals(values[i]))
{
Test.Eval(true);
}
else
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_002 The value returned by TryGetValue doesn't match the expected value");
}
}
}
public void AddSameKey //Same Value - Different Value should not matter
(K[] keys, V[] values, int index, int repeat)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < repeat; i++)
{
try
{
tbl.Add(keys[index], values[index]);
Test.Eval(false, "Err_003 Expected to get ArgumentException when invoking Add() on an already existing key");
}
catch (ArgumentException)
{
Test.Eval(true);
}
}
}
public void AddValidations(K[] keys, V[] values, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to add null key
try
{
tbl.Add(null, value);
Test.Eval(false, "Err_004 Expected to get ArgumentNullException when invoking Add() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
}
public void RemoveValidations(K[] keys, V[] values, K key, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// Try to remove key from an empty dictionary
// Remove should return false
Test.Eval(!tbl.Remove(keys[0]), "Err_005 Expected Remove to return false");
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to remove null key
try
{
tbl.Remove(null);
Test.Eval(false, "Err_006 Expected to get ArgumentNullException when invoking Remove() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// Remove non existing key
// Remove should return false
Test.Eval(!tbl.Remove(key), "Err_007 Expected Remove to return false");
}
public void TryGetValueValidations(K[] keys, V[] values, K key, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
V val;
// Try to get key from an empty dictionary
// TryGetValue should return false and value should contian default(TValue)
Test.Eval(!tbl.TryGetValue(keys[0], out val), "Err_008 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_009 Expected val to be null");
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to get null key
try
{
tbl.TryGetValue(null, out val);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// Try to get non existing key
// TryGetValue should return false and value should contian default(TValue)
Test.Eval(!tbl.TryGetValue(key, out val), "Err_011 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_012 Expected val to be null");
}
public Dictionary<string, string> g_stringDict = new Dictionary<string, string>();
public Dictionary<RefX1<int>, string> g_refIntDict = new Dictionary<RefX1<int>, string>();
public Dictionary<RefX1<string>, string> g_refStringDict = new Dictionary<RefX1<string>, string>();
public void GenerateValuesForStringKeys(string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_stringDict.Add(stringArr[i], stringArr[i]);
}
}
public void GenerateValuesForIntRefKeys(RefX1<int>[] refIntArr, string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_refIntDict.Add(refIntArr[i], stringArr[i]);
}
}
public void GenerateValuesForStringRefKeys(RefX1<string>[] refStringArr, string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_refStringDict.Add(refStringArr[i], stringArr[i]);
}
}
//This method is used for the mscorlib defined delegate
// public delegate V CreateValueCallback(K key);
public V CreateValue(K key)
{
if (key is string)
{
return g_stringDict[key as string] as V;
}
else if (key is RefX1<int>)
{
return g_refIntDict[key as RefX1<int>] as V;
}
else if (key is RefX1<string>)
{
return g_refStringDict[key as RefX1<string>] as V;
}
Test.Eval(false, "Err_12a Unknown type of key provided to CreateValue()");
return null;
}
public void VerifyValue(K key, V val)
{
V expectedVal;
if (key is string)
{
expectedVal = g_stringDict[key as string] as V;
}
else if (key is RefX1<int>)
{
expectedVal = g_refIntDict[key as RefX1<int>] as V;
}
else if (key is RefX1<string>)
{
expectedVal = g_refStringDict[key as RefX1<string>] as V;
}
else
{
Test.Eval(false, "Err_12e Incorrect key type supplied");
return;
}
if (!val.Equals(expectedVal))
{
Test.Eval(false, "Err_12b The value returned by TryGetValue doesn't match the expected value for key: " + key +
"\nExpected value: " + expectedVal + "; Actual: " + val);
}
}
public void GetValueValidations(K[] keys, V[] values)
{
ConditionalWeakTable<K,V>.CreateValueCallback valueCallBack =
new ConditionalWeakTable<K,V>.CreateValueCallback(CreateValue);
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
K key = keys[0];
// Get key from an empty dictionary
// GetValue should return the new value generated from CreateValue()
tbl.GetValue(key, valueCallBack);
// check that this opeartion added the (key,value) pair to the dictionary
V val;
Test.Eval(tbl.TryGetValue(key, out val));
VerifyValue(key, val);
// now add values to the table
for (int i = 1; i < keys.Length; i++)
{
try
{
tbl.Add(keys[i], values[i]);
}
catch (ArgumentException) { }
}
// try to get value for a key that already exists in the table
tbl.GetValue(keys[55], valueCallBack);
Test.Eval(tbl.TryGetValue(keys[55], out val));
VerifyValue(keys[55], val);
//try to get null key
try
{
tbl.GetValue(null, valueCallBack);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// try to use null callback
try
{
valueCallBack = null;
tbl.GetValue(key, valueCallBack);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null callback");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
}
// The method first adds some keys to the table
// Then removes a key, checks that it was removed, adds the same key and verifies that it was added.
public void AddRemoveKeyValPair(K[] keys, V[] values, int index, int repeat)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < repeat; i++)
{
// remove existing key and ensure method return true
Test.Eval(tbl.Remove(keys[index]), "Err_013 Expected Remove to return true");
V val;
// since we removed the key, TryGetValue should return false
Test.Eval(!tbl.TryGetValue(keys[index], out val), "Err_014 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_015 Expected val to be null");
// next add the same key
tbl.Add(keys[index], values[index]);
// since we added the key, TryGetValue should return true
Test.Eval(tbl.TryGetValue(keys[index], out val), "Err_016 Expected TryGetValue to return true");
if (val == null && values[i] == null)
{
Test.Eval(true);
}
else if (val != null && values[index] != null && val.Equals(values[index]))
{
Test.Eval(true);
}
else
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_017 The value returned by TryGetValue doesn't match the expected value");
}
}
}
public void BasicGetOrCreateValue(K[] keys)
{
V[] values = new V[keys.Length];
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// assume additions for all values
for (int i = 0; i < keys.Length; i++)
{
values[i] = tbl.GetOrCreateValue(keys[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure TryGetValues return true, since the key should be in the table
Test.Eval(tbl.TryGetValue(keys[i], out val), "Err_018 Expected TryGetValue to return true");
if (val == null || !val.Equals(values[i]))
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_019 The value returned by TryGetValue doesn't match the object created via the default constructor");
}
}
}
public void BasicAddThenGetOrCreateValue(K[] keys, V[] values)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// assume additions for all values
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure GetOrCreateValues the value added (and not a new object)
val = tbl.GetOrCreateValue(keys[i]);
if (val == null || !val.Equals(values[i]))
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_020 The value returned by GetOrCreateValue doesn't match the object added");
}
}
}
}
public class NoDefaultConstructor
{
public NoDefaultConstructor(string str)
{
}
}
public class WithDefaultConstructor
{
private string str;
public WithDefaultConstructor()
{
}
public WithDefaultConstructor(string s)
{
str = s;
}
public new bool Equals(object obj)
{
WithDefaultConstructor wdc = (WithDefaultConstructor)obj;
return (wdc.str.Equals(str));
}
}
public class NegativeTestCases
{
public static void NoDefaulConstructor()
{
ConditionalWeakTable<string,NoDefaultConstructor> tbl = new ConditionalWeakTable<string,NoDefaultConstructor>();
try
{
tbl.GetOrCreateValue("string1");
Test.Eval(false, "Err_021 MissingMethodException execpted");
}
catch (Exception e)
{
Test.Eval(typeof(MissingMethodException) == e.GetType(), "Err_022 Incorrect exception thrown: " + e);
}
}
}
public class TestAPIs
{
public static int Main()
{
Random r = new Random();
try
{
// test for ConditionalWeakTable<string>
Driver<string,string> stringDriver = new Driver<string,string>();
string[] stringArr = new string[100];
for (int i = 0; i < 100; i++)
{
stringArr[i] = "SomeTestString" + i.ToString();
}
// test with generic object
// test for ConditionalWeakTable<RefX1<int>>
Driver<string,RefX1<int>> refIntDriver = new Driver<string,RefX1<int>>();
RefX1<int>[] refIntArr = new RefX1<int>[100];
for (int i = 0; i < 100; i++)
{
refIntArr[i] = new RefX1<int>(i);
}
// test with generic object
// test for ConditionalWeakTable<RefX1<string>>
Driver<string, RefX1<string>> refStringDriver = new Driver<string,RefX1<string>>();
RefX1<string>[] refStringArr = new RefX1<string>[100];
for (int i = 0; i < 100; i++)
{
refStringArr[i] = new RefX1<string>("SomeTestString" + i.ToString());
}
stringDriver.BasicAdd(stringArr, stringArr);
refIntDriver.BasicAdd(stringArr, refIntArr);
refStringDriver.BasicAdd(stringArr, refStringArr);
//===============================================================
// test various boundary conditions
// - add/remove/lookup of null key
// - remove/lookup of non-existing key in an empty dictionary and a non-empty dictionary
stringDriver.AddValidations(stringArr, stringArr, stringArr[0]);
refIntDriver.AddValidations(stringArr, refIntArr, refIntArr[0]);
refStringDriver.AddValidations(stringArr, refStringArr, refStringArr[0]);
//===============================================================
stringDriver.RemoveValidations(stringArr, stringArr, r.Next().ToString(), stringArr[0]);
refIntDriver.RemoveValidations(stringArr, refIntArr, r.Next().ToString(), refIntArr[0]);
refStringDriver.RemoveValidations(stringArr, refStringArr, r.Next().ToString(), refStringArr[0]);
//===============================================================
stringDriver.TryGetValueValidations(stringArr, stringArr, r.Next().ToString(), stringArr[0]);
refIntDriver.TryGetValueValidations(stringArr, refIntArr, r.Next().ToString(), refIntArr[0]);
refStringDriver.TryGetValueValidations(stringArr, refStringArr, r.Next().ToString(), refStringArr[0]);
//===============================================================
// this method generates a dictionary with keys and values to be used for GetValue() method testing
stringDriver.GenerateValuesForStringKeys(stringArr);
stringDriver.GetValueValidations(stringArr, stringArr);
Driver<RefX1<int>, string> refIntDriver2 = new Driver<RefX1<int>, string>();
refIntDriver2.GenerateValuesForIntRefKeys(refIntArr, stringArr);
refIntDriver2.GetValueValidations(refIntArr,stringArr);
Driver<RefX1<string>, string> refStringDriver2 = new Driver<RefX1<string>, string>();
refStringDriver2.GenerateValuesForStringRefKeys(refStringArr, stringArr);
refStringDriver2.GetValueValidations(refStringArr, stringArr);
//===============================================================
stringDriver.AddSameKey(stringArr, stringArr, 0, 2);
stringDriver.AddSameKey(stringArr, stringArr, 99, 3);
stringDriver.AddSameKey(stringArr, stringArr, 50, 4);
stringDriver.AddSameKey(stringArr, stringArr, 1, 5);
stringDriver.AddSameKey(stringArr, stringArr, 98, 6);
refIntDriver.AddSameKey(stringArr, refIntArr, 0, 2);
refIntDriver.AddSameKey(stringArr, refIntArr, 99, 3);
refIntDriver.AddSameKey(stringArr, refIntArr, 50, 4);
refIntDriver.AddSameKey(stringArr, refIntArr, 1, 5);
refIntDriver.AddSameKey(stringArr, refIntArr, 98, 6);
refStringDriver.AddSameKey(stringArr, refStringArr, 0, 2);
refStringDriver.AddSameKey(stringArr, refStringArr, 99, 3);
refStringDriver.AddSameKey(stringArr, refStringArr, 50, 4);
refStringDriver.AddSameKey(stringArr, refStringArr, 1, 5);
refStringDriver.AddSameKey(stringArr, refStringArr, 98, 6);
//===============================================================
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 0, 2);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 99, 3);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 50, 4);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 1, 5);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 98, 6);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 0, 2);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 99, 3);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 50, 4);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 1, 5);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 98, 6);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 0, 2);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 99, 3);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 50, 4);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 1, 5);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 98, 6);
//==============================================================
// new tests for GetOrCreateValue
(new Driver<string, WithDefaultConstructor>()).BasicGetOrCreateValue(stringArr);
WithDefaultConstructor[] wvalues = new WithDefaultConstructor[stringArr.Length];
for (int i=0; i<wvalues.Length; i++) wvalues[i] = new WithDefaultConstructor(stringArr[i]);
(new Driver<string, WithDefaultConstructor>()).BasicAddThenGetOrCreateValue(stringArr, wvalues);
NegativeTestCases.NoDefaulConstructor();
//===============================================================
if (Test.result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 101;
}
}
catch (Exception e)
{
Console.WriteLine("Test threw unexpected exception:\n{0}", e);
return 102;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
public class Driver<K, V>
where K : class
where V : class
{
public void BasicAdd(K[] keys, V[] values)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure TryGetValues return true, since the key should be in the table
Test.Eval(tbl.TryGetValue(keys[i], out val), "Err_001 Expected TryGetValue to return true");
if ( val == null && values[i] == null )
{
Test.Eval(true);
}
else if (val != null && values[i] != null && val.Equals(values[i]))
{
Test.Eval(true);
}
else
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_002 The value returned by TryGetValue doesn't match the expected value");
}
}
}
public void AddSameKey //Same Value - Different Value should not matter
(K[] keys, V[] values, int index, int repeat)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < repeat; i++)
{
try
{
tbl.Add(keys[index], values[index]);
Test.Eval(false, "Err_003 Expected to get ArgumentException when invoking Add() on an already existing key");
}
catch (ArgumentException)
{
Test.Eval(true);
}
}
}
public void AddValidations(K[] keys, V[] values, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to add null key
try
{
tbl.Add(null, value);
Test.Eval(false, "Err_004 Expected to get ArgumentNullException when invoking Add() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
}
public void RemoveValidations(K[] keys, V[] values, K key, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// Try to remove key from an empty dictionary
// Remove should return false
Test.Eval(!tbl.Remove(keys[0]), "Err_005 Expected Remove to return false");
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to remove null key
try
{
tbl.Remove(null);
Test.Eval(false, "Err_006 Expected to get ArgumentNullException when invoking Remove() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// Remove non existing key
// Remove should return false
Test.Eval(!tbl.Remove(key), "Err_007 Expected Remove to return false");
}
public void TryGetValueValidations(K[] keys, V[] values, K key, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
V val;
// Try to get key from an empty dictionary
// TryGetValue should return false and value should contian default(TValue)
Test.Eval(!tbl.TryGetValue(keys[0], out val), "Err_008 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_009 Expected val to be null");
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to get null key
try
{
tbl.TryGetValue(null, out val);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// Try to get non existing key
// TryGetValue should return false and value should contian default(TValue)
Test.Eval(!tbl.TryGetValue(key, out val), "Err_011 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_012 Expected val to be null");
}
public Dictionary<string, string> g_stringDict = new Dictionary<string, string>();
public Dictionary<RefX1<int>, string> g_refIntDict = new Dictionary<RefX1<int>, string>();
public Dictionary<RefX1<string>, string> g_refStringDict = new Dictionary<RefX1<string>, string>();
public void GenerateValuesForStringKeys(string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_stringDict.Add(stringArr[i], stringArr[i]);
}
}
public void GenerateValuesForIntRefKeys(RefX1<int>[] refIntArr, string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_refIntDict.Add(refIntArr[i], stringArr[i]);
}
}
public void GenerateValuesForStringRefKeys(RefX1<string>[] refStringArr, string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_refStringDict.Add(refStringArr[i], stringArr[i]);
}
}
//This method is used for the mscorlib defined delegate
// public delegate V CreateValueCallback(K key);
public V CreateValue(K key)
{
if (key is string)
{
return g_stringDict[key as string] as V;
}
else if (key is RefX1<int>)
{
return g_refIntDict[key as RefX1<int>] as V;
}
else if (key is RefX1<string>)
{
return g_refStringDict[key as RefX1<string>] as V;
}
Test.Eval(false, "Err_12a Unknown type of key provided to CreateValue()");
return null;
}
public void VerifyValue(K key, V val)
{
V expectedVal;
if (key is string)
{
expectedVal = g_stringDict[key as string] as V;
}
else if (key is RefX1<int>)
{
expectedVal = g_refIntDict[key as RefX1<int>] as V;
}
else if (key is RefX1<string>)
{
expectedVal = g_refStringDict[key as RefX1<string>] as V;
}
else
{
Test.Eval(false, "Err_12e Incorrect key type supplied");
return;
}
if (!val.Equals(expectedVal))
{
Test.Eval(false, "Err_12b The value returned by TryGetValue doesn't match the expected value for key: " + key +
"\nExpected value: " + expectedVal + "; Actual: " + val);
}
}
public void GetValueValidations(K[] keys, V[] values)
{
ConditionalWeakTable<K,V>.CreateValueCallback valueCallBack =
new ConditionalWeakTable<K,V>.CreateValueCallback(CreateValue);
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
K key = keys[0];
// Get key from an empty dictionary
// GetValue should return the new value generated from CreateValue()
tbl.GetValue(key, valueCallBack);
// check that this opeartion added the (key,value) pair to the dictionary
V val;
Test.Eval(tbl.TryGetValue(key, out val));
VerifyValue(key, val);
// now add values to the table
for (int i = 1; i < keys.Length; i++)
{
try
{
tbl.Add(keys[i], values[i]);
}
catch (ArgumentException) { }
}
// try to get value for a key that already exists in the table
tbl.GetValue(keys[55], valueCallBack);
Test.Eval(tbl.TryGetValue(keys[55], out val));
VerifyValue(keys[55], val);
//try to get null key
try
{
tbl.GetValue(null, valueCallBack);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// try to use null callback
try
{
valueCallBack = null;
tbl.GetValue(key, valueCallBack);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null callback");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
}
// The method first adds some keys to the table
// Then removes a key, checks that it was removed, adds the same key and verifies that it was added.
public void AddRemoveKeyValPair(K[] keys, V[] values, int index, int repeat)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < repeat; i++)
{
// remove existing key and ensure method return true
Test.Eval(tbl.Remove(keys[index]), "Err_013 Expected Remove to return true");
V val;
// since we removed the key, TryGetValue should return false
Test.Eval(!tbl.TryGetValue(keys[index], out val), "Err_014 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_015 Expected val to be null");
// next add the same key
tbl.Add(keys[index], values[index]);
// since we added the key, TryGetValue should return true
Test.Eval(tbl.TryGetValue(keys[index], out val), "Err_016 Expected TryGetValue to return true");
if (val == null && values[i] == null)
{
Test.Eval(true);
}
else if (val != null && values[index] != null && val.Equals(values[index]))
{
Test.Eval(true);
}
else
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_017 The value returned by TryGetValue doesn't match the expected value");
}
}
}
public void BasicGetOrCreateValue(K[] keys)
{
V[] values = new V[keys.Length];
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// assume additions for all values
for (int i = 0; i < keys.Length; i++)
{
values[i] = tbl.GetOrCreateValue(keys[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure TryGetValues return true, since the key should be in the table
Test.Eval(tbl.TryGetValue(keys[i], out val), "Err_018 Expected TryGetValue to return true");
if (val == null || !val.Equals(values[i]))
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_019 The value returned by TryGetValue doesn't match the object created via the default constructor");
}
}
}
public void BasicAddThenGetOrCreateValue(K[] keys, V[] values)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// assume additions for all values
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure GetOrCreateValues the value added (and not a new object)
val = tbl.GetOrCreateValue(keys[i]);
if (val == null || !val.Equals(values[i]))
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_020 The value returned by GetOrCreateValue doesn't match the object added");
}
}
}
}
public class NoDefaultConstructor
{
public NoDefaultConstructor(string str)
{
}
}
public class WithDefaultConstructor
{
private string str;
public WithDefaultConstructor()
{
}
public WithDefaultConstructor(string s)
{
str = s;
}
public new bool Equals(object obj)
{
WithDefaultConstructor wdc = (WithDefaultConstructor)obj;
return (wdc.str.Equals(str));
}
}
public class NegativeTestCases
{
public static void NoDefaulConstructor()
{
ConditionalWeakTable<string,NoDefaultConstructor> tbl = new ConditionalWeakTable<string,NoDefaultConstructor>();
try
{
tbl.GetOrCreateValue("string1");
Test.Eval(false, "Err_021 MissingMethodException execpted");
}
catch (Exception e)
{
Test.Eval(typeof(MissingMethodException) == e.GetType(), "Err_022 Incorrect exception thrown: " + e);
}
}
}
public class TestAPIs
{
public static int Main()
{
Random r = new Random();
try
{
// test for ConditionalWeakTable<string>
Driver<string,string> stringDriver = new Driver<string,string>();
string[] stringArr = new string[100];
for (int i = 0; i < 100; i++)
{
stringArr[i] = "SomeTestString" + i.ToString();
}
// test with generic object
// test for ConditionalWeakTable<RefX1<int>>
Driver<string,RefX1<int>> refIntDriver = new Driver<string,RefX1<int>>();
RefX1<int>[] refIntArr = new RefX1<int>[100];
for (int i = 0; i < 100; i++)
{
refIntArr[i] = new RefX1<int>(i);
}
// test with generic object
// test for ConditionalWeakTable<RefX1<string>>
Driver<string, RefX1<string>> refStringDriver = new Driver<string,RefX1<string>>();
RefX1<string>[] refStringArr = new RefX1<string>[100];
for (int i = 0; i < 100; i++)
{
refStringArr[i] = new RefX1<string>("SomeTestString" + i.ToString());
}
stringDriver.BasicAdd(stringArr, stringArr);
refIntDriver.BasicAdd(stringArr, refIntArr);
refStringDriver.BasicAdd(stringArr, refStringArr);
//===============================================================
// test various boundary conditions
// - add/remove/lookup of null key
// - remove/lookup of non-existing key in an empty dictionary and a non-empty dictionary
stringDriver.AddValidations(stringArr, stringArr, stringArr[0]);
refIntDriver.AddValidations(stringArr, refIntArr, refIntArr[0]);
refStringDriver.AddValidations(stringArr, refStringArr, refStringArr[0]);
//===============================================================
stringDriver.RemoveValidations(stringArr, stringArr, r.Next().ToString(), stringArr[0]);
refIntDriver.RemoveValidations(stringArr, refIntArr, r.Next().ToString(), refIntArr[0]);
refStringDriver.RemoveValidations(stringArr, refStringArr, r.Next().ToString(), refStringArr[0]);
//===============================================================
stringDriver.TryGetValueValidations(stringArr, stringArr, r.Next().ToString(), stringArr[0]);
refIntDriver.TryGetValueValidations(stringArr, refIntArr, r.Next().ToString(), refIntArr[0]);
refStringDriver.TryGetValueValidations(stringArr, refStringArr, r.Next().ToString(), refStringArr[0]);
//===============================================================
// this method generates a dictionary with keys and values to be used for GetValue() method testing
stringDriver.GenerateValuesForStringKeys(stringArr);
stringDriver.GetValueValidations(stringArr, stringArr);
Driver<RefX1<int>, string> refIntDriver2 = new Driver<RefX1<int>, string>();
refIntDriver2.GenerateValuesForIntRefKeys(refIntArr, stringArr);
refIntDriver2.GetValueValidations(refIntArr,stringArr);
Driver<RefX1<string>, string> refStringDriver2 = new Driver<RefX1<string>, string>();
refStringDriver2.GenerateValuesForStringRefKeys(refStringArr, stringArr);
refStringDriver2.GetValueValidations(refStringArr, stringArr);
//===============================================================
stringDriver.AddSameKey(stringArr, stringArr, 0, 2);
stringDriver.AddSameKey(stringArr, stringArr, 99, 3);
stringDriver.AddSameKey(stringArr, stringArr, 50, 4);
stringDriver.AddSameKey(stringArr, stringArr, 1, 5);
stringDriver.AddSameKey(stringArr, stringArr, 98, 6);
refIntDriver.AddSameKey(stringArr, refIntArr, 0, 2);
refIntDriver.AddSameKey(stringArr, refIntArr, 99, 3);
refIntDriver.AddSameKey(stringArr, refIntArr, 50, 4);
refIntDriver.AddSameKey(stringArr, refIntArr, 1, 5);
refIntDriver.AddSameKey(stringArr, refIntArr, 98, 6);
refStringDriver.AddSameKey(stringArr, refStringArr, 0, 2);
refStringDriver.AddSameKey(stringArr, refStringArr, 99, 3);
refStringDriver.AddSameKey(stringArr, refStringArr, 50, 4);
refStringDriver.AddSameKey(stringArr, refStringArr, 1, 5);
refStringDriver.AddSameKey(stringArr, refStringArr, 98, 6);
//===============================================================
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 0, 2);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 99, 3);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 50, 4);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 1, 5);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 98, 6);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 0, 2);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 99, 3);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 50, 4);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 1, 5);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 98, 6);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 0, 2);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 99, 3);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 50, 4);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 1, 5);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 98, 6);
//==============================================================
// new tests for GetOrCreateValue
(new Driver<string, WithDefaultConstructor>()).BasicGetOrCreateValue(stringArr);
WithDefaultConstructor[] wvalues = new WithDefaultConstructor[stringArr.Length];
for (int i=0; i<wvalues.Length; i++) wvalues[i] = new WithDefaultConstructor(stringArr[i]);
(new Driver<string, WithDefaultConstructor>()).BasicAddThenGetOrCreateValue(stringArr, wvalues);
NegativeTestCases.NoDefaulConstructor();
//===============================================================
if (Test.result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 101;
}
}
catch (Exception e)
{
Console.WriteLine("Test threw unexpected exception:\n{0}", e);
return 102;
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.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.IO;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Security
{
//
// The class maintains the state of the authentication process and the security context.
// It encapsulates security context and does the real work in authentication and
// user data encryption with NEGO SSPI package.
//
internal static partial class NegotiateStreamPal
{
// value should match the Windows sspicli NTE_FAIL value
// defined in winerror.h
private const int NTE_FAIL = unchecked((int)0x80090020);
internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext)
{
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
return negoContext.IsNtlmUsed ? NegotiationInfoClass.NTLM : NegotiationInfoClass.Kerberos;
}
private static byte[] GssWrap(
SafeGssContextHandle? context,
bool encrypt,
ReadOnlySpan<byte> buffer)
{
Interop.NetSecurityNative.GssBuffer encryptedBuffer = default;
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.WrapBuffer(out minorStatus, context, encrypt, buffer, ref encryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return encryptedBuffer.ToByteArray();
}
finally
{
encryptedBuffer.Dispose();
}
}
private static int GssUnwrap(
SafeGssContextHandle? context,
byte[] buffer,
int offset,
int count)
{
Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Decrypt");
Debug.Assert((offset >= 0) && (offset <= buffer.Length), "Invalid input offset passed to Decrypt");
Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Decrypt");
Interop.NetSecurityNative.GssBuffer decryptedBuffer = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.UnwrapBuffer(out minorStatus, context, buffer, offset, count, ref decryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return decryptedBuffer.Copy(buffer, offset);
}
finally
{
decryptedBuffer.Dispose();
}
}
private static bool GssInitSecurityContext(
ref SafeGssContextHandle? context,
SafeGssCredHandle credential,
bool isNtlm,
ChannelBinding? channelBinding,
SafeGssNameHandle? targetName,
Interop.NetSecurityNative.GssFlags inFlags,
byte[]? buffer,
out byte[]? outputBuffer,
out uint outFlags,
out bool isNtlmUsed)
{
outputBuffer = null;
outFlags = 0;
// EstablishSecurityContext is called multiple times in a session.
// In each call, we need to pass the context handle from the previous call.
// For the first call, the context handle will be null.
bool newContext = false;
if (context == null)
{
newContext = true;
context = new SafeGssContextHandle();
}
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
Interop.NetSecurityNative.Status status;
try
{
Interop.NetSecurityNative.Status minorStatus;
if (channelBinding != null)
{
// If a TLS channel binding token (cbt) is available then get the pointer
// to the application specific data.
int appDataOffset = Marshal.SizeOf<SecChannelBindings>();
Debug.Assert(appDataOffset < channelBinding.Size);
IntPtr cbtAppData = channelBinding.DangerousGetHandle() + appDataOffset;
int cbtAppDataSize = channelBinding.Size - appDataOffset;
status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
credential,
ref context,
isNtlm,
cbtAppData,
cbtAppDataSize,
targetName,
(uint)inFlags,
buffer,
(buffer == null) ? 0 : buffer.Length,
ref token,
out outFlags,
out isNtlmUsed);
}
else
{
status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
credential,
ref context,
isNtlm,
targetName,
(uint)inFlags,
buffer,
(buffer == null) ? 0 : buffer.Length,
ref token,
out outFlags,
out isNtlmUsed);
}
if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) &&
(status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
{
if (newContext)
{
context.Dispose();
context = null;
}
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
outputBuffer = token.ToByteArray();
}
finally
{
token.Dispose();
}
return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
}
private static bool GssAcceptSecurityContext(
ref SafeGssContextHandle? context,
SafeGssCredHandle credential,
byte[]? buffer,
out byte[] outputBuffer,
out uint outFlags,
out bool isNtlmUsed)
{
Debug.Assert(credential != null);
bool newContext = false;
if (context == null)
{
newContext = true;
context = new SafeGssContextHandle();
}
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
Interop.NetSecurityNative.Status status;
try
{
Interop.NetSecurityNative.Status minorStatus;
status = Interop.NetSecurityNative.AcceptSecContext(out minorStatus,
credential,
ref context,
buffer,
buffer?.Length ?? 0,
ref token,
out outFlags,
out isNtlmUsed);
if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) &&
(status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
{
if (newContext)
{
context.Dispose();
context = null;
}
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
outputBuffer = token.ToByteArray();
}
finally
{
token.Dispose();
}
return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
}
private static string GssGetUser(
ref SafeGssContextHandle? context)
{
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status status
= Interop.NetSecurityNative.GetUser(out var minorStatus,
context,
ref token);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
ReadOnlySpan<byte> tokenBytes = token.Span;
int length = tokenBytes.Length;
if (length > 0 && tokenBytes[length - 1] == '\0')
{
// Some GSS-API providers (gss-ntlmssp) include the terminating null with strings, so skip that.
tokenBytes = tokenBytes.Slice(0, length - 1);
}
#if NETSTANDARD2_0
return Encoding.UTF8.GetString(tokenBytes.ToArray(), 0, tokenBytes.Length);
#else
return Encoding.UTF8.GetString(tokenBytes);
#endif
}
finally
{
token.Dispose();
}
}
private static SecurityStatusPal EstablishSecurityContext(
SafeFreeNegoCredentials credential,
ref SafeDeleteContext? context,
ChannelBinding? channelBinding,
string? targetName,
ContextFlagsPal inFlags,
byte[]? incomingBlob,
ref byte[]? resultBuffer,
ref ContextFlagsPal outFlags)
{
bool isNtlmOnly = credential.IsNtlmOnly;
if (context == null)
{
if (NetEventSource.Log.IsEnabled())
{
string protocol = isNtlmOnly ? "NTLM" : "SPNEGO";
NetEventSource.Info(context, $"requested protocol = {protocol}, target = {targetName}");
}
context = new SafeDeleteNegoContext(credential, targetName!);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)context;
try
{
Interop.NetSecurityNative.GssFlags inputFlags =
ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(inFlags, isServer: false);
uint outputFlags;
bool isNtlmUsed;
SafeGssContextHandle? contextHandle = negoContext.GssContext;
bool done = GssInitSecurityContext(
ref contextHandle,
credential.GssCredential,
isNtlmOnly,
channelBinding,
negoContext.TargetName,
inputFlags,
incomingBlob,
out resultBuffer,
out outputFlags,
out isNtlmUsed);
if (done)
{
if (NetEventSource.Log.IsEnabled())
{
string protocol = isNtlmOnly ? "NTLM" : isNtlmUsed ? "SPNEGO-NTLM" : "SPNEGO-Kerberos";
NetEventSource.Info(context, $"actual protocol = {protocol}");
}
// Populate protocol used for authentication
negoContext.SetAuthenticationPackage(isNtlmUsed);
}
Debug.Assert(resultBuffer != null, "Unexpected null buffer returned by GssApi");
outFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(
(Interop.NetSecurityNative.GssFlags)outputFlags, isServer: false);
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
// Save the inner context handle for further calls to NetSecurity
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
if (null == negoContext.GssContext)
{
negoContext.SetGssContext(contextHandle!);
}
SecurityStatusPalErrorCode errorCode = done ?
(negoContext.IsNtlmUsed && resultBuffer.Length > 0 ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.CompleteNeeded) :
SecurityStatusPalErrorCode.ContinueNeeded;
return new SecurityStatusPal(errorCode);
}
catch (Exception ex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
internal static SecurityStatusPal InitializeSecurityContext(
ref SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext? securityContext,
string? spn,
ContextFlagsPal requestedContextFlags,
byte[]? incomingBlob,
ChannelBinding? channelBinding,
ref byte[]? resultBlob,
ref ContextFlagsPal contextFlags)
{
SafeFreeNegoCredentials negoCredentialsHandle = (SafeFreeNegoCredentials)credentialsHandle;
if (negoCredentialsHandle.IsDefault && string.IsNullOrEmpty(spn))
{
throw new PlatformNotSupportedException(SR.net_nego_not_supported_empty_target_with_defaultcreds);
}
SecurityStatusPal status = EstablishSecurityContext(
negoCredentialsHandle,
ref securityContext,
channelBinding,
spn,
requestedContextFlags,
incomingBlob,
ref resultBlob,
ref contextFlags);
// Confidentiality flag should not be set if not requested
if (status.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded)
{
ContextFlagsPal mask = ContextFlagsPal.Confidentiality;
if ((requestedContextFlags & mask) != (contextFlags & mask))
{
throw new PlatformNotSupportedException(SR.net_nego_protection_level_not_supported);
}
}
return status;
}
internal static SecurityStatusPal AcceptSecurityContext(
SafeFreeCredentials? credentialsHandle,
ref SafeDeleteContext? securityContext,
ContextFlagsPal requestedContextFlags,
byte[]? incomingBlob,
ChannelBinding? channelBinding,
ref byte[] resultBlob,
ref ContextFlagsPal contextFlags)
{
if (securityContext == null)
{
securityContext = new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle!);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
try
{
SafeGssContextHandle? contextHandle = negoContext.GssContext;
bool done = GssAcceptSecurityContext(
ref contextHandle,
negoContext.AcceptorCredential,
incomingBlob,
out resultBlob,
out uint outputFlags,
out bool isNtlmUsed);
Debug.Assert(resultBlob != null, "Unexpected null buffer returned by GssApi");
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
// Save the inner context handle for further calls to NetSecurity
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
if (null == negoContext.GssContext)
{
negoContext.SetGssContext(contextHandle!);
}
contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(
(Interop.NetSecurityNative.GssFlags)outputFlags, isServer: true);
SecurityStatusPalErrorCode errorCode;
if (done)
{
if (NetEventSource.Log.IsEnabled())
{
string protocol = isNtlmUsed ? "SPNEGO-NTLM" : "SPNEGO-Kerberos";
NetEventSource.Info(securityContext, $"AcceptSecurityContext: actual protocol = {protocol}");
}
negoContext.SetAuthenticationPackage(isNtlmUsed);
errorCode = (isNtlmUsed && resultBlob.Length > 0) ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.CompleteNeeded;
}
else
{
errorCode = SecurityStatusPalErrorCode.ContinueNeeded;
}
return new SecurityStatusPal(errorCode);
}
catch (Interop.NetSecurityNative.GssApiException gex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, gex);
return new SecurityStatusPal(GetErrorCode(gex), gex);
}
catch (Exception ex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
// https://www.gnu.org/software/gss/reference/gss.pdf (page 25)
private static SecurityStatusPalErrorCode GetErrorCode(Interop.NetSecurityNative.GssApiException exception)
{
switch (exception.MajorStatus)
{
case Interop.NetSecurityNative.Status.GSS_S_NO_CRED:
return SecurityStatusPalErrorCode.UnknownCredentials;
case Interop.NetSecurityNative.Status.GSS_S_BAD_BINDINGS:
return SecurityStatusPalErrorCode.BadBinding;
case Interop.NetSecurityNative.Status.GSS_S_CREDENTIALS_EXPIRED:
return SecurityStatusPalErrorCode.CertExpired;
case Interop.NetSecurityNative.Status.GSS_S_DEFECTIVE_TOKEN:
return SecurityStatusPalErrorCode.InvalidToken;
case Interop.NetSecurityNative.Status.GSS_S_DEFECTIVE_CREDENTIAL:
return SecurityStatusPalErrorCode.IncompleteCredentials;
case Interop.NetSecurityNative.Status.GSS_S_BAD_SIG:
return SecurityStatusPalErrorCode.MessageAltered;
case Interop.NetSecurityNative.Status.GSS_S_BAD_MECH:
return SecurityStatusPalErrorCode.Unsupported;
case Interop.NetSecurityNative.Status.GSS_S_NO_CONTEXT:
default:
return SecurityStatusPalErrorCode.InternalError;
}
}
private static string GetUser(
ref SafeDeleteContext securityContext)
{
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
try
{
SafeGssContextHandle? contextHandle = negoContext.GssContext;
return GssGetUser(ref contextHandle);
}
catch (Exception ex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, ex);
throw;
}
}
internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode)
{
return new Win32Exception(NTE_FAIL, (statusCode.Exception != null) ? statusCode.Exception.Message : statusCode.ErrorCode.ToString());
}
internal static int QueryMaxTokenSize(string package)
{
// This value is not used on Unix
return 0;
}
internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer)
{
return AcquireCredentialsHandle(package, isServer, new NetworkCredential(string.Empty, string.Empty, string.Empty));
}
internal static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
{
bool isEmptyCredential = string.IsNullOrWhiteSpace(credential.UserName) ||
string.IsNullOrWhiteSpace(credential.Password);
bool ntlmOnly = string.Equals(package, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase);
if (ntlmOnly && isEmptyCredential)
{
// NTLM authentication is not possible with default credentials which are no-op
throw new PlatformNotSupportedException(SR.net_ntlm_not_possible_default_cred);
}
try
{
return isEmptyCredential ?
new SafeFreeNegoCredentials(false, string.Empty, string.Empty, string.Empty) :
new SafeFreeNegoCredentials(ntlmOnly, credential.UserName, credential.Password, credential.Domain);
}
catch (Exception ex)
{
throw new Win32Exception(NTE_FAIL, ex.Message);
}
}
internal static SecurityStatusPal CompleteAuthToken(
ref SafeDeleteContext? securityContext,
byte[]? incomingBlob)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
internal static int Encrypt(
SafeDeleteContext securityContext,
ReadOnlySpan<byte> buffer,
bool isConfidential,
bool isNtlm,
[NotNull] ref byte[]? output,
uint sequenceNumber)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext) securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, isConfidential, buffer);
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
internal static int Decrypt(
SafeDeleteContext securityContext,
byte[]? buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
out int newOffset,
uint sequenceNumber)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
Debug.Fail("Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
Debug.Fail("Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
newOffset = offset;
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer!, offset, count);
}
internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
Debug.Fail("Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
Debug.Fail("Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer!, offset, count);
}
internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, [AllowNull] ref byte[] output)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext)securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, false, new ReadOnlySpan<byte>(buffer, offset, count));
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
}
}
| // 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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Security
{
//
// The class maintains the state of the authentication process and the security context.
// It encapsulates security context and does the real work in authentication and
// user data encryption with NEGO SSPI package.
//
internal static partial class NegotiateStreamPal
{
// value should match the Windows sspicli NTE_FAIL value
// defined in winerror.h
private const int NTE_FAIL = unchecked((int)0x80090020);
internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext)
{
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
return negoContext.IsNtlmUsed ? NegotiationInfoClass.NTLM : NegotiationInfoClass.Kerberos;
}
private static byte[] GssWrap(
SafeGssContextHandle? context,
bool encrypt,
ReadOnlySpan<byte> buffer)
{
Interop.NetSecurityNative.GssBuffer encryptedBuffer = default;
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.WrapBuffer(out minorStatus, context, encrypt, buffer, ref encryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return encryptedBuffer.ToByteArray();
}
finally
{
encryptedBuffer.Dispose();
}
}
private static int GssUnwrap(
SafeGssContextHandle? context,
byte[] buffer,
int offset,
int count)
{
Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Decrypt");
Debug.Assert((offset >= 0) && (offset <= buffer.Length), "Invalid input offset passed to Decrypt");
Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Decrypt");
Interop.NetSecurityNative.GssBuffer decryptedBuffer = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.UnwrapBuffer(out minorStatus, context, buffer, offset, count, ref decryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return decryptedBuffer.Copy(buffer, offset);
}
finally
{
decryptedBuffer.Dispose();
}
}
private static bool GssInitSecurityContext(
ref SafeGssContextHandle? context,
SafeGssCredHandle credential,
bool isNtlm,
ChannelBinding? channelBinding,
SafeGssNameHandle? targetName,
Interop.NetSecurityNative.GssFlags inFlags,
byte[]? buffer,
out byte[]? outputBuffer,
out uint outFlags,
out bool isNtlmUsed)
{
outputBuffer = null;
outFlags = 0;
// EstablishSecurityContext is called multiple times in a session.
// In each call, we need to pass the context handle from the previous call.
// For the first call, the context handle will be null.
bool newContext = false;
if (context == null)
{
newContext = true;
context = new SafeGssContextHandle();
}
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
Interop.NetSecurityNative.Status status;
try
{
Interop.NetSecurityNative.Status minorStatus;
if (channelBinding != null)
{
// If a TLS channel binding token (cbt) is available then get the pointer
// to the application specific data.
int appDataOffset = Marshal.SizeOf<SecChannelBindings>();
Debug.Assert(appDataOffset < channelBinding.Size);
IntPtr cbtAppData = channelBinding.DangerousGetHandle() + appDataOffset;
int cbtAppDataSize = channelBinding.Size - appDataOffset;
status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
credential,
ref context,
isNtlm,
cbtAppData,
cbtAppDataSize,
targetName,
(uint)inFlags,
buffer,
(buffer == null) ? 0 : buffer.Length,
ref token,
out outFlags,
out isNtlmUsed);
}
else
{
status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
credential,
ref context,
isNtlm,
targetName,
(uint)inFlags,
buffer,
(buffer == null) ? 0 : buffer.Length,
ref token,
out outFlags,
out isNtlmUsed);
}
if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) &&
(status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
{
if (newContext)
{
context.Dispose();
context = null;
}
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
outputBuffer = token.ToByteArray();
}
finally
{
token.Dispose();
}
return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
}
private static bool GssAcceptSecurityContext(
ref SafeGssContextHandle? context,
SafeGssCredHandle credential,
byte[]? buffer,
out byte[] outputBuffer,
out uint outFlags,
out bool isNtlmUsed)
{
Debug.Assert(credential != null);
bool newContext = false;
if (context == null)
{
newContext = true;
context = new SafeGssContextHandle();
}
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
Interop.NetSecurityNative.Status status;
try
{
Interop.NetSecurityNative.Status minorStatus;
status = Interop.NetSecurityNative.AcceptSecContext(out minorStatus,
credential,
ref context,
buffer,
buffer?.Length ?? 0,
ref token,
out outFlags,
out isNtlmUsed);
if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) &&
(status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
{
if (newContext)
{
context.Dispose();
context = null;
}
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
outputBuffer = token.ToByteArray();
}
finally
{
token.Dispose();
}
return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
}
private static string GssGetUser(
ref SafeGssContextHandle? context)
{
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status status
= Interop.NetSecurityNative.GetUser(out var minorStatus,
context,
ref token);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
ReadOnlySpan<byte> tokenBytes = token.Span;
int length = tokenBytes.Length;
if (length > 0 && tokenBytes[length - 1] == '\0')
{
// Some GSS-API providers (gss-ntlmssp) include the terminating null with strings, so skip that.
tokenBytes = tokenBytes.Slice(0, length - 1);
}
#if NETSTANDARD2_0
return Encoding.UTF8.GetString(tokenBytes.ToArray(), 0, tokenBytes.Length);
#else
return Encoding.UTF8.GetString(tokenBytes);
#endif
}
finally
{
token.Dispose();
}
}
private static SecurityStatusPal EstablishSecurityContext(
SafeFreeNegoCredentials credential,
ref SafeDeleteContext? context,
ChannelBinding? channelBinding,
string? targetName,
ContextFlagsPal inFlags,
byte[]? incomingBlob,
ref byte[]? resultBuffer,
ref ContextFlagsPal outFlags)
{
bool isNtlmOnly = credential.IsNtlmOnly;
if (context == null)
{
if (NetEventSource.Log.IsEnabled())
{
string protocol = isNtlmOnly ? "NTLM" : "SPNEGO";
NetEventSource.Info(context, $"requested protocol = {protocol}, target = {targetName}");
}
context = new SafeDeleteNegoContext(credential, targetName!);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)context;
try
{
Interop.NetSecurityNative.GssFlags inputFlags =
ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(inFlags, isServer: false);
uint outputFlags;
bool isNtlmUsed;
SafeGssContextHandle? contextHandle = negoContext.GssContext;
bool done = GssInitSecurityContext(
ref contextHandle,
credential.GssCredential,
isNtlmOnly,
channelBinding,
negoContext.TargetName,
inputFlags,
incomingBlob,
out resultBuffer,
out outputFlags,
out isNtlmUsed);
if (done)
{
if (NetEventSource.Log.IsEnabled())
{
string protocol = isNtlmOnly ? "NTLM" : isNtlmUsed ? "SPNEGO-NTLM" : "SPNEGO-Kerberos";
NetEventSource.Info(context, $"actual protocol = {protocol}");
}
// Populate protocol used for authentication
negoContext.SetAuthenticationPackage(isNtlmUsed);
}
Debug.Assert(resultBuffer != null, "Unexpected null buffer returned by GssApi");
outFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(
(Interop.NetSecurityNative.GssFlags)outputFlags, isServer: false);
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
// Save the inner context handle for further calls to NetSecurity
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
if (null == negoContext.GssContext)
{
negoContext.SetGssContext(contextHandle!);
}
SecurityStatusPalErrorCode errorCode = done ?
(negoContext.IsNtlmUsed && resultBuffer.Length > 0 ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.CompleteNeeded) :
SecurityStatusPalErrorCode.ContinueNeeded;
return new SecurityStatusPal(errorCode);
}
catch (Exception ex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
internal static SecurityStatusPal InitializeSecurityContext(
ref SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext? securityContext,
string? spn,
ContextFlagsPal requestedContextFlags,
byte[]? incomingBlob,
ChannelBinding? channelBinding,
ref byte[]? resultBlob,
ref ContextFlagsPal contextFlags)
{
SafeFreeNegoCredentials negoCredentialsHandle = (SafeFreeNegoCredentials)credentialsHandle;
if (negoCredentialsHandle.IsDefault && string.IsNullOrEmpty(spn))
{
throw new PlatformNotSupportedException(SR.net_nego_not_supported_empty_target_with_defaultcreds);
}
SecurityStatusPal status = EstablishSecurityContext(
negoCredentialsHandle,
ref securityContext,
channelBinding,
spn,
requestedContextFlags,
incomingBlob,
ref resultBlob,
ref contextFlags);
// Confidentiality flag should not be set if not requested
if (status.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded)
{
ContextFlagsPal mask = ContextFlagsPal.Confidentiality;
if ((requestedContextFlags & mask) != (contextFlags & mask))
{
throw new PlatformNotSupportedException(SR.net_nego_protection_level_not_supported);
}
}
return status;
}
internal static SecurityStatusPal AcceptSecurityContext(
SafeFreeCredentials? credentialsHandle,
ref SafeDeleteContext? securityContext,
ContextFlagsPal requestedContextFlags,
byte[]? incomingBlob,
ChannelBinding? channelBinding,
ref byte[] resultBlob,
ref ContextFlagsPal contextFlags)
{
if (securityContext == null)
{
securityContext = new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle!);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
try
{
SafeGssContextHandle? contextHandle = negoContext.GssContext;
bool done = GssAcceptSecurityContext(
ref contextHandle,
negoContext.AcceptorCredential,
incomingBlob,
out resultBlob,
out uint outputFlags,
out bool isNtlmUsed);
Debug.Assert(resultBlob != null, "Unexpected null buffer returned by GssApi");
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
// Save the inner context handle for further calls to NetSecurity
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
if (null == negoContext.GssContext)
{
negoContext.SetGssContext(contextHandle!);
}
contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(
(Interop.NetSecurityNative.GssFlags)outputFlags, isServer: true);
SecurityStatusPalErrorCode errorCode;
if (done)
{
if (NetEventSource.Log.IsEnabled())
{
string protocol = isNtlmUsed ? "SPNEGO-NTLM" : "SPNEGO-Kerberos";
NetEventSource.Info(securityContext, $"AcceptSecurityContext: actual protocol = {protocol}");
}
negoContext.SetAuthenticationPackage(isNtlmUsed);
errorCode = (isNtlmUsed && resultBlob.Length > 0) ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.CompleteNeeded;
}
else
{
errorCode = SecurityStatusPalErrorCode.ContinueNeeded;
}
return new SecurityStatusPal(errorCode);
}
catch (Interop.NetSecurityNative.GssApiException gex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, gex);
return new SecurityStatusPal(GetErrorCode(gex), gex);
}
catch (Exception ex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
// https://www.gnu.org/software/gss/reference/gss.pdf (page 25)
private static SecurityStatusPalErrorCode GetErrorCode(Interop.NetSecurityNative.GssApiException exception)
{
switch (exception.MajorStatus)
{
case Interop.NetSecurityNative.Status.GSS_S_NO_CRED:
return SecurityStatusPalErrorCode.UnknownCredentials;
case Interop.NetSecurityNative.Status.GSS_S_BAD_BINDINGS:
return SecurityStatusPalErrorCode.BadBinding;
case Interop.NetSecurityNative.Status.GSS_S_CREDENTIALS_EXPIRED:
return SecurityStatusPalErrorCode.CertExpired;
case Interop.NetSecurityNative.Status.GSS_S_DEFECTIVE_TOKEN:
return SecurityStatusPalErrorCode.InvalidToken;
case Interop.NetSecurityNative.Status.GSS_S_DEFECTIVE_CREDENTIAL:
return SecurityStatusPalErrorCode.IncompleteCredentials;
case Interop.NetSecurityNative.Status.GSS_S_BAD_SIG:
return SecurityStatusPalErrorCode.MessageAltered;
case Interop.NetSecurityNative.Status.GSS_S_BAD_MECH:
return SecurityStatusPalErrorCode.Unsupported;
case Interop.NetSecurityNative.Status.GSS_S_NO_CONTEXT:
default:
return SecurityStatusPalErrorCode.InternalError;
}
}
private static string GetUser(
ref SafeDeleteContext securityContext)
{
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
try
{
SafeGssContextHandle? contextHandle = negoContext.GssContext;
return GssGetUser(ref contextHandle);
}
catch (Exception ex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, ex);
throw;
}
}
internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode)
{
return new Win32Exception(NTE_FAIL, (statusCode.Exception != null) ? statusCode.Exception.Message : statusCode.ErrorCode.ToString());
}
internal static int QueryMaxTokenSize(string package)
{
// This value is not used on Unix
return 0;
}
internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer)
{
return AcquireCredentialsHandle(package, isServer, new NetworkCredential(string.Empty, string.Empty, string.Empty));
}
internal static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
{
bool isEmptyCredential = string.IsNullOrWhiteSpace(credential.UserName) ||
string.IsNullOrWhiteSpace(credential.Password);
bool ntlmOnly = string.Equals(package, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase);
if (ntlmOnly && isEmptyCredential)
{
// NTLM authentication is not possible with default credentials which are no-op
throw new PlatformNotSupportedException(SR.net_ntlm_not_possible_default_cred);
}
try
{
return isEmptyCredential ?
new SafeFreeNegoCredentials(false, string.Empty, string.Empty, string.Empty) :
new SafeFreeNegoCredentials(ntlmOnly, credential.UserName, credential.Password, credential.Domain);
}
catch (Exception ex)
{
throw new Win32Exception(NTE_FAIL, ex.Message);
}
}
internal static SecurityStatusPal CompleteAuthToken(
ref SafeDeleteContext? securityContext,
byte[]? incomingBlob)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
internal static int Encrypt(
SafeDeleteContext securityContext,
ReadOnlySpan<byte> buffer,
bool isConfidential,
bool isNtlm,
[NotNull] ref byte[]? output,
uint sequenceNumber)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext) securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, isConfidential, buffer);
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
internal static int Decrypt(
SafeDeleteContext securityContext,
byte[]? buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
out int newOffset,
uint sequenceNumber)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
Debug.Fail("Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
Debug.Fail("Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
newOffset = offset;
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer!, offset, count);
}
internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
Debug.Fail("Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
Debug.Fail("Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer!, offset, count);
}
internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, [AllowNull] ref byte[] output)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext)securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, false, new ReadOnlySpan<byte>(buffer, offset, count));
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.CoreLib/src/System/Reflection/IReflect.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.Globalization;
namespace System.Reflection
{
public interface IReflect
{
// Return the requested method if it is implemented by the Reflection object. The
// match is based upon the name and DescriptorInfo which describes the signature
// of the method.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers);
// Return the requested method if it is implemented by the Reflection object. The
// match is based upon the name of the method. If the object implementes multiple methods
// with the same name an AmbiguousMatchException is thrown.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
MethodInfo? GetMethod(string name, BindingFlags bindingAttr);
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
MethodInfo[] GetMethods(BindingFlags bindingAttr);
// Return the requestion field if it is implemented by the Reflection object. The
// match is based upon a name. There cannot be more than a single field with
// a name.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)]
FieldInfo? GetField(string name, BindingFlags bindingAttr);
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)]
FieldInfo[] GetFields(BindingFlags bindingAttr);
// Return the property based upon name. If more than one property has the given
// name an AmbiguousMatchException will be thrown. Returns null if no property
// is found.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
PropertyInfo? GetProperty(string name, BindingFlags bindingAttr);
// Return the property based upon the name and Descriptor info describing the property
// indexing. Return null if no property is found.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers);
// Returns an array of PropertyInfos for all the properties defined on
// the Reflection object.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
PropertyInfo[] GetProperties(BindingFlags bindingAttr);
// Return an array of members which match the passed in name.
[DynamicallyAccessedMembers(System.Type.GetAllMembers)]
MemberInfo[] GetMember(string name, BindingFlags bindingAttr);
// Return an array of all of the members defined for this object.
[DynamicallyAccessedMembers(System.Type.GetAllMembers)]
MemberInfo[] GetMembers(BindingFlags bindingAttr);
// Description of the Binding Process.
// We must invoke a method that is accessible and for which the provided
// parameters have the most specific match. A method may be called if
// 1. The number of parameters in the method declaration equals the number of
// arguments provided to the invocation
// 2. The type of each argument can be converted by the binder to the
// type of the type of the parameter.
//
// The binder will find all of the matching methods. These method are found based
// upon the type of binding requested (MethodInvoke, Get/Set Properties). The set
// of methods is filtered by the name, number of arguments and a set of search modifiers
// defined in the Binder.
//
// After the method is selected, it will be invoked. Accessibility is checked
// at that point. The search may be control which set of methods are searched based
// upon the accessibility attribute associated with the method.
//
// The BindToMethod method is responsible for selecting the method to be invoked.
// For the default binder, the most specific method will be selected.
//
// This will invoke a specific member...
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters);
// Return the underlying Type that represents the IReflect Object. For expando object,
// this is the (Object) IReflectInstance.GetType(). For Type object it is this.
Type UnderlyingSystemType { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace System.Reflection
{
public interface IReflect
{
// Return the requested method if it is implemented by the Reflection object. The
// match is based upon the name and DescriptorInfo which describes the signature
// of the method.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers);
// Return the requested method if it is implemented by the Reflection object. The
// match is based upon the name of the method. If the object implementes multiple methods
// with the same name an AmbiguousMatchException is thrown.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
MethodInfo? GetMethod(string name, BindingFlags bindingAttr);
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
MethodInfo[] GetMethods(BindingFlags bindingAttr);
// Return the requestion field if it is implemented by the Reflection object. The
// match is based upon a name. There cannot be more than a single field with
// a name.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)]
FieldInfo? GetField(string name, BindingFlags bindingAttr);
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)]
FieldInfo[] GetFields(BindingFlags bindingAttr);
// Return the property based upon name. If more than one property has the given
// name an AmbiguousMatchException will be thrown. Returns null if no property
// is found.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
PropertyInfo? GetProperty(string name, BindingFlags bindingAttr);
// Return the property based upon the name and Descriptor info describing the property
// indexing. Return null if no property is found.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers);
// Returns an array of PropertyInfos for all the properties defined on
// the Reflection object.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
PropertyInfo[] GetProperties(BindingFlags bindingAttr);
// Return an array of members which match the passed in name.
[DynamicallyAccessedMembers(System.Type.GetAllMembers)]
MemberInfo[] GetMember(string name, BindingFlags bindingAttr);
// Return an array of all of the members defined for this object.
[DynamicallyAccessedMembers(System.Type.GetAllMembers)]
MemberInfo[] GetMembers(BindingFlags bindingAttr);
// Description of the Binding Process.
// We must invoke a method that is accessible and for which the provided
// parameters have the most specific match. A method may be called if
// 1. The number of parameters in the method declaration equals the number of
// arguments provided to the invocation
// 2. The type of each argument can be converted by the binder to the
// type of the type of the parameter.
//
// The binder will find all of the matching methods. These method are found based
// upon the type of binding requested (MethodInvoke, Get/Set Properties). The set
// of methods is filtered by the name, number of arguments and a set of search modifiers
// defined in the Binder.
//
// After the method is selected, it will be invoked. Accessibility is checked
// at that point. The search may be control which set of methods are searched based
// upon the accessibility attribute associated with the method.
//
// The BindToMethod method is responsible for selecting the method to be invoked.
// For the default binder, the most specific method will be selected.
//
// This will invoke a specific member...
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters);
// Return the underlying Type that represents the IReflect Object. For expando object,
// this is the (Object) IReflectInstance.GetType(). For Type object it is this.
Type UnderlyingSystemType { get; }
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Net.Primitives/src/System/Net/HttpStatusCode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Net
{
// HTTP status codes as per RFC 2616.
public enum HttpStatusCode
{
// Informational 1xx
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
// Successful 2xx
OK = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
IMUsed = 226,
// Redirection 3xx
MultipleChoices = 300,
Ambiguous = 300,
MovedPermanently = 301,
Moved = 301,
Found = 302,
Redirect = 302,
SeeOther = 303,
RedirectMethod = 303,
NotModified = 304,
UseProxy = 305,
Unused = 306,
TemporaryRedirect = 307,
RedirectKeepVerb = 307,
PermanentRedirect = 308,
// Client Error 4xx
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
RequestEntityTooLarge = 413,
RequestUriTooLong = 414,
UnsupportedMediaType = 415,
RequestedRangeNotSatisfiable = 416,
ExpectationFailed = 417,
// From https://github.com/dotnet/runtime/issues/15650:
// "It would be a mistake to add it to .NET now. See golang/go#21326,
// nodejs/node#14644, requests/requests#4238 and aspnet/HttpAbstractions#915".
// ImATeapot = 418
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,
// Server Error 5xx
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Net
{
// HTTP status codes as per RFC 2616.
public enum HttpStatusCode
{
// Informational 1xx
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
// Successful 2xx
OK = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
IMUsed = 226,
// Redirection 3xx
MultipleChoices = 300,
Ambiguous = 300,
MovedPermanently = 301,
Moved = 301,
Found = 302,
Redirect = 302,
SeeOther = 303,
RedirectMethod = 303,
NotModified = 304,
UseProxy = 305,
Unused = 306,
TemporaryRedirect = 307,
RedirectKeepVerb = 307,
PermanentRedirect = 308,
// Client Error 4xx
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
RequestEntityTooLarge = 413,
RequestUriTooLong = 414,
UnsupportedMediaType = 415,
RequestedRangeNotSatisfiable = 416,
ExpectationFailed = 417,
// From https://github.com/dotnet/runtime/issues/15650:
// "It would be a mistake to add it to .NET now. See golang/go#21326,
// nodejs/node#14644, requests/requests#4238 and aspnet/HttpAbstractions#915".
// ImATeapot = 418
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,
// Server Error 5xx
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AddSaturate.Vector128.UInt64.Vector128.UInt64.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.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 AddSaturate_Vector128_UInt64_Vector128_UInt64()
{
var test = new SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64
{
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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64 testClass)
{
var result = AdvSimd.AddSaturate(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.AddSaturate(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddSaturate), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddSaturate), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddSaturate(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64();
var result = AdvSimd.AddSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddSaturate(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AddSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AddSaturate(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddSaturate)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AddSaturate_Vector128_UInt64_Vector128_UInt64()
{
var test = new SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64
{
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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64 testClass)
{
var result = AdvSimd.AddSaturate(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.AddSaturate(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddSaturate), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddSaturate), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddSaturate(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64();
var result = AdvSimd.AddSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddSaturate_Vector128_UInt64_Vector128_UInt64();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddSaturate(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AddSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.AddSaturate(
AdvSimd.LoadVector128((UInt64*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AddSaturate(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddSaturate)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {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,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ZipHigh.Vector128.UInt64.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.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 ZipHigh_Vector128_UInt64()
{
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ZipHigh_Vector128_UInt64
{
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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__ZipHigh_Vector128_UInt64 testClass)
{
var result = AdvSimd.Arm64.ZipHigh(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ZipHigh_Vector128_UInt64 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ZipHigh_Vector128_UInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__ZipHigh_Vector128_UInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.ZipHigh(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipHigh), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipHigh), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ZipHigh(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.ZipHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.ZipHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt64();
var result = AdvSimd.Arm64.ZipHigh(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt64();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ZipHigh(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ZipHigh(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
int index = 0;
int half = RetElementCount / 2;
for (var i = 0; i < RetElementCount; i+=2, index++)
{
if (result[i] != left[index+half] || result[i+1] != right[index+half])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ZipHigh)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ZipHigh_Vector128_UInt64()
{
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ZipHigh_Vector128_UInt64
{
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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__ZipHigh_Vector128_UInt64 testClass)
{
var result = AdvSimd.Arm64.ZipHigh(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ZipHigh_Vector128_UInt64 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ZipHigh_Vector128_UInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__ZipHigh_Vector128_UInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.ZipHigh(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipHigh), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipHigh), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ZipHigh(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.ZipHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.ZipHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt64();
var result = AdvSimd.Arm64.ZipHigh(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt64();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ZipHigh(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ZipHigh(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt64*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
int index = 0;
int half = RetElementCount / 2;
for (var i = 0; i < RetElementCount; i+=2, index++)
{
if (result[i] != left[index+half] || result[i+1] != right[index+half])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ZipHigh)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {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,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/Generics/Parameters/static_assignment_class01.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
public struct ValX0 { }
public struct ValY0 { }
public struct ValX1<T> { }
public struct ValY1<T> { }
public struct ValX2<T, U> { }
public struct ValY2<T, U> { }
public struct ValX3<T, U, V> { }
public struct ValY3<T, U, V> { }
public class RefX0 { }
public class RefY0 { }
public class RefX1<T> { }
public class RefY1<T> { }
public class RefX2<T, U> { }
public class RefY2<T, U> { }
public class RefX3<T, U, V> { }
public class RefY3<T, U, V> { }
public class Gen<T>
{
public static void AssignRef(T tin, ref T tref)
{
tref = tin;
}
public static void AssignOut(T tin, out T tout)
{
tout = tin;
}
}
public class Test_static_assignment_class01
{
public static int counter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
int _int1 = 1;
int _int2 = 2;
Gen<int>.AssignRef(_int1, ref _int2);
Eval(_int1.Equals(_int2));
_int2 = 2;
Gen<int>.AssignOut(_int1, out _int2);
Eval(_int1.Equals(_int2));
double _double1 = 1;
double _double2 = 2;
Gen<double>.AssignRef(_double1, ref _double2);
Eval(_double1.Equals(_double2));
_double2 = 2;
Gen<double>.AssignOut(_double1, out _double2);
Eval(_double1.Equals(_double2));
string _string1 = "string1";
string _string2 = "string2";
Gen<string>.AssignRef(_string1, ref _string2);
Eval(_string1.Equals(_string2));
_string2 = "string2";
Gen<string>.AssignOut(_string1, out _string2);
Eval(_string1.Equals(_string2));
object _object1 = (object)_int1;
object _object2 = (object)_string2;
Gen<object>.AssignRef(_object1, ref _object2);
Eval(_object1.Equals(_object2));
_object2 = (object)_string2;
Gen<object>.AssignOut(_object1, out _object2);
Eval(_object1.Equals(_object2));
Guid _Guid1 = new Guid(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
Guid _Guid2 = new Guid(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
Gen<Guid>.AssignRef(_Guid1, ref _Guid2);
Eval(_Guid1.Equals(_Guid2));
_Guid2 = new Guid(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
Gen<Guid>.AssignOut(_Guid1, out _Guid2);
Eval(_Guid1.Equals(_Guid2));
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
public struct ValX0 { }
public struct ValY0 { }
public struct ValX1<T> { }
public struct ValY1<T> { }
public struct ValX2<T, U> { }
public struct ValY2<T, U> { }
public struct ValX3<T, U, V> { }
public struct ValY3<T, U, V> { }
public class RefX0 { }
public class RefY0 { }
public class RefX1<T> { }
public class RefY1<T> { }
public class RefX2<T, U> { }
public class RefY2<T, U> { }
public class RefX3<T, U, V> { }
public class RefY3<T, U, V> { }
public class Gen<T>
{
public static void AssignRef(T tin, ref T tref)
{
tref = tin;
}
public static void AssignOut(T tin, out T tout)
{
tout = tin;
}
}
public class Test_static_assignment_class01
{
public static int counter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
int _int1 = 1;
int _int2 = 2;
Gen<int>.AssignRef(_int1, ref _int2);
Eval(_int1.Equals(_int2));
_int2 = 2;
Gen<int>.AssignOut(_int1, out _int2);
Eval(_int1.Equals(_int2));
double _double1 = 1;
double _double2 = 2;
Gen<double>.AssignRef(_double1, ref _double2);
Eval(_double1.Equals(_double2));
_double2 = 2;
Gen<double>.AssignOut(_double1, out _double2);
Eval(_double1.Equals(_double2));
string _string1 = "string1";
string _string2 = "string2";
Gen<string>.AssignRef(_string1, ref _string2);
Eval(_string1.Equals(_string2));
_string2 = "string2";
Gen<string>.AssignOut(_string1, out _string2);
Eval(_string1.Equals(_string2));
object _object1 = (object)_int1;
object _object2 = (object)_string2;
Gen<object>.AssignRef(_object1, ref _object2);
Eval(_object1.Equals(_object2));
_object2 = (object)_string2;
Gen<object>.AssignOut(_object1, out _object2);
Eval(_object1.Equals(_object2));
Guid _Guid1 = new Guid(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
Guid _Guid2 = new Guid(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
Gen<Guid>.AssignRef(_Guid1, ref _Guid2);
Eval(_Guid1.Equals(_Guid2));
_Guid2 = new Guid(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
Gen<Guid>.AssignOut(_Guid1, out _Guid2);
Eval(_Guid1.Equals(_Guid2));
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.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
{
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Schema;
using System.Globalization;
internal sealed class XmlNodeReaderNavigator
{
private XmlNode _curNode;
private XmlNode? _elemNode;
private XmlNode _logNode;
private int _attrIndex;
private int _logAttrIndex;
//presave these 2 variables since they shouldn't change.
private readonly XmlNameTable _nameTable;
private readonly XmlDocument _doc;
private int _nAttrInd; //used to identify virtual attributes of DocumentType node and XmlDeclaration node
private const string strPublicID = "PUBLIC";
private const string strSystemID = "SYSTEM";
private const string strVersion = "version";
private const string strStandalone = "standalone";
private const string strEncoding = "encoding";
//caching variables for perf reasons
private int _nDeclarationAttrCount;
private int _nDocTypeAttrCount;
//variables for roll back the moves
private int _nLogLevel;
private int _nLogAttrInd;
private bool _bLogOnAttrVal;
private readonly bool _bCreatedOnAttribute;
internal struct VirtualAttribute
{
internal string? name;
internal string? value;
internal VirtualAttribute(string? name, string? value)
{
this.name = name;
this.value = value;
}
};
internal VirtualAttribute[] decNodeAttributes = {
new VirtualAttribute( null, null ),
new VirtualAttribute( null, null ),
new VirtualAttribute( null, null )
};
internal VirtualAttribute[] docTypeNodeAttributes = {
new VirtualAttribute( null, null ),
new VirtualAttribute( null, null )
};
private bool _bOnAttrVal;
public XmlNodeReaderNavigator(XmlNode node)
{
_curNode = node;
_logNode = node;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Attribute)
{
_elemNode = null;
_attrIndex = -1;
_bCreatedOnAttribute = true;
}
else
{
_elemNode = node;
_attrIndex = -1;
_bCreatedOnAttribute = false;
}
//presave this for pref reason since it shouldn't change.
if (nt == XmlNodeType.Document)
_doc = (XmlDocument)_curNode;
else
_doc = node.OwnerDocument!;
_nameTable = _doc.NameTable;
_nAttrInd = -1;
//initialize the caching variables
_nDeclarationAttrCount = -1;
_nDocTypeAttrCount = -1;
_bOnAttrVal = false;
_bLogOnAttrVal = false;
}
public XmlNodeType NodeType
{
get
{
XmlNodeType nt = _curNode.NodeType;
if (_nAttrInd != -1)
{
Debug.Assert(nt == XmlNodeType.XmlDeclaration || nt == XmlNodeType.DocumentType);
if (_bOnAttrVal)
return XmlNodeType.Text;
else
return XmlNodeType.Attribute;
}
return nt;
}
}
public string NamespaceURI
{
get { return _curNode.NamespaceURI; }
}
public string Name
{
get
{
if (_nAttrInd != -1)
{
Debug.Assert(_curNode.NodeType == XmlNodeType.XmlDeclaration || _curNode.NodeType == XmlNodeType.DocumentType);
if (_bOnAttrVal)
return string.Empty; //Text node's name is String.Empty
else
{
Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount);
if (_curNode.NodeType == XmlNodeType.XmlDeclaration)
return decNodeAttributes[_nAttrInd].name!;
else
return docTypeNodeAttributes[_nAttrInd].name!;
}
}
if (IsLocalNameEmpty(_curNode.NodeType))
return string.Empty;
return _curNode.Name;
}
}
public string LocalName
{
get
{
if (_nAttrInd != -1)
//for the nodes in this case, their LocalName should be the same as their name
return Name;
if (IsLocalNameEmpty(_curNode.NodeType))
return string.Empty;
return _curNode.LocalName;
}
}
internal bool CreatedOnAttribute
{
get
{
return _bCreatedOnAttribute;
}
}
private bool IsLocalNameEmpty(XmlNodeType nt)
{
switch (nt)
{
case XmlNodeType.None:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.EndElement:
case XmlNodeType.EndEntity:
return true;
case XmlNodeType.Element:
case XmlNodeType.Attribute:
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.DocumentType:
case XmlNodeType.Notation:
case XmlNodeType.XmlDeclaration:
return false;
default:
return true;
}
}
public string Prefix
{
get { return _curNode.Prefix; }
}
public bool HasValue
{
//In DOM, DocumentType node and XmlDeclaration node doesn't value
//In XPathNavigator, XmlDeclaration node's value is its InnerText; DocumentType doesn't have value
//In XmlReader, DocumentType node's value is its InternalSubset which is never null ( at least String.Empty )
get
{
if (_nAttrInd != -1)
{
//Pointing at the one of virtual attributes of Declaration or DocumentType nodes
Debug.Assert(_curNode.NodeType == XmlNodeType.XmlDeclaration || _curNode.NodeType == XmlNodeType.DocumentType);
Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount);
return true;
}
if (_curNode.Value != null || _curNode.NodeType == XmlNodeType.DocumentType)
return true;
return false;
}
}
public string Value
{
//See comments in HasValue
get
{
string? retValue;
XmlNodeType nt = _curNode.NodeType;
if (_nAttrInd != -1)
{
//Pointing at the one of virtual attributes of Declaration or DocumentType nodes
Debug.Assert(nt == XmlNodeType.XmlDeclaration || nt == XmlNodeType.DocumentType);
Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount);
if (_curNode.NodeType == XmlNodeType.XmlDeclaration)
return decNodeAttributes[_nAttrInd].value!;
else
return docTypeNodeAttributes[_nAttrInd].value!;
}
if (nt == XmlNodeType.DocumentType)
retValue = ((XmlDocumentType)_curNode).InternalSubset; //in this case nav.Value will be null
else if (nt == XmlNodeType.XmlDeclaration)
{
StringBuilder strb = new StringBuilder(string.Empty);
if (_nDeclarationAttrCount == -1)
InitDecAttr();
for (int i = 0; i < _nDeclarationAttrCount; i++)
{
strb.Append($"{decNodeAttributes[i].name}=\"{decNodeAttributes[i].value}\"");
if (i != (_nDeclarationAttrCount - 1))
strb.Append(' ');
}
retValue = strb.ToString();
}
else
retValue = _curNode.Value;
return (retValue == null) ? string.Empty : retValue;
}
}
public string BaseURI
{
get { return _curNode.BaseURI; }
}
public XmlSpace XmlSpace
{
get { return _curNode.XmlSpace; }
}
public string XmlLang
{
get { return _curNode.XmlLang; }
}
public bool IsEmptyElement
{
get
{
if (_curNode.NodeType == XmlNodeType.Element)
{
return ((XmlElement)_curNode).IsEmpty;
}
return false;
}
}
public bool IsDefault
{
get
{
if (_curNode.NodeType == XmlNodeType.Attribute)
{
return !((XmlAttribute)_curNode).Specified;
}
return false;
}
}
public IXmlSchemaInfo SchemaInfo
{
get
{
return _curNode.SchemaInfo;
}
}
public XmlNameTable NameTable
{
get { return _nameTable; }
}
public int AttributeCount
{
get
{
if (_bCreatedOnAttribute)
return 0;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Element)
return ((XmlElement)_curNode).Attributes.Count;
else if (nt == XmlNodeType.Attribute
|| (_bOnAttrVal && nt != XmlNodeType.XmlDeclaration && nt != XmlNodeType.DocumentType))
return _elemNode!.Attributes!.Count;
else if (nt == XmlNodeType.XmlDeclaration)
{
if (_nDeclarationAttrCount != -1)
return _nDeclarationAttrCount;
InitDecAttr();
return _nDeclarationAttrCount;
}
else if (nt == XmlNodeType.DocumentType)
{
if (_nDocTypeAttrCount != -1)
return _nDocTypeAttrCount;
InitDocTypeAttr();
return _nDocTypeAttrCount;
}
return 0;
}
}
private void CheckIndexCondition(int attributeIndex)
{
if (attributeIndex < 0 || attributeIndex >= AttributeCount)
{
throw new ArgumentOutOfRangeException(nameof(attributeIndex));
}
}
//8 functions below are the helper functions to deal with virtual attributes of XmlDeclaration nodes and DocumentType nodes.
private void InitDecAttr()
{
int i = 0;
string? strTemp = _doc.Version;
if (strTemp != null && strTemp.Length != 0)
{
decNodeAttributes[i].name = strVersion;
decNodeAttributes[i].value = strTemp;
i++;
}
strTemp = _doc.Encoding;
if (strTemp != null && strTemp.Length != 0)
{
decNodeAttributes[i].name = strEncoding;
decNodeAttributes[i].value = strTemp;
i++;
}
strTemp = _doc.Standalone;
if (strTemp != null && strTemp.Length != 0)
{
decNodeAttributes[i].name = strStandalone;
decNodeAttributes[i].value = strTemp;
i++;
}
_nDeclarationAttrCount = i;
}
public string? GetDeclarationAttr(XmlDeclaration decl, string name)
{
//PreCondition: curNode is pointing at Declaration node or one of its virtual attributes
if (name == strVersion)
return decl.Version;
if (name == strEncoding)
return decl.Encoding;
if (name == strStandalone)
return decl.Standalone;
return null;
}
public string? GetDeclarationAttr(int i)
{
if (_nDeclarationAttrCount == -1)
InitDecAttr();
return decNodeAttributes[i].value;
}
public int GetDecAttrInd(string name)
{
if (_nDeclarationAttrCount == -1)
InitDecAttr();
for (int i = 0; i < _nDeclarationAttrCount; i++)
{
if (decNodeAttributes[i].name == name)
return i;
}
return -1;
}
private void InitDocTypeAttr()
{
int i = 0;
XmlDocumentType? docType = _doc.DocumentType;
if (docType == null)
{
_nDocTypeAttrCount = 0;
return;
}
string? strTemp = docType.PublicId;
if (strTemp != null)
{
docTypeNodeAttributes[i].name = strPublicID;
docTypeNodeAttributes[i].value = strTemp;
i++;
}
strTemp = docType.SystemId;
if (strTemp != null)
{
docTypeNodeAttributes[i].name = strSystemID;
docTypeNodeAttributes[i].value = strTemp;
i++;
}
_nDocTypeAttrCount = i;
}
public string? GetDocumentTypeAttr(XmlDocumentType docType, string name)
{
//PreCondition: nav is pointing at DocumentType node or one of its virtual attributes
if (name == strPublicID)
return docType.PublicId;
if (name == strSystemID)
return docType.SystemId;
return null;
}
public string? GetDocumentTypeAttr(int i)
{
if (_nDocTypeAttrCount == -1)
InitDocTypeAttr();
return docTypeNodeAttributes[i].value;
}
public int GetDocTypeAttrInd(string name)
{
if (_nDocTypeAttrCount == -1)
InitDocTypeAttr();
for (int i = 0; i < _nDocTypeAttrCount; i++)
{
if (docTypeNodeAttributes[i].name == name)
return i;
}
return -1;
}
private string? GetAttributeFromElement(XmlElement elem, string name)
{
XmlAttribute? attr = elem.GetAttributeNode(name);
if (attr != null)
return attr.Value;
return null;
}
public string? GetAttribute(string name)
{
if (_bCreatedOnAttribute)
return null;
return _curNode.NodeType switch
{
XmlNodeType.Element => GetAttributeFromElement((XmlElement)_curNode!, name),
XmlNodeType.Attribute => GetAttributeFromElement((XmlElement)_elemNode!, name),
XmlNodeType.XmlDeclaration => GetDeclarationAttr((XmlDeclaration)_curNode, name),
XmlNodeType.DocumentType => GetDocumentTypeAttr((XmlDocumentType)_curNode, name),
_ => null,
};
}
private string? GetAttributeFromElement(XmlElement elem, string name, string? ns)
{
XmlAttribute? attr = elem.GetAttributeNode(name, ns);
if (attr != null)
return attr.Value;
return null;
}
public string? GetAttribute(string name, string ns)
{
if (_bCreatedOnAttribute)
return null;
return _curNode.NodeType switch
{
XmlNodeType.Element => GetAttributeFromElement((XmlElement)_curNode, name, ns),
XmlNodeType.Attribute => GetAttributeFromElement((XmlElement)_elemNode!, name, ns),
XmlNodeType.XmlDeclaration => (ns.Length == 0) ? GetDeclarationAttr((XmlDeclaration)_curNode, name) : null,
XmlNodeType.DocumentType => (ns.Length == 0) ? GetDocumentTypeAttr((XmlDocumentType)_curNode, name) : null,
_ => null,
};
}
public string? GetAttribute(int attributeIndex)
{
if (_bCreatedOnAttribute)
return null;
switch (_curNode.NodeType)
{
case XmlNodeType.Element:
CheckIndexCondition(attributeIndex);
return ((XmlElement)_curNode).Attributes[attributeIndex].Value;
case XmlNodeType.Attribute:
CheckIndexCondition(attributeIndex);
return ((XmlElement)_elemNode!).Attributes[attributeIndex].Value;
case XmlNodeType.XmlDeclaration:
{
CheckIndexCondition(attributeIndex);
return GetDeclarationAttr(attributeIndex);
}
case XmlNodeType.DocumentType:
{
CheckIndexCondition(attributeIndex);
return GetDocumentTypeAttr(attributeIndex);
}
}
throw new ArgumentOutOfRangeException(nameof(attributeIndex)); //for other senario, AttributeCount is 0, i has to be out of range
}
public void LogMove(int level)
{
_logNode = _curNode;
_nLogLevel = level;
_nLogAttrInd = _nAttrInd;
_logAttrIndex = _attrIndex;
_bLogOnAttrVal = _bOnAttrVal;
}
//The function has to be used in pair with ResetMove when the operation fails after LogMove() is
// called because it relies on the values of nOrigLevel, logNav and nOrigAttrInd to be accurate.
public void RollBackMove(ref int level)
{
_curNode = _logNode;
level = _nLogLevel;
_nAttrInd = _nLogAttrInd;
_attrIndex = _logAttrIndex;
_bOnAttrVal = _bLogOnAttrVal;
}
private bool IsOnDeclOrDocType
{
get
{
XmlNodeType nt = _curNode.NodeType;
return (nt == XmlNodeType.XmlDeclaration || nt == XmlNodeType.DocumentType);
}
}
public void ResetToAttribute(ref int level)
{
//the current cursor is pointing at one of the attribute children -- this could be caused by
// the calls to ReadAttributeValue(..)
if (_bCreatedOnAttribute)
return;
if (_bOnAttrVal)
{
if (IsOnDeclOrDocType)
{
level -= 2;
}
else
{
while (_curNode.NodeType != XmlNodeType.Attribute && ((_curNode = _curNode.ParentNode!) != null))
level--;
}
_bOnAttrVal = false;
}
}
public void ResetMove(ref int level, ref XmlNodeType nt)
{
LogMove(level);
if (_bCreatedOnAttribute)
return;
if (_nAttrInd != -1)
{
Debug.Assert(IsOnDeclOrDocType);
if (_bOnAttrVal)
{
level--;
_bOnAttrVal = false;
}
_nLogAttrInd = _nAttrInd;
level--;
_nAttrInd = -1;
nt = _curNode.NodeType;
return;
}
if (_bOnAttrVal && _curNode.NodeType != XmlNodeType.Attribute)
ResetToAttribute(ref level);
if (_curNode.NodeType == XmlNodeType.Attribute)
{
_curNode = ((XmlAttribute)_curNode).OwnerElement!;
_attrIndex = -1;
level--;
nt = XmlNodeType.Element;
}
if (_curNode.NodeType == XmlNodeType.Element)
_elemNode = _curNode;
}
public bool MoveToAttribute(string name)
{
return MoveToAttribute(name, string.Empty);
}
private bool MoveToAttributeFromElement(XmlElement elem, string name, string ns)
{
XmlAttribute? attr;
if (ns.Length == 0)
attr = elem.GetAttributeNode(name);
else
attr = elem.GetAttributeNode(name, ns);
if (attr != null)
{
_bOnAttrVal = false;
_elemNode = elem;
_curNode = attr;
_attrIndex = elem.Attributes.FindNodeOffsetNS(attr);
if (_attrIndex != -1)
{
return true;
}
}
return false;
}
public bool MoveToAttribute(string name, string namespaceURI)
{
if (_bCreatedOnAttribute)
return false;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Element)
return MoveToAttributeFromElement((XmlElement)_curNode, name, namespaceURI);
else if (nt == XmlNodeType.Attribute)
return MoveToAttributeFromElement((XmlElement)_elemNode!, name, namespaceURI);
else if (nt == XmlNodeType.XmlDeclaration && namespaceURI.Length == 0)
{
if ((_nAttrInd = GetDecAttrInd(name)) != -1)
{
_bOnAttrVal = false;
return true;
}
}
else if (nt == XmlNodeType.DocumentType && namespaceURI.Length == 0)
{
if ((_nAttrInd = GetDocTypeAttrInd(name)) != -1)
{
_bOnAttrVal = false;
return true;
}
}
return false;
}
public void MoveToAttribute(int attributeIndex)
{
if (_bCreatedOnAttribute)
return;
XmlAttribute? attr;
switch (_curNode.NodeType)
{
case XmlNodeType.Element:
CheckIndexCondition(attributeIndex);
attr = ((XmlElement)_curNode).Attributes[attributeIndex];
if (attr != null)
{
_elemNode = _curNode;
_curNode = (XmlNode)attr;
_attrIndex = attributeIndex;
}
break;
case XmlNodeType.Attribute:
CheckIndexCondition(attributeIndex);
attr = ((XmlElement)_elemNode!).Attributes[attributeIndex];
if (attr != null)
{
_curNode = (XmlNode)attr;
_attrIndex = attributeIndex;
}
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.DocumentType:
CheckIndexCondition(attributeIndex);
_nAttrInd = attributeIndex;
break;
}
}
public bool MoveToNextAttribute(ref int level)
{
if (_bCreatedOnAttribute)
return false;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Attribute)
{
if (_attrIndex >= (_elemNode!.Attributes!.Count - 1))
return false;
else
{
_curNode = _elemNode.Attributes[++_attrIndex];
return true;
}
}
else if (nt == XmlNodeType.Element)
{
if (_curNode.Attributes!.Count > 0)
{
level++;
_elemNode = _curNode;
_curNode = _curNode.Attributes[0];
_attrIndex = 0;
return true;
}
}
else if (nt == XmlNodeType.XmlDeclaration)
{
if (_nDeclarationAttrCount == -1)
InitDecAttr();
_nAttrInd++;
if (_nAttrInd < _nDeclarationAttrCount)
{
if (_nAttrInd == 0) level++;
_bOnAttrVal = false;
return true;
}
_nAttrInd--;
}
else if (nt == XmlNodeType.DocumentType)
{
if (_nDocTypeAttrCount == -1)
InitDocTypeAttr();
_nAttrInd++;
if (_nAttrInd < _nDocTypeAttrCount)
{
if (_nAttrInd == 0) level++;
_bOnAttrVal = false;
return true;
}
_nAttrInd--;
}
return false;
}
public bool MoveToParent()
{
XmlNode? parent = _curNode.ParentNode;
if (parent != null)
{
_curNode = parent;
if (!_bOnAttrVal)
_attrIndex = 0;
return true;
}
return false;
}
public bool MoveToFirstChild()
{
XmlNode? firstChild = _curNode.FirstChild;
if (firstChild != null)
{
_curNode = firstChild;
if (!_bOnAttrVal)
_attrIndex = -1;
return true;
}
return false;
}
private bool MoveToNextSibling(XmlNode node)
{
XmlNode? nextSibling = node.NextSibling;
if (nextSibling != null)
{
_curNode = nextSibling;
if (!_bOnAttrVal)
_attrIndex = -1;
return true;
}
return false;
}
public bool MoveToNext()
{
if (_curNode.NodeType != XmlNodeType.Attribute)
return MoveToNextSibling(_curNode);
else
return MoveToNextSibling(_elemNode!);
}
public bool MoveToElement()
{
if (_bCreatedOnAttribute)
return false;
switch (_curNode.NodeType)
{
case XmlNodeType.Attribute:
if (_elemNode != null)
{
_curNode = _elemNode;
_attrIndex = -1;
return true;
}
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.DocumentType:
{
if (_nAttrInd != -1)
{
_nAttrInd = -1;
return true;
}
break;
}
}
return false;
}
public string? LookupNamespace(string prefix)
{
if (_bCreatedOnAttribute)
return null;
if (prefix == "xmlns")
{
return _nameTable.Add(XmlReservedNs.NsXmlNs);
}
if (prefix == "xml")
{
return _nameTable.Add(XmlReservedNs.NsXml);
}
// construct the name of the xmlns attribute
string attrName;
if (prefix == null)
prefix = string.Empty;
if (prefix.Length == 0)
attrName = "xmlns";
else
attrName = $"xmlns:{prefix}";
// walk up the XmlNode parent chain, looking for the xmlns attribute
XmlNode? node = _curNode;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttribute? attr = elem.GetAttributeNode(attrName);
if (attr != null)
{
return attr.Value;
}
}
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
continue;
}
node = node.ParentNode;
}
if (prefix.Length == 0)
{
return string.Empty;
}
return null;
}
internal string? DefaultLookupNamespace(string prefix)
{
if (!_bCreatedOnAttribute)
{
if (prefix == "xmlns")
{
return _nameTable.Add(XmlReservedNs.NsXmlNs);
}
if (prefix == "xml")
{
return _nameTable.Add(XmlReservedNs.NsXml);
}
if (prefix == string.Empty)
{
return _nameTable.Add(string.Empty);
}
}
return null;
}
internal string? LookupPrefix(string namespaceName)
{
if (_bCreatedOnAttribute || namespaceName == null)
{
return null;
}
if (namespaceName == XmlReservedNs.NsXmlNs)
{
return _nameTable.Add("xmlns");
}
if (namespaceName == XmlReservedNs.NsXml)
{
return _nameTable.Add("xml");
}
if (namespaceName.Length == 0)
{
return string.Empty;
}
// walk up the XmlNode parent chain, looking for the xmlns attribute with namespaceName value
XmlNode? node = _curNode;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute a = attrs[i];
if (a.Value == namespaceName)
{
if (a.Prefix.Length == 0 && a.LocalName == "xmlns")
{
if (LookupNamespace(string.Empty) == namespaceName)
{
return string.Empty;
}
}
else if (a.Prefix == "xmlns")
{
string pref = a.LocalName;
if (LookupNamespace(pref) == namespaceName)
{
return _nameTable.Add(pref);
}
}
}
}
}
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
continue;
}
node = node.ParentNode;
}
return null;
}
internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (_bCreatedOnAttribute)
return dict;
// walk up the XmlNode parent chain and add all namespace declarations to the dictionary
XmlNode? node = _curNode;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute a = attrs[i];
if (a.LocalName == "xmlns" && a.Prefix.Length == 0)
{
if (!dict.ContainsKey(string.Empty))
{
dict.Add(_nameTable.Add(string.Empty), _nameTable.Add(a.Value!));
}
}
else if (a.Prefix == "xmlns")
{
string localName = a.LocalName;
if (!dict.ContainsKey(localName))
{
dict.Add(_nameTable.Add(localName), _nameTable.Add(a.Value!));
}
}
}
}
if (scope == XmlNamespaceScope.Local)
{
break;
}
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
continue;
}
node = node.ParentNode;
}
if (scope != XmlNamespaceScope.Local)
{
if (dict.ContainsKey(string.Empty) && dict[string.Empty] == string.Empty)
{
dict.Remove(string.Empty);
}
if (scope == XmlNamespaceScope.All)
{
dict.Add(_nameTable.Add("xml"), _nameTable.Add(XmlReservedNs.NsXml));
}
}
return dict;
}
public bool ReadAttributeValue(ref int level, ref bool bResolveEntity, ref XmlNodeType nt)
{
if (_nAttrInd != -1)
{
Debug.Assert(_curNode.NodeType == XmlNodeType.XmlDeclaration || _curNode.NodeType == XmlNodeType.DocumentType);
if (!_bOnAttrVal)
{
_bOnAttrVal = true;
level++;
nt = XmlNodeType.Text;
return true;
}
return false;
}
if (_curNode.NodeType == XmlNodeType.Attribute)
{
XmlNode? firstChild = _curNode.FirstChild;
if (firstChild != null)
{
_curNode = firstChild;
nt = _curNode.NodeType;
level++;
_bOnAttrVal = true;
return true;
}
}
else if (_bOnAttrVal)
{
XmlNode? nextSibling;
if (_curNode.NodeType == XmlNodeType.EntityReference && bResolveEntity)
{
//going down to ent ref node
_curNode = _curNode.FirstChild!;
Debug.Assert(_curNode != null);
nt = _curNode.NodeType;
level++;
bResolveEntity = false;
return true;
}
else
nextSibling = _curNode.NextSibling;
if (nextSibling == null)
{
XmlNode? parentNode = _curNode.ParentNode;
//Check if its parent is entity ref node is sufficient, because in this senario, ent ref node can't have more than 1 level of children that are not other ent ref nodes
if (parentNode != null && parentNode.NodeType == XmlNodeType.EntityReference)
{
//come back from ent ref node
_curNode = parentNode;
nt = XmlNodeType.EndEntity;
level--;
return true;
}
}
if (nextSibling != null)
{
_curNode = nextSibling;
nt = _curNode.NodeType;
return true;
}
else
return false;
}
return false;
}
public XmlDocument Document
{
get
{
return _doc;
}
}
}
// Represents a reader that provides fast, non-cached forward only stream access
// to XML data in an XmlDocument or a specific XmlNode within an XmlDocument.
public class XmlNodeReader : XmlReader, IXmlNamespaceResolver
{
private readonly XmlNodeReaderNavigator _readerNav;
private XmlNodeType _nodeType; // nodeType of the node that the reader is currently positioned on
private int _curDepth; // depth of attrNav ( also functions as reader's depth )
private ReadState _readState; // current reader's state
private bool _fEOF; // flag to show if reaches the end of file
//mark to the state that EntityReference node is supposed to be resolved
private bool _bResolveEntity;
private bool _bStartFromDocument;
private bool _bInReadBinary;
private ReadContentAsBinaryHelper? _readBinaryHelper;
// Creates an instance of the XmlNodeReader class using the specified XmlNode.
public XmlNodeReader(XmlNode node!!)
{
_readerNav = new XmlNodeReaderNavigator(node);
_curDepth = 0;
_readState = ReadState.Initial;
_fEOF = false;
_nodeType = XmlNodeType.None;
_bResolveEntity = false;
_bStartFromDocument = false;
}
//function returns if the reader currently in valid reading states
internal bool IsInReadingStates()
{
return (_readState == ReadState.Interactive); // || readState == ReadState.EndOfFile
}
//
// Node Properties
//
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get { return (IsInReadingStates()) ? _nodeType : XmlNodeType.None; }
}
// Gets the name of
// the current node, including the namespace prefix.
public override string Name
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.Name;
}
}
// Gets the name of the current node without the namespace prefix.
public override string LocalName
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.LocalName;
}
}
// Gets the namespace URN (as defined in the W3C Namespace Specification)
// of the current namespace scope.
public override string NamespaceURI
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.NamespaceURI;
}
}
// Gets the namespace prefix associated with the current node.
public override string Prefix
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.Prefix;
}
}
// Gets a value indicating whether
// XmlNodeReader.Value has a value to return.
public override bool HasValue
{
get
{
if (!IsInReadingStates())
return false;
return _readerNav.HasValue;
}
}
// Gets the text value of the current node.
public override string Value
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.Value;
}
}
// Gets the depth of the
// current node in the XML element stack.
public override int Depth
{
get { return _curDepth; }
}
// Gets the base URI of the current node.
public override string BaseURI
{
get { return _readerNav.BaseURI; }
}
public override bool CanResolveEntity
{
get { return true; }
}
// Gets a value indicating whether the current
// node is an empty element (for example, <MyElement/>.
public override bool IsEmptyElement
{
get
{
if (!IsInReadingStates())
return false;
return _readerNav.IsEmptyElement;
}
}
// Gets a value indicating whether the current node is an
// attribute that was generated from the default value defined
// in the DTD or schema.
public override bool IsDefault
{
get
{
if (!IsInReadingStates())
return false;
return _readerNav.IsDefault;
}
}
// Gets the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
if (!IsInReadingStates())
return XmlSpace.None;
return _readerNav.XmlSpace;
}
}
// Gets the current xml:lang scope.
public override string XmlLang
{
// Assume everything is in Unicode
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.XmlLang;
}
}
public override IXmlSchemaInfo? SchemaInfo
{
get
{
if (!IsInReadingStates())
{
return null;
}
return _readerNav.SchemaInfo;
}
}
//
// Attribute Accessors
//
// Gets the number of attributes on the current node.
public override int AttributeCount
{
get
{
if (!IsInReadingStates() || _nodeType == XmlNodeType.EndElement)
return 0;
return _readerNav.AttributeCount;
}
}
// Gets the value of the attribute with the specified name.
public override string? GetAttribute(string name)
{
//if not on Attribute, only element node could have attributes
if (!IsInReadingStates())
return null;
return _readerNav.GetAttribute(name);
}
// Gets the value of the attribute with the specified name and namespace.
public override string? GetAttribute(string name, string? namespaceURI)
{
//if not on Attribute, only element node could have attributes
if (!IsInReadingStates())
return null;
string ns = (namespaceURI == null) ? string.Empty : namespaceURI;
return _readerNav.GetAttribute(name, ns);
}
// Gets the value of the attribute with the specified index.
public override string GetAttribute(int attributeIndex)
{
if (!IsInReadingStates())
throw new ArgumentOutOfRangeException(nameof(attributeIndex));
//CheckIndexCondition( i );
//Debug.Assert( nav.NodeType == XmlNodeType.Element );
return _readerNav.GetAttribute(attributeIndex)!;
}
// Moves to the attribute with the specified name.
public override bool MoveToAttribute(string name)
{
if (!IsInReadingStates())
return false;
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
if (_readerNav.MoveToAttribute(name))
{ //, ref curDepth ) ) {
_curDepth++;
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
// Moves to the attribute with the specified name and namespace.
public override bool MoveToAttribute(string name, string? namespaceURI)
{
if (!IsInReadingStates())
return false;
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
string ns = (namespaceURI == null) ? string.Empty : namespaceURI;
if (_readerNav.MoveToAttribute(name, ns))
{ //, ref curDepth ) ) {
_curDepth++;
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
// Moves to the attribute with the specified index.
public override void MoveToAttribute(int attributeIndex)
{
if (!IsInReadingStates())
throw new ArgumentOutOfRangeException(nameof(attributeIndex));
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
try
{
if (AttributeCount > 0)
{
_readerNav.MoveToAttribute(attributeIndex);
if (_bInReadBinary)
{
FinishReadBinary();
}
}
else
throw new ArgumentOutOfRangeException(nameof(attributeIndex));
}
catch
{
_readerNav.RollBackMove(ref _curDepth);
throw;
}
_curDepth++;
_nodeType = _readerNav.NodeType;
}
// Moves to the first attribute.
public override bool MoveToFirstAttribute()
{
if (!IsInReadingStates())
return false;
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
if (AttributeCount > 0)
{
_readerNav.MoveToAttribute(0);
_curDepth++;
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
// Moves to the next attribute.
public override bool MoveToNextAttribute()
{
if (!IsInReadingStates() || _nodeType == XmlNodeType.EndElement)
return false;
_readerNav.LogMove(_curDepth);
_readerNav.ResetToAttribute(ref _curDepth);
if (_readerNav.MoveToNextAttribute(ref _curDepth))
{
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
// Moves to the element that contains the current attribute node.
public override bool MoveToElement()
{
if (!IsInReadingStates())
return false;
_readerNav.LogMove(_curDepth);
_readerNav.ResetToAttribute(ref _curDepth);
if (_readerNav.MoveToElement())
{
_curDepth--;
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
//
// Moving through the Stream
//
// Reads the next node from the stream.
public override bool Read()
{
return Read(false);
}
private bool Read(bool fSkipChildren)
{
if (_fEOF)
return false;
if (_readState == ReadState.Initial)
{
// if nav is pointing at the document node, start with its children
// otherwise,start with the node.
if ((_readerNav.NodeType == XmlNodeType.Document) || (_readerNav.NodeType == XmlNodeType.DocumentFragment))
{
_bStartFromDocument = true;
if (!ReadNextNode(fSkipChildren))
{
_readState = ReadState.Error;
return false;
}
}
ReSetReadingMarks();
_readState = ReadState.Interactive;
_nodeType = _readerNav.NodeType;
//_depth = 0;
_curDepth = 0;
return true;
}
if (_bInReadBinary)
{
FinishReadBinary();
}
if ((_readerNav.CreatedOnAttribute))
return false;
ReSetReadingMarks();
if (ReadNextNode(fSkipChildren))
{
return true;
}
else
{
if (_readState == ReadState.Initial || _readState == ReadState.Interactive)
_readState = ReadState.Error;
if (_readState == ReadState.EndOfFile)
_nodeType = XmlNodeType.None;
return false;
}
}
private bool ReadNextNode(bool fSkipChildren)
{
if (_readState != ReadState.Interactive && _readState != ReadState.Initial)
{
_nodeType = XmlNodeType.None;
return false;
}
bool bDrillDown = !fSkipChildren;
XmlNodeType nt = _readerNav.NodeType;
//only goes down when nav.NodeType is of element or of document at the initial state, other nav.NodeType will not be parsed down
//if nav.NodeType is of EntityReference, ResolveEntity() could be called to get the content parsed;
bDrillDown = bDrillDown
&& (_nodeType != XmlNodeType.EndElement)
&& (_nodeType != XmlNodeType.EndEntity)
&& (nt == XmlNodeType.Element || (nt == XmlNodeType.EntityReference && _bResolveEntity) ||
(((_readerNav.NodeType == XmlNodeType.Document) || (_readerNav.NodeType == XmlNodeType.DocumentFragment)) && _readState == ReadState.Initial));
//first see if there are children of current node, so to move down
if (bDrillDown)
{
if (_readerNav.MoveToFirstChild())
{
_nodeType = _readerNav.NodeType;
_curDepth++;
if (_bResolveEntity)
_bResolveEntity = false;
return true;
}
else if (_readerNav.NodeType == XmlNodeType.Element
&& !_readerNav.IsEmptyElement)
{
_nodeType = XmlNodeType.EndElement;
return true;
}
else if (_readerNav.NodeType == XmlNodeType.EntityReference && _bResolveEntity)
{
_bResolveEntity = false;
_nodeType = XmlNodeType.EndEntity;
return true;
}
// if fails to move to it 1st Child, try to move to next below
return ReadForward(fSkipChildren);
}
else
{
if (_readerNav.NodeType == XmlNodeType.EntityReference && _bResolveEntity)
{
//The only way to get to here is because Skip() is called directly after ResolveEntity()
// in this case, user wants to skip the first Child of EntityRef node and fSkipChildren is true
// We want to pointing to the first child node.
if (_readerNav.MoveToFirstChild())
{
_nodeType = _readerNav.NodeType;
_curDepth++;
}
else
{
_nodeType = XmlNodeType.EndEntity;
}
_bResolveEntity = false;
return true;
}
}
return ReadForward(fSkipChildren); //has to get the next node by moving forward
}
private void SetEndOfFile()
{
_fEOF = true;
_readState = ReadState.EndOfFile;
_nodeType = XmlNodeType.None;
}
private bool ReadAtZeroLevel(bool fSkipChildren)
{
Debug.Assert(_curDepth == 0);
if (!fSkipChildren
&& _nodeType != XmlNodeType.EndElement
&& _readerNav.NodeType == XmlNodeType.Element
&& !_readerNav.IsEmptyElement)
{
_nodeType = XmlNodeType.EndElement;
return true;
}
else
{
SetEndOfFile();
return false;
}
}
private bool ReadForward(bool fSkipChildren)
{
if (_readState == ReadState.Error)
return false;
if (!_bStartFromDocument && _curDepth == 0)
{
//already on top most node and we shouldn't move to next
return ReadAtZeroLevel(fSkipChildren);
}
//else either we are not on top level or we are starting from the document at the very beginning in which case
// we will need to read all the "top" most nodes
if (_readerNav.MoveToNext())
{
_nodeType = _readerNav.NodeType;
return true;
}
else
{
//need to check its parent
if (_curDepth == 0)
return ReadAtZeroLevel(fSkipChildren);
if (_readerNav.MoveToParent())
{
if (_readerNav.NodeType == XmlNodeType.Element)
{
_curDepth--;
_nodeType = XmlNodeType.EndElement;
return true;
}
else if (_readerNav.NodeType == XmlNodeType.EntityReference)
{
//coming back from entity reference node -- must be getting down through call ResolveEntity()
_curDepth--;
_nodeType = XmlNodeType.EndEntity;
return true;
}
return true;
}
}
return false;
}
//the function reset the marks used for ReadChars() and MoveToAttribute(...), ReadAttributeValue(...)
private void ReSetReadingMarks()
{
//_attrValInd = -1;
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
//attrNav.MoveTo( nav );
//curDepth = _depth;
}
// Gets a value indicating whether the reader is positioned at the
// end of the stream.
public override bool EOF
{
get { return (_readState != ReadState.Closed) && _fEOF; }
}
// Closes the stream, changes the XmlNodeReader.ReadState
// to Closed, and sets all the properties back to zero.
public override void Close()
{
_readState = ReadState.Closed;
}
// Gets the read state of the stream.
public override ReadState ReadState
{
get { return _readState; }
}
// Skips to the end tag of the current element.
public override void Skip()
{
Read(true);
}
// Reads the contents of an element as a string.
public override string ReadString()
{
if ((this.NodeType == XmlNodeType.EntityReference) && _bResolveEntity)
{
if (!this.Read())
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
return base.ReadString();
}
//
// Partial Content Read Methods
//
// Gets a value indicating whether the current node
// has any attributes.
public override bool HasAttributes
{
get
{
return (AttributeCount > 0);
}
}
//
// Nametable and Namespace Helpers
//
// Gets the XmlNameTable associated with this implementation.
public override XmlNameTable NameTable
{
get { return _readerNav.NameTable; }
}
// Resolves a namespace prefix in the current element's scope.
public override string? LookupNamespace(string prefix)
{
if (!IsInReadingStates())
return null;
string? ns = _readerNav.LookupNamespace(prefix);
if (ns != null && ns.Length == 0)
{
return null;
}
return ns;
}
// Resolves the entity reference for nodes of NodeType EntityReference.
public override void ResolveEntity()
{
if (!IsInReadingStates() || (_nodeType != XmlNodeType.EntityReference))
throw new InvalidOperationException(SR.Xnr_ResolveEntity);
_bResolveEntity = true;
}
// Parses the attribute value into one or more Text and/or
// EntityReference node types.
public override bool ReadAttributeValue()
{
if (!IsInReadingStates())
return false;
if (_readerNav.ReadAttributeValue(ref _curDepth, ref _bResolveEntity, ref _nodeType))
{
_bInReadBinary = false;
return true;
}
return false;
}
public override bool CanReadBinaryContent
{
get
{
return true;
}
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
if (_readState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (!_bInReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
// turn off bInReadBinary in order to have a normal Read() behavior when called from readBinaryHelper
_bInReadBinary = false;
// call to the helper
int readCount = _readBinaryHelper!.ReadContentAsBase64(buffer, index, count);
// turn on bInReadBinary in again and return
_bInReadBinary = true;
return readCount;
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
if (_readState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (!_bInReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
// turn off bInReadBinary in order to have a normal Read() behavior when called from readBinaryHelper
_bInReadBinary = false;
// call to the helper
int readCount = _readBinaryHelper!.ReadContentAsBinHex(buffer, index, count);
// turn on bInReadBinary in again and return
_bInReadBinary = true;
return readCount;
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
if (_readState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (!_bInReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
// turn off bInReadBinary in order to have a normal Read() behavior when called from readBinaryHelper
_bInReadBinary = false;
// call to the helper
int readCount = _readBinaryHelper!.ReadElementContentAsBase64(buffer, index, count);
// turn on bInReadBinary in again and return
_bInReadBinary = true;
return readCount;
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
if (_readState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (!_bInReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
// turn off bInReadBinary in order to have a normal Read() behavior when called from readBinaryHelper
_bInReadBinary = false;
// call to the helper
int readCount = _readBinaryHelper!.ReadElementContentAsBinHex(buffer, index, count);
// turn on bInReadBinary in again and return
_bInReadBinary = true;
return readCount;
}
private void FinishReadBinary()
{
_bInReadBinary = false;
_readBinaryHelper!.Finish();
}
//
// IXmlNamespaceResolver
//
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return _readerNav.GetNamespacesInScope(scope);
}
string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _readerNav.LookupPrefix(namespaceName);
}
string? IXmlNamespaceResolver.LookupNamespace(string prefix)
{
if (!IsInReadingStates())
{
return _readerNav.DefaultLookupNamespace(prefix);
}
string? ns = _readerNav.LookupNamespace(prefix);
if (ns != null)
{
ns = _readerNav.NameTable.Add(ns);
}
return ns;
}
// DTD/Schema info used by XmlReader.GetDtdSchemaInfo()
internal override IDtdInfo? DtdInfo
{
get
{
return _readerNav.Document.DtdSchemaInfo;
}
}
}
}
| // 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
{
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Schema;
using System.Globalization;
internal sealed class XmlNodeReaderNavigator
{
private XmlNode _curNode;
private XmlNode? _elemNode;
private XmlNode _logNode;
private int _attrIndex;
private int _logAttrIndex;
//presave these 2 variables since they shouldn't change.
private readonly XmlNameTable _nameTable;
private readonly XmlDocument _doc;
private int _nAttrInd; //used to identify virtual attributes of DocumentType node and XmlDeclaration node
private const string strPublicID = "PUBLIC";
private const string strSystemID = "SYSTEM";
private const string strVersion = "version";
private const string strStandalone = "standalone";
private const string strEncoding = "encoding";
//caching variables for perf reasons
private int _nDeclarationAttrCount;
private int _nDocTypeAttrCount;
//variables for roll back the moves
private int _nLogLevel;
private int _nLogAttrInd;
private bool _bLogOnAttrVal;
private readonly bool _bCreatedOnAttribute;
internal struct VirtualAttribute
{
internal string? name;
internal string? value;
internal VirtualAttribute(string? name, string? value)
{
this.name = name;
this.value = value;
}
};
internal VirtualAttribute[] decNodeAttributes = {
new VirtualAttribute( null, null ),
new VirtualAttribute( null, null ),
new VirtualAttribute( null, null )
};
internal VirtualAttribute[] docTypeNodeAttributes = {
new VirtualAttribute( null, null ),
new VirtualAttribute( null, null )
};
private bool _bOnAttrVal;
public XmlNodeReaderNavigator(XmlNode node)
{
_curNode = node;
_logNode = node;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Attribute)
{
_elemNode = null;
_attrIndex = -1;
_bCreatedOnAttribute = true;
}
else
{
_elemNode = node;
_attrIndex = -1;
_bCreatedOnAttribute = false;
}
//presave this for pref reason since it shouldn't change.
if (nt == XmlNodeType.Document)
_doc = (XmlDocument)_curNode;
else
_doc = node.OwnerDocument!;
_nameTable = _doc.NameTable;
_nAttrInd = -1;
//initialize the caching variables
_nDeclarationAttrCount = -1;
_nDocTypeAttrCount = -1;
_bOnAttrVal = false;
_bLogOnAttrVal = false;
}
public XmlNodeType NodeType
{
get
{
XmlNodeType nt = _curNode.NodeType;
if (_nAttrInd != -1)
{
Debug.Assert(nt == XmlNodeType.XmlDeclaration || nt == XmlNodeType.DocumentType);
if (_bOnAttrVal)
return XmlNodeType.Text;
else
return XmlNodeType.Attribute;
}
return nt;
}
}
public string NamespaceURI
{
get { return _curNode.NamespaceURI; }
}
public string Name
{
get
{
if (_nAttrInd != -1)
{
Debug.Assert(_curNode.NodeType == XmlNodeType.XmlDeclaration || _curNode.NodeType == XmlNodeType.DocumentType);
if (_bOnAttrVal)
return string.Empty; //Text node's name is String.Empty
else
{
Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount);
if (_curNode.NodeType == XmlNodeType.XmlDeclaration)
return decNodeAttributes[_nAttrInd].name!;
else
return docTypeNodeAttributes[_nAttrInd].name!;
}
}
if (IsLocalNameEmpty(_curNode.NodeType))
return string.Empty;
return _curNode.Name;
}
}
public string LocalName
{
get
{
if (_nAttrInd != -1)
//for the nodes in this case, their LocalName should be the same as their name
return Name;
if (IsLocalNameEmpty(_curNode.NodeType))
return string.Empty;
return _curNode.LocalName;
}
}
internal bool CreatedOnAttribute
{
get
{
return _bCreatedOnAttribute;
}
}
private bool IsLocalNameEmpty(XmlNodeType nt)
{
switch (nt)
{
case XmlNodeType.None:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.EndElement:
case XmlNodeType.EndEntity:
return true;
case XmlNodeType.Element:
case XmlNodeType.Attribute:
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.DocumentType:
case XmlNodeType.Notation:
case XmlNodeType.XmlDeclaration:
return false;
default:
return true;
}
}
public string Prefix
{
get { return _curNode.Prefix; }
}
public bool HasValue
{
//In DOM, DocumentType node and XmlDeclaration node doesn't value
//In XPathNavigator, XmlDeclaration node's value is its InnerText; DocumentType doesn't have value
//In XmlReader, DocumentType node's value is its InternalSubset which is never null ( at least String.Empty )
get
{
if (_nAttrInd != -1)
{
//Pointing at the one of virtual attributes of Declaration or DocumentType nodes
Debug.Assert(_curNode.NodeType == XmlNodeType.XmlDeclaration || _curNode.NodeType == XmlNodeType.DocumentType);
Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount);
return true;
}
if (_curNode.Value != null || _curNode.NodeType == XmlNodeType.DocumentType)
return true;
return false;
}
}
public string Value
{
//See comments in HasValue
get
{
string? retValue;
XmlNodeType nt = _curNode.NodeType;
if (_nAttrInd != -1)
{
//Pointing at the one of virtual attributes of Declaration or DocumentType nodes
Debug.Assert(nt == XmlNodeType.XmlDeclaration || nt == XmlNodeType.DocumentType);
Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount);
if (_curNode.NodeType == XmlNodeType.XmlDeclaration)
return decNodeAttributes[_nAttrInd].value!;
else
return docTypeNodeAttributes[_nAttrInd].value!;
}
if (nt == XmlNodeType.DocumentType)
retValue = ((XmlDocumentType)_curNode).InternalSubset; //in this case nav.Value will be null
else if (nt == XmlNodeType.XmlDeclaration)
{
StringBuilder strb = new StringBuilder(string.Empty);
if (_nDeclarationAttrCount == -1)
InitDecAttr();
for (int i = 0; i < _nDeclarationAttrCount; i++)
{
strb.Append($"{decNodeAttributes[i].name}=\"{decNodeAttributes[i].value}\"");
if (i != (_nDeclarationAttrCount - 1))
strb.Append(' ');
}
retValue = strb.ToString();
}
else
retValue = _curNode.Value;
return (retValue == null) ? string.Empty : retValue;
}
}
public string BaseURI
{
get { return _curNode.BaseURI; }
}
public XmlSpace XmlSpace
{
get { return _curNode.XmlSpace; }
}
public string XmlLang
{
get { return _curNode.XmlLang; }
}
public bool IsEmptyElement
{
get
{
if (_curNode.NodeType == XmlNodeType.Element)
{
return ((XmlElement)_curNode).IsEmpty;
}
return false;
}
}
public bool IsDefault
{
get
{
if (_curNode.NodeType == XmlNodeType.Attribute)
{
return !((XmlAttribute)_curNode).Specified;
}
return false;
}
}
public IXmlSchemaInfo SchemaInfo
{
get
{
return _curNode.SchemaInfo;
}
}
public XmlNameTable NameTable
{
get { return _nameTable; }
}
public int AttributeCount
{
get
{
if (_bCreatedOnAttribute)
return 0;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Element)
return ((XmlElement)_curNode).Attributes.Count;
else if (nt == XmlNodeType.Attribute
|| (_bOnAttrVal && nt != XmlNodeType.XmlDeclaration && nt != XmlNodeType.DocumentType))
return _elemNode!.Attributes!.Count;
else if (nt == XmlNodeType.XmlDeclaration)
{
if (_nDeclarationAttrCount != -1)
return _nDeclarationAttrCount;
InitDecAttr();
return _nDeclarationAttrCount;
}
else if (nt == XmlNodeType.DocumentType)
{
if (_nDocTypeAttrCount != -1)
return _nDocTypeAttrCount;
InitDocTypeAttr();
return _nDocTypeAttrCount;
}
return 0;
}
}
private void CheckIndexCondition(int attributeIndex)
{
if (attributeIndex < 0 || attributeIndex >= AttributeCount)
{
throw new ArgumentOutOfRangeException(nameof(attributeIndex));
}
}
//8 functions below are the helper functions to deal with virtual attributes of XmlDeclaration nodes and DocumentType nodes.
private void InitDecAttr()
{
int i = 0;
string? strTemp = _doc.Version;
if (strTemp != null && strTemp.Length != 0)
{
decNodeAttributes[i].name = strVersion;
decNodeAttributes[i].value = strTemp;
i++;
}
strTemp = _doc.Encoding;
if (strTemp != null && strTemp.Length != 0)
{
decNodeAttributes[i].name = strEncoding;
decNodeAttributes[i].value = strTemp;
i++;
}
strTemp = _doc.Standalone;
if (strTemp != null && strTemp.Length != 0)
{
decNodeAttributes[i].name = strStandalone;
decNodeAttributes[i].value = strTemp;
i++;
}
_nDeclarationAttrCount = i;
}
public string? GetDeclarationAttr(XmlDeclaration decl, string name)
{
//PreCondition: curNode is pointing at Declaration node or one of its virtual attributes
if (name == strVersion)
return decl.Version;
if (name == strEncoding)
return decl.Encoding;
if (name == strStandalone)
return decl.Standalone;
return null;
}
public string? GetDeclarationAttr(int i)
{
if (_nDeclarationAttrCount == -1)
InitDecAttr();
return decNodeAttributes[i].value;
}
public int GetDecAttrInd(string name)
{
if (_nDeclarationAttrCount == -1)
InitDecAttr();
for (int i = 0; i < _nDeclarationAttrCount; i++)
{
if (decNodeAttributes[i].name == name)
return i;
}
return -1;
}
private void InitDocTypeAttr()
{
int i = 0;
XmlDocumentType? docType = _doc.DocumentType;
if (docType == null)
{
_nDocTypeAttrCount = 0;
return;
}
string? strTemp = docType.PublicId;
if (strTemp != null)
{
docTypeNodeAttributes[i].name = strPublicID;
docTypeNodeAttributes[i].value = strTemp;
i++;
}
strTemp = docType.SystemId;
if (strTemp != null)
{
docTypeNodeAttributes[i].name = strSystemID;
docTypeNodeAttributes[i].value = strTemp;
i++;
}
_nDocTypeAttrCount = i;
}
public string? GetDocumentTypeAttr(XmlDocumentType docType, string name)
{
//PreCondition: nav is pointing at DocumentType node or one of its virtual attributes
if (name == strPublicID)
return docType.PublicId;
if (name == strSystemID)
return docType.SystemId;
return null;
}
public string? GetDocumentTypeAttr(int i)
{
if (_nDocTypeAttrCount == -1)
InitDocTypeAttr();
return docTypeNodeAttributes[i].value;
}
public int GetDocTypeAttrInd(string name)
{
if (_nDocTypeAttrCount == -1)
InitDocTypeAttr();
for (int i = 0; i < _nDocTypeAttrCount; i++)
{
if (docTypeNodeAttributes[i].name == name)
return i;
}
return -1;
}
private string? GetAttributeFromElement(XmlElement elem, string name)
{
XmlAttribute? attr = elem.GetAttributeNode(name);
if (attr != null)
return attr.Value;
return null;
}
public string? GetAttribute(string name)
{
if (_bCreatedOnAttribute)
return null;
return _curNode.NodeType switch
{
XmlNodeType.Element => GetAttributeFromElement((XmlElement)_curNode!, name),
XmlNodeType.Attribute => GetAttributeFromElement((XmlElement)_elemNode!, name),
XmlNodeType.XmlDeclaration => GetDeclarationAttr((XmlDeclaration)_curNode, name),
XmlNodeType.DocumentType => GetDocumentTypeAttr((XmlDocumentType)_curNode, name),
_ => null,
};
}
private string? GetAttributeFromElement(XmlElement elem, string name, string? ns)
{
XmlAttribute? attr = elem.GetAttributeNode(name, ns);
if (attr != null)
return attr.Value;
return null;
}
public string? GetAttribute(string name, string ns)
{
if (_bCreatedOnAttribute)
return null;
return _curNode.NodeType switch
{
XmlNodeType.Element => GetAttributeFromElement((XmlElement)_curNode, name, ns),
XmlNodeType.Attribute => GetAttributeFromElement((XmlElement)_elemNode!, name, ns),
XmlNodeType.XmlDeclaration => (ns.Length == 0) ? GetDeclarationAttr((XmlDeclaration)_curNode, name) : null,
XmlNodeType.DocumentType => (ns.Length == 0) ? GetDocumentTypeAttr((XmlDocumentType)_curNode, name) : null,
_ => null,
};
}
public string? GetAttribute(int attributeIndex)
{
if (_bCreatedOnAttribute)
return null;
switch (_curNode.NodeType)
{
case XmlNodeType.Element:
CheckIndexCondition(attributeIndex);
return ((XmlElement)_curNode).Attributes[attributeIndex].Value;
case XmlNodeType.Attribute:
CheckIndexCondition(attributeIndex);
return ((XmlElement)_elemNode!).Attributes[attributeIndex].Value;
case XmlNodeType.XmlDeclaration:
{
CheckIndexCondition(attributeIndex);
return GetDeclarationAttr(attributeIndex);
}
case XmlNodeType.DocumentType:
{
CheckIndexCondition(attributeIndex);
return GetDocumentTypeAttr(attributeIndex);
}
}
throw new ArgumentOutOfRangeException(nameof(attributeIndex)); //for other senario, AttributeCount is 0, i has to be out of range
}
public void LogMove(int level)
{
_logNode = _curNode;
_nLogLevel = level;
_nLogAttrInd = _nAttrInd;
_logAttrIndex = _attrIndex;
_bLogOnAttrVal = _bOnAttrVal;
}
//The function has to be used in pair with ResetMove when the operation fails after LogMove() is
// called because it relies on the values of nOrigLevel, logNav and nOrigAttrInd to be accurate.
public void RollBackMove(ref int level)
{
_curNode = _logNode;
level = _nLogLevel;
_nAttrInd = _nLogAttrInd;
_attrIndex = _logAttrIndex;
_bOnAttrVal = _bLogOnAttrVal;
}
private bool IsOnDeclOrDocType
{
get
{
XmlNodeType nt = _curNode.NodeType;
return (nt == XmlNodeType.XmlDeclaration || nt == XmlNodeType.DocumentType);
}
}
public void ResetToAttribute(ref int level)
{
//the current cursor is pointing at one of the attribute children -- this could be caused by
// the calls to ReadAttributeValue(..)
if (_bCreatedOnAttribute)
return;
if (_bOnAttrVal)
{
if (IsOnDeclOrDocType)
{
level -= 2;
}
else
{
while (_curNode.NodeType != XmlNodeType.Attribute && ((_curNode = _curNode.ParentNode!) != null))
level--;
}
_bOnAttrVal = false;
}
}
public void ResetMove(ref int level, ref XmlNodeType nt)
{
LogMove(level);
if (_bCreatedOnAttribute)
return;
if (_nAttrInd != -1)
{
Debug.Assert(IsOnDeclOrDocType);
if (_bOnAttrVal)
{
level--;
_bOnAttrVal = false;
}
_nLogAttrInd = _nAttrInd;
level--;
_nAttrInd = -1;
nt = _curNode.NodeType;
return;
}
if (_bOnAttrVal && _curNode.NodeType != XmlNodeType.Attribute)
ResetToAttribute(ref level);
if (_curNode.NodeType == XmlNodeType.Attribute)
{
_curNode = ((XmlAttribute)_curNode).OwnerElement!;
_attrIndex = -1;
level--;
nt = XmlNodeType.Element;
}
if (_curNode.NodeType == XmlNodeType.Element)
_elemNode = _curNode;
}
public bool MoveToAttribute(string name)
{
return MoveToAttribute(name, string.Empty);
}
private bool MoveToAttributeFromElement(XmlElement elem, string name, string ns)
{
XmlAttribute? attr;
if (ns.Length == 0)
attr = elem.GetAttributeNode(name);
else
attr = elem.GetAttributeNode(name, ns);
if (attr != null)
{
_bOnAttrVal = false;
_elemNode = elem;
_curNode = attr;
_attrIndex = elem.Attributes.FindNodeOffsetNS(attr);
if (_attrIndex != -1)
{
return true;
}
}
return false;
}
public bool MoveToAttribute(string name, string namespaceURI)
{
if (_bCreatedOnAttribute)
return false;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Element)
return MoveToAttributeFromElement((XmlElement)_curNode, name, namespaceURI);
else if (nt == XmlNodeType.Attribute)
return MoveToAttributeFromElement((XmlElement)_elemNode!, name, namespaceURI);
else if (nt == XmlNodeType.XmlDeclaration && namespaceURI.Length == 0)
{
if ((_nAttrInd = GetDecAttrInd(name)) != -1)
{
_bOnAttrVal = false;
return true;
}
}
else if (nt == XmlNodeType.DocumentType && namespaceURI.Length == 0)
{
if ((_nAttrInd = GetDocTypeAttrInd(name)) != -1)
{
_bOnAttrVal = false;
return true;
}
}
return false;
}
public void MoveToAttribute(int attributeIndex)
{
if (_bCreatedOnAttribute)
return;
XmlAttribute? attr;
switch (_curNode.NodeType)
{
case XmlNodeType.Element:
CheckIndexCondition(attributeIndex);
attr = ((XmlElement)_curNode).Attributes[attributeIndex];
if (attr != null)
{
_elemNode = _curNode;
_curNode = (XmlNode)attr;
_attrIndex = attributeIndex;
}
break;
case XmlNodeType.Attribute:
CheckIndexCondition(attributeIndex);
attr = ((XmlElement)_elemNode!).Attributes[attributeIndex];
if (attr != null)
{
_curNode = (XmlNode)attr;
_attrIndex = attributeIndex;
}
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.DocumentType:
CheckIndexCondition(attributeIndex);
_nAttrInd = attributeIndex;
break;
}
}
public bool MoveToNextAttribute(ref int level)
{
if (_bCreatedOnAttribute)
return false;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Attribute)
{
if (_attrIndex >= (_elemNode!.Attributes!.Count - 1))
return false;
else
{
_curNode = _elemNode.Attributes[++_attrIndex];
return true;
}
}
else if (nt == XmlNodeType.Element)
{
if (_curNode.Attributes!.Count > 0)
{
level++;
_elemNode = _curNode;
_curNode = _curNode.Attributes[0];
_attrIndex = 0;
return true;
}
}
else if (nt == XmlNodeType.XmlDeclaration)
{
if (_nDeclarationAttrCount == -1)
InitDecAttr();
_nAttrInd++;
if (_nAttrInd < _nDeclarationAttrCount)
{
if (_nAttrInd == 0) level++;
_bOnAttrVal = false;
return true;
}
_nAttrInd--;
}
else if (nt == XmlNodeType.DocumentType)
{
if (_nDocTypeAttrCount == -1)
InitDocTypeAttr();
_nAttrInd++;
if (_nAttrInd < _nDocTypeAttrCount)
{
if (_nAttrInd == 0) level++;
_bOnAttrVal = false;
return true;
}
_nAttrInd--;
}
return false;
}
public bool MoveToParent()
{
XmlNode? parent = _curNode.ParentNode;
if (parent != null)
{
_curNode = parent;
if (!_bOnAttrVal)
_attrIndex = 0;
return true;
}
return false;
}
public bool MoveToFirstChild()
{
XmlNode? firstChild = _curNode.FirstChild;
if (firstChild != null)
{
_curNode = firstChild;
if (!_bOnAttrVal)
_attrIndex = -1;
return true;
}
return false;
}
private bool MoveToNextSibling(XmlNode node)
{
XmlNode? nextSibling = node.NextSibling;
if (nextSibling != null)
{
_curNode = nextSibling;
if (!_bOnAttrVal)
_attrIndex = -1;
return true;
}
return false;
}
public bool MoveToNext()
{
if (_curNode.NodeType != XmlNodeType.Attribute)
return MoveToNextSibling(_curNode);
else
return MoveToNextSibling(_elemNode!);
}
public bool MoveToElement()
{
if (_bCreatedOnAttribute)
return false;
switch (_curNode.NodeType)
{
case XmlNodeType.Attribute:
if (_elemNode != null)
{
_curNode = _elemNode;
_attrIndex = -1;
return true;
}
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.DocumentType:
{
if (_nAttrInd != -1)
{
_nAttrInd = -1;
return true;
}
break;
}
}
return false;
}
public string? LookupNamespace(string prefix)
{
if (_bCreatedOnAttribute)
return null;
if (prefix == "xmlns")
{
return _nameTable.Add(XmlReservedNs.NsXmlNs);
}
if (prefix == "xml")
{
return _nameTable.Add(XmlReservedNs.NsXml);
}
// construct the name of the xmlns attribute
string attrName;
if (prefix == null)
prefix = string.Empty;
if (prefix.Length == 0)
attrName = "xmlns";
else
attrName = $"xmlns:{prefix}";
// walk up the XmlNode parent chain, looking for the xmlns attribute
XmlNode? node = _curNode;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttribute? attr = elem.GetAttributeNode(attrName);
if (attr != null)
{
return attr.Value;
}
}
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
continue;
}
node = node.ParentNode;
}
if (prefix.Length == 0)
{
return string.Empty;
}
return null;
}
internal string? DefaultLookupNamespace(string prefix)
{
if (!_bCreatedOnAttribute)
{
if (prefix == "xmlns")
{
return _nameTable.Add(XmlReservedNs.NsXmlNs);
}
if (prefix == "xml")
{
return _nameTable.Add(XmlReservedNs.NsXml);
}
if (prefix == string.Empty)
{
return _nameTable.Add(string.Empty);
}
}
return null;
}
internal string? LookupPrefix(string namespaceName)
{
if (_bCreatedOnAttribute || namespaceName == null)
{
return null;
}
if (namespaceName == XmlReservedNs.NsXmlNs)
{
return _nameTable.Add("xmlns");
}
if (namespaceName == XmlReservedNs.NsXml)
{
return _nameTable.Add("xml");
}
if (namespaceName.Length == 0)
{
return string.Empty;
}
// walk up the XmlNode parent chain, looking for the xmlns attribute with namespaceName value
XmlNode? node = _curNode;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute a = attrs[i];
if (a.Value == namespaceName)
{
if (a.Prefix.Length == 0 && a.LocalName == "xmlns")
{
if (LookupNamespace(string.Empty) == namespaceName)
{
return string.Empty;
}
}
else if (a.Prefix == "xmlns")
{
string pref = a.LocalName;
if (LookupNamespace(pref) == namespaceName)
{
return _nameTable.Add(pref);
}
}
}
}
}
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
continue;
}
node = node.ParentNode;
}
return null;
}
internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (_bCreatedOnAttribute)
return dict;
// walk up the XmlNode parent chain and add all namespace declarations to the dictionary
XmlNode? node = _curNode;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute a = attrs[i];
if (a.LocalName == "xmlns" && a.Prefix.Length == 0)
{
if (!dict.ContainsKey(string.Empty))
{
dict.Add(_nameTable.Add(string.Empty), _nameTable.Add(a.Value!));
}
}
else if (a.Prefix == "xmlns")
{
string localName = a.LocalName;
if (!dict.ContainsKey(localName))
{
dict.Add(_nameTable.Add(localName), _nameTable.Add(a.Value!));
}
}
}
}
if (scope == XmlNamespaceScope.Local)
{
break;
}
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
continue;
}
node = node.ParentNode;
}
if (scope != XmlNamespaceScope.Local)
{
if (dict.ContainsKey(string.Empty) && dict[string.Empty] == string.Empty)
{
dict.Remove(string.Empty);
}
if (scope == XmlNamespaceScope.All)
{
dict.Add(_nameTable.Add("xml"), _nameTable.Add(XmlReservedNs.NsXml));
}
}
return dict;
}
public bool ReadAttributeValue(ref int level, ref bool bResolveEntity, ref XmlNodeType nt)
{
if (_nAttrInd != -1)
{
Debug.Assert(_curNode.NodeType == XmlNodeType.XmlDeclaration || _curNode.NodeType == XmlNodeType.DocumentType);
if (!_bOnAttrVal)
{
_bOnAttrVal = true;
level++;
nt = XmlNodeType.Text;
return true;
}
return false;
}
if (_curNode.NodeType == XmlNodeType.Attribute)
{
XmlNode? firstChild = _curNode.FirstChild;
if (firstChild != null)
{
_curNode = firstChild;
nt = _curNode.NodeType;
level++;
_bOnAttrVal = true;
return true;
}
}
else if (_bOnAttrVal)
{
XmlNode? nextSibling;
if (_curNode.NodeType == XmlNodeType.EntityReference && bResolveEntity)
{
//going down to ent ref node
_curNode = _curNode.FirstChild!;
Debug.Assert(_curNode != null);
nt = _curNode.NodeType;
level++;
bResolveEntity = false;
return true;
}
else
nextSibling = _curNode.NextSibling;
if (nextSibling == null)
{
XmlNode? parentNode = _curNode.ParentNode;
//Check if its parent is entity ref node is sufficient, because in this senario, ent ref node can't have more than 1 level of children that are not other ent ref nodes
if (parentNode != null && parentNode.NodeType == XmlNodeType.EntityReference)
{
//come back from ent ref node
_curNode = parentNode;
nt = XmlNodeType.EndEntity;
level--;
return true;
}
}
if (nextSibling != null)
{
_curNode = nextSibling;
nt = _curNode.NodeType;
return true;
}
else
return false;
}
return false;
}
public XmlDocument Document
{
get
{
return _doc;
}
}
}
// Represents a reader that provides fast, non-cached forward only stream access
// to XML data in an XmlDocument or a specific XmlNode within an XmlDocument.
public class XmlNodeReader : XmlReader, IXmlNamespaceResolver
{
private readonly XmlNodeReaderNavigator _readerNav;
private XmlNodeType _nodeType; // nodeType of the node that the reader is currently positioned on
private int _curDepth; // depth of attrNav ( also functions as reader's depth )
private ReadState _readState; // current reader's state
private bool _fEOF; // flag to show if reaches the end of file
//mark to the state that EntityReference node is supposed to be resolved
private bool _bResolveEntity;
private bool _bStartFromDocument;
private bool _bInReadBinary;
private ReadContentAsBinaryHelper? _readBinaryHelper;
// Creates an instance of the XmlNodeReader class using the specified XmlNode.
public XmlNodeReader(XmlNode node!!)
{
_readerNav = new XmlNodeReaderNavigator(node);
_curDepth = 0;
_readState = ReadState.Initial;
_fEOF = false;
_nodeType = XmlNodeType.None;
_bResolveEntity = false;
_bStartFromDocument = false;
}
//function returns if the reader currently in valid reading states
internal bool IsInReadingStates()
{
return (_readState == ReadState.Interactive); // || readState == ReadState.EndOfFile
}
//
// Node Properties
//
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get { return (IsInReadingStates()) ? _nodeType : XmlNodeType.None; }
}
// Gets the name of
// the current node, including the namespace prefix.
public override string Name
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.Name;
}
}
// Gets the name of the current node without the namespace prefix.
public override string LocalName
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.LocalName;
}
}
// Gets the namespace URN (as defined in the W3C Namespace Specification)
// of the current namespace scope.
public override string NamespaceURI
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.NamespaceURI;
}
}
// Gets the namespace prefix associated with the current node.
public override string Prefix
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.Prefix;
}
}
// Gets a value indicating whether
// XmlNodeReader.Value has a value to return.
public override bool HasValue
{
get
{
if (!IsInReadingStates())
return false;
return _readerNav.HasValue;
}
}
// Gets the text value of the current node.
public override string Value
{
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.Value;
}
}
// Gets the depth of the
// current node in the XML element stack.
public override int Depth
{
get { return _curDepth; }
}
// Gets the base URI of the current node.
public override string BaseURI
{
get { return _readerNav.BaseURI; }
}
public override bool CanResolveEntity
{
get { return true; }
}
// Gets a value indicating whether the current
// node is an empty element (for example, <MyElement/>.
public override bool IsEmptyElement
{
get
{
if (!IsInReadingStates())
return false;
return _readerNav.IsEmptyElement;
}
}
// Gets a value indicating whether the current node is an
// attribute that was generated from the default value defined
// in the DTD or schema.
public override bool IsDefault
{
get
{
if (!IsInReadingStates())
return false;
return _readerNav.IsDefault;
}
}
// Gets the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
if (!IsInReadingStates())
return XmlSpace.None;
return _readerNav.XmlSpace;
}
}
// Gets the current xml:lang scope.
public override string XmlLang
{
// Assume everything is in Unicode
get
{
if (!IsInReadingStates())
return string.Empty;
return _readerNav.XmlLang;
}
}
public override IXmlSchemaInfo? SchemaInfo
{
get
{
if (!IsInReadingStates())
{
return null;
}
return _readerNav.SchemaInfo;
}
}
//
// Attribute Accessors
//
// Gets the number of attributes on the current node.
public override int AttributeCount
{
get
{
if (!IsInReadingStates() || _nodeType == XmlNodeType.EndElement)
return 0;
return _readerNav.AttributeCount;
}
}
// Gets the value of the attribute with the specified name.
public override string? GetAttribute(string name)
{
//if not on Attribute, only element node could have attributes
if (!IsInReadingStates())
return null;
return _readerNav.GetAttribute(name);
}
// Gets the value of the attribute with the specified name and namespace.
public override string? GetAttribute(string name, string? namespaceURI)
{
//if not on Attribute, only element node could have attributes
if (!IsInReadingStates())
return null;
string ns = (namespaceURI == null) ? string.Empty : namespaceURI;
return _readerNav.GetAttribute(name, ns);
}
// Gets the value of the attribute with the specified index.
public override string GetAttribute(int attributeIndex)
{
if (!IsInReadingStates())
throw new ArgumentOutOfRangeException(nameof(attributeIndex));
//CheckIndexCondition( i );
//Debug.Assert( nav.NodeType == XmlNodeType.Element );
return _readerNav.GetAttribute(attributeIndex)!;
}
// Moves to the attribute with the specified name.
public override bool MoveToAttribute(string name)
{
if (!IsInReadingStates())
return false;
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
if (_readerNav.MoveToAttribute(name))
{ //, ref curDepth ) ) {
_curDepth++;
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
// Moves to the attribute with the specified name and namespace.
public override bool MoveToAttribute(string name, string? namespaceURI)
{
if (!IsInReadingStates())
return false;
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
string ns = (namespaceURI == null) ? string.Empty : namespaceURI;
if (_readerNav.MoveToAttribute(name, ns))
{ //, ref curDepth ) ) {
_curDepth++;
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
// Moves to the attribute with the specified index.
public override void MoveToAttribute(int attributeIndex)
{
if (!IsInReadingStates())
throw new ArgumentOutOfRangeException(nameof(attributeIndex));
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
try
{
if (AttributeCount > 0)
{
_readerNav.MoveToAttribute(attributeIndex);
if (_bInReadBinary)
{
FinishReadBinary();
}
}
else
throw new ArgumentOutOfRangeException(nameof(attributeIndex));
}
catch
{
_readerNav.RollBackMove(ref _curDepth);
throw;
}
_curDepth++;
_nodeType = _readerNav.NodeType;
}
// Moves to the first attribute.
public override bool MoveToFirstAttribute()
{
if (!IsInReadingStates())
return false;
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
if (AttributeCount > 0)
{
_readerNav.MoveToAttribute(0);
_curDepth++;
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
// Moves to the next attribute.
public override bool MoveToNextAttribute()
{
if (!IsInReadingStates() || _nodeType == XmlNodeType.EndElement)
return false;
_readerNav.LogMove(_curDepth);
_readerNav.ResetToAttribute(ref _curDepth);
if (_readerNav.MoveToNextAttribute(ref _curDepth))
{
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
// Moves to the element that contains the current attribute node.
public override bool MoveToElement()
{
if (!IsInReadingStates())
return false;
_readerNav.LogMove(_curDepth);
_readerNav.ResetToAttribute(ref _curDepth);
if (_readerNav.MoveToElement())
{
_curDepth--;
_nodeType = _readerNav.NodeType;
if (_bInReadBinary)
{
FinishReadBinary();
}
return true;
}
_readerNav.RollBackMove(ref _curDepth);
return false;
}
//
// Moving through the Stream
//
// Reads the next node from the stream.
public override bool Read()
{
return Read(false);
}
private bool Read(bool fSkipChildren)
{
if (_fEOF)
return false;
if (_readState == ReadState.Initial)
{
// if nav is pointing at the document node, start with its children
// otherwise,start with the node.
if ((_readerNav.NodeType == XmlNodeType.Document) || (_readerNav.NodeType == XmlNodeType.DocumentFragment))
{
_bStartFromDocument = true;
if (!ReadNextNode(fSkipChildren))
{
_readState = ReadState.Error;
return false;
}
}
ReSetReadingMarks();
_readState = ReadState.Interactive;
_nodeType = _readerNav.NodeType;
//_depth = 0;
_curDepth = 0;
return true;
}
if (_bInReadBinary)
{
FinishReadBinary();
}
if ((_readerNav.CreatedOnAttribute))
return false;
ReSetReadingMarks();
if (ReadNextNode(fSkipChildren))
{
return true;
}
else
{
if (_readState == ReadState.Initial || _readState == ReadState.Interactive)
_readState = ReadState.Error;
if (_readState == ReadState.EndOfFile)
_nodeType = XmlNodeType.None;
return false;
}
}
private bool ReadNextNode(bool fSkipChildren)
{
if (_readState != ReadState.Interactive && _readState != ReadState.Initial)
{
_nodeType = XmlNodeType.None;
return false;
}
bool bDrillDown = !fSkipChildren;
XmlNodeType nt = _readerNav.NodeType;
//only goes down when nav.NodeType is of element or of document at the initial state, other nav.NodeType will not be parsed down
//if nav.NodeType is of EntityReference, ResolveEntity() could be called to get the content parsed;
bDrillDown = bDrillDown
&& (_nodeType != XmlNodeType.EndElement)
&& (_nodeType != XmlNodeType.EndEntity)
&& (nt == XmlNodeType.Element || (nt == XmlNodeType.EntityReference && _bResolveEntity) ||
(((_readerNav.NodeType == XmlNodeType.Document) || (_readerNav.NodeType == XmlNodeType.DocumentFragment)) && _readState == ReadState.Initial));
//first see if there are children of current node, so to move down
if (bDrillDown)
{
if (_readerNav.MoveToFirstChild())
{
_nodeType = _readerNav.NodeType;
_curDepth++;
if (_bResolveEntity)
_bResolveEntity = false;
return true;
}
else if (_readerNav.NodeType == XmlNodeType.Element
&& !_readerNav.IsEmptyElement)
{
_nodeType = XmlNodeType.EndElement;
return true;
}
else if (_readerNav.NodeType == XmlNodeType.EntityReference && _bResolveEntity)
{
_bResolveEntity = false;
_nodeType = XmlNodeType.EndEntity;
return true;
}
// if fails to move to it 1st Child, try to move to next below
return ReadForward(fSkipChildren);
}
else
{
if (_readerNav.NodeType == XmlNodeType.EntityReference && _bResolveEntity)
{
//The only way to get to here is because Skip() is called directly after ResolveEntity()
// in this case, user wants to skip the first Child of EntityRef node and fSkipChildren is true
// We want to pointing to the first child node.
if (_readerNav.MoveToFirstChild())
{
_nodeType = _readerNav.NodeType;
_curDepth++;
}
else
{
_nodeType = XmlNodeType.EndEntity;
}
_bResolveEntity = false;
return true;
}
}
return ReadForward(fSkipChildren); //has to get the next node by moving forward
}
private void SetEndOfFile()
{
_fEOF = true;
_readState = ReadState.EndOfFile;
_nodeType = XmlNodeType.None;
}
private bool ReadAtZeroLevel(bool fSkipChildren)
{
Debug.Assert(_curDepth == 0);
if (!fSkipChildren
&& _nodeType != XmlNodeType.EndElement
&& _readerNav.NodeType == XmlNodeType.Element
&& !_readerNav.IsEmptyElement)
{
_nodeType = XmlNodeType.EndElement;
return true;
}
else
{
SetEndOfFile();
return false;
}
}
private bool ReadForward(bool fSkipChildren)
{
if (_readState == ReadState.Error)
return false;
if (!_bStartFromDocument && _curDepth == 0)
{
//already on top most node and we shouldn't move to next
return ReadAtZeroLevel(fSkipChildren);
}
//else either we are not on top level or we are starting from the document at the very beginning in which case
// we will need to read all the "top" most nodes
if (_readerNav.MoveToNext())
{
_nodeType = _readerNav.NodeType;
return true;
}
else
{
//need to check its parent
if (_curDepth == 0)
return ReadAtZeroLevel(fSkipChildren);
if (_readerNav.MoveToParent())
{
if (_readerNav.NodeType == XmlNodeType.Element)
{
_curDepth--;
_nodeType = XmlNodeType.EndElement;
return true;
}
else if (_readerNav.NodeType == XmlNodeType.EntityReference)
{
//coming back from entity reference node -- must be getting down through call ResolveEntity()
_curDepth--;
_nodeType = XmlNodeType.EndEntity;
return true;
}
return true;
}
}
return false;
}
//the function reset the marks used for ReadChars() and MoveToAttribute(...), ReadAttributeValue(...)
private void ReSetReadingMarks()
{
//_attrValInd = -1;
_readerNav.ResetMove(ref _curDepth, ref _nodeType);
//attrNav.MoveTo( nav );
//curDepth = _depth;
}
// Gets a value indicating whether the reader is positioned at the
// end of the stream.
public override bool EOF
{
get { return (_readState != ReadState.Closed) && _fEOF; }
}
// Closes the stream, changes the XmlNodeReader.ReadState
// to Closed, and sets all the properties back to zero.
public override void Close()
{
_readState = ReadState.Closed;
}
// Gets the read state of the stream.
public override ReadState ReadState
{
get { return _readState; }
}
// Skips to the end tag of the current element.
public override void Skip()
{
Read(true);
}
// Reads the contents of an element as a string.
public override string ReadString()
{
if ((this.NodeType == XmlNodeType.EntityReference) && _bResolveEntity)
{
if (!this.Read())
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
return base.ReadString();
}
//
// Partial Content Read Methods
//
// Gets a value indicating whether the current node
// has any attributes.
public override bool HasAttributes
{
get
{
return (AttributeCount > 0);
}
}
//
// Nametable and Namespace Helpers
//
// Gets the XmlNameTable associated with this implementation.
public override XmlNameTable NameTable
{
get { return _readerNav.NameTable; }
}
// Resolves a namespace prefix in the current element's scope.
public override string? LookupNamespace(string prefix)
{
if (!IsInReadingStates())
return null;
string? ns = _readerNav.LookupNamespace(prefix);
if (ns != null && ns.Length == 0)
{
return null;
}
return ns;
}
// Resolves the entity reference for nodes of NodeType EntityReference.
public override void ResolveEntity()
{
if (!IsInReadingStates() || (_nodeType != XmlNodeType.EntityReference))
throw new InvalidOperationException(SR.Xnr_ResolveEntity);
_bResolveEntity = true;
}
// Parses the attribute value into one or more Text and/or
// EntityReference node types.
public override bool ReadAttributeValue()
{
if (!IsInReadingStates())
return false;
if (_readerNav.ReadAttributeValue(ref _curDepth, ref _bResolveEntity, ref _nodeType))
{
_bInReadBinary = false;
return true;
}
return false;
}
public override bool CanReadBinaryContent
{
get
{
return true;
}
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
if (_readState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (!_bInReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
// turn off bInReadBinary in order to have a normal Read() behavior when called from readBinaryHelper
_bInReadBinary = false;
// call to the helper
int readCount = _readBinaryHelper!.ReadContentAsBase64(buffer, index, count);
// turn on bInReadBinary in again and return
_bInReadBinary = true;
return readCount;
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
if (_readState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (!_bInReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
// turn off bInReadBinary in order to have a normal Read() behavior when called from readBinaryHelper
_bInReadBinary = false;
// call to the helper
int readCount = _readBinaryHelper!.ReadContentAsBinHex(buffer, index, count);
// turn on bInReadBinary in again and return
_bInReadBinary = true;
return readCount;
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
if (_readState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (!_bInReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
// turn off bInReadBinary in order to have a normal Read() behavior when called from readBinaryHelper
_bInReadBinary = false;
// call to the helper
int readCount = _readBinaryHelper!.ReadElementContentAsBase64(buffer, index, count);
// turn on bInReadBinary in again and return
_bInReadBinary = true;
return readCount;
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
if (_readState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (!_bInReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
}
// turn off bInReadBinary in order to have a normal Read() behavior when called from readBinaryHelper
_bInReadBinary = false;
// call to the helper
int readCount = _readBinaryHelper!.ReadElementContentAsBinHex(buffer, index, count);
// turn on bInReadBinary in again and return
_bInReadBinary = true;
return readCount;
}
private void FinishReadBinary()
{
_bInReadBinary = false;
_readBinaryHelper!.Finish();
}
//
// IXmlNamespaceResolver
//
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return _readerNav.GetNamespacesInScope(scope);
}
string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _readerNav.LookupPrefix(namespaceName);
}
string? IXmlNamespaceResolver.LookupNamespace(string prefix)
{
if (!IsInReadingStates())
{
return _readerNav.DefaultLookupNamespace(prefix);
}
string? ns = _readerNav.LookupNamespace(prefix);
if (ns != null)
{
ns = _readerNav.NameTable.Add(ns);
}
return ns;
}
// DTD/Schema info used by XmlReader.GetDtdSchemaInfo()
internal override IDtdInfo? DtdInfo
{
get
{
return _readerNav.Document.DtdSchemaInfo;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices
{
/// <summary>Provides a handler used by the language compiler to process interpolated strings into <see cref="string"/> instances.</summary>
[InterpolatedStringHandler]
public ref struct DefaultInterpolatedStringHandler
{
// Implementation note:
// As this type lives in CompilerServices and is only intended to be targeted by the compiler,
// public APIs eschew argument validation logic in a variety of places, e.g. allowing a null input
// when one isn't expected to produce a NullReferenceException rather than an ArgumentNullException.
/// <summary>Expected average length of formatted data used for an individual interpolation expression result.</summary>
/// <remarks>
/// This is inherited from string.Format, and could be changed based on further data.
/// string.Format actually uses `format.Length + args.Length * 8`, but format.Length
/// includes the format items themselves, e.g. "{0}", and since it's rare to have double-digit
/// numbers of items, we bump the 8 up to 11 to account for the three extra characters in "{d}",
/// since the compiler-provided base length won't include the equivalent character count.
/// </remarks>
private const int GuessedLengthPerHole = 11;
/// <summary>Minimum size array to rent from the pool.</summary>
/// <remarks>Same as stack-allocation size used today by string.Format.</remarks>
private const int MinimumArrayPoolLength = 256;
/// <summary>Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.</summary>
private readonly IFormatProvider? _provider;
/// <summary>Array rented from the array pool and used to back <see cref="_chars"/>.</summary>
private char[]? _arrayToReturnToPool;
/// <summary>The span to write into.</summary>
private Span<char> _chars;
/// <summary>Position at which to write the next character.</summary>
private int _pos;
/// <summary>Whether <see cref="_provider"/> provides an ICustomFormatter.</summary>
/// <remarks>
/// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive
/// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field
/// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider
/// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a
/// formatter, we pay for the extra interface call on each AppendFormatted that needs it.
/// </remarks>
private readonly bool _hasCustomFormatter;
/// <summary>Creates a handler used to translate an interpolated string into a <see cref="string"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_provider = null;
_chars = _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(GetDefaultLength(literalLength, formattedCount));
_pos = 0;
_hasCustomFormatter = false;
}
/// <summary>Creates a handler used to translate an interpolated string into a <see cref="string"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)
{
_provider = provider;
_chars = _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(GetDefaultLength(literalLength, formattedCount));
_pos = 0;
_hasCustomFormatter = provider is not null && HasCustomFormatter(provider);
}
/// <summary>Creates a handler used to translate an interpolated string into a <see cref="string"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="initialBuffer">A buffer temporarily transferred to the handler for use as part of its formatting. Contents may be overwritten.</param>
/// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span<char> initialBuffer)
{
_provider = provider;
_chars = initialBuffer;
_arrayToReturnToPool = null;
_pos = 0;
_hasCustomFormatter = provider is not null && HasCustomFormatter(provider);
}
/// <summary>Derives a default length with which to seed the handler.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // becomes a constant when inputs are constant
internal static int GetDefaultLength(int literalLength, int formattedCount) =>
Math.Max(MinimumArrayPoolLength, literalLength + (formattedCount * GuessedLengthPerHole));
/// <summary>Gets the built <see cref="string"/>.</summary>
/// <returns>The built string.</returns>
public override string ToString() => new string(Text);
/// <summary>Gets the built <see cref="string"/> and clears the handler.</summary>
/// <returns>The built string.</returns>
/// <remarks>
/// This releases any resources used by the handler. The method should be invoked only
/// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,
/// and may destabilize the process, as may using any other copies of the handler after ToStringAndClear
/// is called on any one of them.
/// </remarks>
public string ToStringAndClear()
{
string result = new string(Text);
Clear();
return result;
}
/// <summary>Clears the handler, returning any rented array to the pool.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // used only on a few hot paths
internal void Clear()
{
char[]? toReturn = _arrayToReturnToPool;
this = default; // defensive clear
if (toReturn is not null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
/// <summary>Gets a span of the written characters thus far.</summary>
internal ReadOnlySpan<char> Text => _chars.Slice(0, _pos);
/// <summary>Writes the specified string to the handler.</summary>
/// <param name="value">The string to write.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AppendLiteral(string value)
{
// AppendLiteral is expected to always be called by compiler-generated code with a literal string.
// By inlining it, the method body is exposed to the constant length of that literal, allowing the JIT to
// prune away the irrelevant cases. This effectively enables multiple implementations of AppendLiteral,
// special-cased on and optimized for the literal's length. We special-case lengths 1 and 2 because
// they're very common, e.g.
// 1: ' ', '.', '-', '\t', etc.
// 2: ", ", "0x", "=>", ": ", etc.
// but we refrain from adding more because, in the rare case where AppendLiteral is called with a non-literal,
// there is a lot of code here to be inlined.
// TODO: https://github.com/dotnet/runtime/issues/41692#issuecomment-685192193
// What we really want here is to be able to add a bunch of additional special-cases based on length,
// e.g. a switch with a case for each length <= 8, not mark the method as AggressiveInlining, and have
// it inlined when provided with a string literal such that all the other cases evaporate but not inlined
// if called directly with something that doesn't enable pruning. Even better, if "literal".TryCopyTo
// could be unrolled based on the literal, ala https://github.com/dotnet/runtime/pull/46392, we might
// be able to remove all special-casing here.
if (value.Length == 1)
{
Span<char> chars = _chars;
int pos = _pos;
if ((uint)pos < (uint)chars.Length)
{
chars[pos] = value[0];
_pos = pos + 1;
}
else
{
GrowThenCopyString(value);
}
return;
}
if (value.Length == 2)
{
Span<char> chars = _chars;
int pos = _pos;
if ((uint)pos < chars.Length - 1)
{
Unsafe.WriteUnaligned(
ref Unsafe.As<char, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(chars), pos)),
Unsafe.ReadUnaligned<int>(ref Unsafe.As<char, byte>(ref value.GetRawStringData())));
_pos = pos + 2;
}
else
{
GrowThenCopyString(value);
}
return;
}
AppendStringDirect(value);
}
/// <summary>Writes the specified string to the handler.</summary>
/// <param name="value">The string to write.</param>
private void AppendStringDirect(string value)
{
if (value.TryCopyTo(_chars.Slice(_pos)))
{
_pos += value.Length;
}
else
{
GrowThenCopyString(value);
}
}
#region AppendFormatted
// Design note:
// The compiler requires a AppendFormatted overload for anything that might be within an interpolation expression;
// if it can't find an appropriate overload, for handlers in general it'll simply fail to compile.
// (For target-typing to string where it uses DefaultInterpolatedStringHandler implicitly, it'll instead fall back to
// its other mechanisms, e.g. using string.Format. This fallback has the benefit that if we miss a case,
// interpolated strings will still work, but it has the downside that a developer generally won't know
// if the fallback is happening and they're paying more.)
//
// At a minimum, then, we would need an overload that accepts:
// (object value, int alignment = 0, string? format = null)
// Such an overload would provide the same expressiveness as string.Format. However, this has several
// shortcomings:
// - Every value type in an interpolation expression would be boxed.
// - ReadOnlySpan<char> could not be used in interpolation expressions.
// - Every AppendFormatted call would have three arguments at the call site, bloating the IL further.
// - Every invocation would be more expensive, due to lack of specialization, every call needing to account
// for alignment and format, etc.
//
// To address that, we could just have overloads for T and ReadOnlySpan<char>:
// (T)
// (T, int alignment)
// (T, string? format)
// (T, int alignment, string? format)
// (ReadOnlySpan<char>)
// (ReadOnlySpan<char>, int alignment)
// (ReadOnlySpan<char>, string? format)
// (ReadOnlySpan<char>, int alignment, string? format)
// but this also has shortcomings:
// - Some expressions that would have worked with an object overload will now force a fallback to string.Format
// (or fail to compile if the handler is used in places where the fallback isn't provided), because the compiler
// can't always target type to T, e.g. `b switch { true => 1, false => null }` where `b` is a bool can successfully
// be passed as an argument of type `object` but not of type `T`.
// - Reference types get no benefit from going through the generic code paths, and actually incur some overheads
// from doing so.
// - Nullable value types also pay a heavy price, in particular around interface checks that would generally evaporate
// at compile time for value types but don't (currently) if the Nullable<T> goes through the same code paths
// (see https://github.com/dotnet/runtime/issues/50915).
//
// We could try to take a more elaborate approach for DefaultInterpolatedStringHandler, since it is the most common handler
// and we want to minimize overheads both at runtime and in IL size, e.g. have a complete set of overloads for each of:
// (T, ...) where T : struct
// (T?, ...) where T : struct
// (object, ...)
// (ReadOnlySpan<char>, ...)
// (string, ...)
// but this also has shortcomings, most importantly:
// - If you have an unconstrained T that happens to be a value type, it'll now end up getting boxed to use the object overload.
// This also necessitates the T? overload, since nullable value types don't meet a T : struct constraint, so without those
// they'd all map to the object overloads as well.
// - Any reference type with an implicit cast to ROS<char> will fail to compile due to ambiguities between the overloads. string
// is one such type, hence needing dedicated overloads for it that can be bound to more tightly.
//
// A middle ground we've settled on, which is likely to be the right approach for most other handlers as well, would be the set:
// (T, ...) with no constraint
// (ReadOnlySpan<char>) and (ReadOnlySpan<char>, int)
// (object, int alignment = 0, string? format = null)
// (string) and (string, int)
// This would address most of the concerns, at the expense of:
// - Most reference types going through the generic code paths and so being a bit more expensive.
// - Nullable types being more expensive until https://github.com/dotnet/runtime/issues/50915 is addressed.
// We could choose to add a T? where T : struct set of overloads if necessary.
// Strings don't require their own overloads here, but as they're expected to be very common and as we can
// optimize them in several ways (can copy the contents directly, don't need to do any interface checks, don't
// need to pay the shared generic overheads, etc.) we can add overloads specifically to optimize for them.
//
// Hole values are formatted according to the following policy:
// 1. If an IFormatProvider was supplied and it provides an ICustomFormatter, use ICustomFormatter.Format (even if the value is null).
// 2. If the type implements ISpanFormattable, use ISpanFormattable.TryFormat.
// 3. If the type implements IFormattable, use IFormattable.ToString.
// 4. Otherwise, use object.ToString.
// This matches the behavior of string.Format, StringBuilder.AppendFormat, etc. The only overloads for which this doesn't
// apply is ReadOnlySpan<char>, which isn't supported by either string.Format nor StringBuilder.AppendFormat, but more
// importantly which can't be boxed to be passed to ICustomFormatter.Format.
#region AppendFormatted T
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value)
{
// This method could delegate to AppendFormatted with a null format, but explicitly passing
// default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined,
// e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format.
// If there's a custom formatter, always use it.
if (_hasCustomFormatter)
{
AppendCustomFormatter(value, format: null);
return;
}
// Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter
// requires the former. For value types, it won't matter as the type checks devolve into
// JIT-time constants. For reference types, they're more likely to implement IFormattable
// than they are to implement ISpanFormattable: if they don't implement either, we save an
// interface check over first checking for ISpanFormattable and then for IFormattable, and
// if it only implements IFormattable, we come out even: only if it implements both do we
// end up paying for an extra interface check.
string? s;
if (value is IFormattable)
{
// If the value can format itself directly into our buffer, do so.
if (value is ISpanFormattable)
{
int charsWritten;
while (!((ISpanFormattable)value).TryFormat(_chars.Slice(_pos), out charsWritten, default, _provider)) // constrained call avoiding boxing for value types
{
Grow();
}
_pos += charsWritten;
return;
}
s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types
}
else
{
s = value?.ToString();
}
if (s is not null)
{
AppendStringDirect(s);
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value, string? format)
{
// If there's a custom formatter, always use it.
if (_hasCustomFormatter)
{
AppendCustomFormatter(value, format);
return;
}
// Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter
// requires the former. For value types, it won't matter as the type checks devolve into
// JIT-time constants. For reference types, they're more likely to implement IFormattable
// than they are to implement ISpanFormattable: if they don't implement either, we save an
// interface check over first checking for ISpanFormattable and then for IFormattable, and
// if it only implements IFormattable, we come out even: only if it implements both do we
// end up paying for an extra interface check.
string? s;
if (value is IFormattable)
{
// If the value can format itself directly into our buffer, do so.
if (value is ISpanFormattable)
{
int charsWritten;
while (!((ISpanFormattable)value).TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) // constrained call avoiding boxing for value types
{
Grow();
}
_pos += charsWritten;
return;
}
s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types
}
else
{
s = value?.ToString();
}
if (s is not null)
{
AppendStringDirect(s);
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value, int alignment)
{
int startingPos = _pos;
AppendFormatted(value);
if (alignment != 0)
{
AppendOrInsertAlignmentIfNeeded(startingPos, alignment);
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value, int alignment, string? format)
{
int startingPos = _pos;
AppendFormatted(value, format);
if (alignment != 0)
{
AppendOrInsertAlignmentIfNeeded(startingPos, alignment);
}
}
#endregion
#region AppendFormatted ReadOnlySpan<char>
/// <summary>Writes the specified character span to the handler.</summary>
/// <param name="value">The span to write.</param>
public void AppendFormatted(ReadOnlySpan<char> value)
{
// Fast path for when the value fits in the current buffer
if (value.TryCopyTo(_chars.Slice(_pos)))
{
_pos += value.Length;
}
else
{
GrowThenCopySpan(value);
}
}
/// <summary>Writes the specified string of chars to the handler.</summary>
/// <param name="value">The span to write.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <param name="format">The format string.</param>
public void AppendFormatted(ReadOnlySpan<char> value, int alignment = 0, string? format = null)
{
bool leftAlign = false;
if (alignment < 0)
{
leftAlign = true;
alignment = -alignment;
}
int paddingRequired = alignment - value.Length;
if (paddingRequired <= 0)
{
// The value is as large or larger than the required amount of padding,
// so just write the value.
AppendFormatted(value);
return;
}
// Write the value along with the appropriate padding.
EnsureCapacityForAdditionalChars(value.Length + paddingRequired);
if (leftAlign)
{
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
_chars.Slice(_pos, paddingRequired).Fill(' ');
_pos += paddingRequired;
}
else
{
_chars.Slice(_pos, paddingRequired).Fill(' ');
_pos += paddingRequired;
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
}
#endregion
#region AppendFormatted string
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
public void AppendFormatted(string? value)
{
// Fast-path for no custom formatter and a non-null string that fits in the current destination buffer.
if (!_hasCustomFormatter &&
value is not null &&
value.TryCopyTo(_chars.Slice(_pos)))
{
_pos += value.Length;
}
else
{
AppendFormattedSlow(value);
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <remarks>
/// Slow path to handle a custom formatter, potentially null value,
/// or a string that doesn't fit in the current buffer.
/// </remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
private void AppendFormattedSlow(string? value)
{
if (_hasCustomFormatter)
{
AppendCustomFormatter(value, format: null);
}
else if (value is not null)
{
EnsureCapacityForAdditionalChars(value.Length);
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <param name="format">The format string.</param>
public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>
// Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload
// simply to disambiguate between ROS<char> and object, just in case someone does specify a format, as
// string is implicitly convertible to both. Just delegate to the T-based implementation.
AppendFormatted<string?>(value, alignment, format);
#endregion
#region AppendFormatted object
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <param name="format">The format string.</param>
public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>
// This overload is expected to be used rarely, only if either a) something strongly typed as object is
// formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It
// exists purely to help make cases from (b) compile. Just delegate to the T-based implementation.
AppendFormatted<object?>(value, alignment, format);
#endregion
#endregion
/// <summary>Gets whether the provider provides a custom formatter.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // only used in a few hot path call sites
internal static bool HasCustomFormatter(IFormatProvider provider)
{
Debug.Assert(provider is not null);
Debug.Assert(provider is not CultureInfo || provider.GetFormat(typeof(ICustomFormatter)) is null, "Expected CultureInfo to not provide a custom formatter");
return
provider.GetType() != typeof(CultureInfo) && // optimization to avoid GetFormat in the majority case
provider.GetFormat(typeof(ICustomFormatter)) != null;
}
/// <summary>Formats the value using the custom formatter from the provider.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
[MethodImpl(MethodImplOptions.NoInlining)]
private void AppendCustomFormatter<T>(T value, string? format)
{
// This case is very rare, but we need to handle it prior to the other checks in case
// a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.
// We do the cast here rather than in the ctor, even though this could be executed multiple times per
// formatting, to make the cast pay for play.
Debug.Assert(_hasCustomFormatter);
Debug.Assert(_provider != null);
ICustomFormatter? formatter = (ICustomFormatter?)_provider.GetFormat(typeof(ICustomFormatter));
Debug.Assert(formatter != null, "An incorrectly written provider said it implemented ICustomFormatter, and then didn't");
if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted)
{
AppendStringDirect(customFormatted);
}
}
/// <summary>Handles adding any padding required for aligning a formatted value in an interpolation expression.</summary>
/// <param name="startingPos">The position at which the written value started.</param>
/// <param name="alignment">Non-zero minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)
{
Debug.Assert(startingPos >= 0 && startingPos <= _pos);
Debug.Assert(alignment != 0);
int charsWritten = _pos - startingPos;
bool leftAlign = false;
if (alignment < 0)
{
leftAlign = true;
alignment = -alignment;
}
int paddingNeeded = alignment - charsWritten;
if (paddingNeeded > 0)
{
EnsureCapacityForAdditionalChars(paddingNeeded);
if (leftAlign)
{
_chars.Slice(_pos, paddingNeeded).Fill(' ');
}
else
{
_chars.Slice(startingPos, charsWritten).CopyTo(_chars.Slice(startingPos + paddingNeeded));
_chars.Slice(startingPos, paddingNeeded).Fill(' ');
}
_pos += paddingNeeded;
}
}
/// <summary>Ensures <see cref="_chars"/> has the capacity to store <paramref name="additionalChars"/> beyond <see cref="_pos"/>.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacityForAdditionalChars(int additionalChars)
{
if (_chars.Length - _pos < additionalChars)
{
Grow(additionalChars);
}
}
/// <summary>Fallback for fast path in <see cref="AppendStringDirect"/> when there's not enough space in the destination.</summary>
/// <param name="value">The string to write.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowThenCopyString(string value)
{
Grow(value.Length);
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
/// <summary>Fallback for <see cref="AppendFormatted(ReadOnlySpan{char})"/> for when not enough space exists in the current buffer.</summary>
/// <param name="value">The span to write.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowThenCopySpan(ReadOnlySpan<char> value)
{
Grow(value.Length);
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
/// <summary>Grows <see cref="_chars"/> to have the capacity to store at least <paramref name="additionalChars"/> beyond <see cref="_pos"/>.</summary>
[MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible
private void Grow(int additionalChars)
{
// This method is called when the remaining space (_chars.Length - _pos) is
// insufficient to store a specific number of additional characters. Thus, we
// need to grow to at least that new total. GrowCore will handle growing by more
// than that if possible.
Debug.Assert(additionalChars > _chars.Length - _pos);
GrowCore((uint)_pos + (uint)additionalChars);
}
/// <summary>Grows the size of <see cref="_chars"/>.</summary>
[MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible
private void Grow()
{
// This method is called when the remaining space in _chars isn't sufficient to continue
// the operation. Thus, we need at least one character beyond _chars.Length. GrowCore
// will handle growing by more than that if possible.
GrowCore((uint)_chars.Length + 1);
}
/// <summary>Grow the size of <see cref="_chars"/> to at least the specified <paramref name="requiredMinCapacity"/>.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines
private void GrowCore(uint requiredMinCapacity)
{
// We want the max of how much space we actually required and doubling our capacity (without going beyond the max allowed length). We
// also want to avoid asking for small arrays, to reduce the number of times we need to grow, and since we're working with unsigned
// ints that could technically overflow if someone tried to, for example, append a huge string to a huge string, we also clamp to int.MaxValue.
// Even if the array creation fails in such a case, we may later fail in ToStringAndClear.
uint newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint)_chars.Length * 2, string.MaxLength));
int arraySize = (int)Math.Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue);
char[] newArray = ArrayPool<char>.Shared.Rent(arraySize);
_chars.Slice(0, _pos).CopyTo(newArray);
char[]? toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = newArray;
if (toReturn is not null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices
{
/// <summary>Provides a handler used by the language compiler to process interpolated strings into <see cref="string"/> instances.</summary>
[InterpolatedStringHandler]
public ref struct DefaultInterpolatedStringHandler
{
// Implementation note:
// As this type lives in CompilerServices and is only intended to be targeted by the compiler,
// public APIs eschew argument validation logic in a variety of places, e.g. allowing a null input
// when one isn't expected to produce a NullReferenceException rather than an ArgumentNullException.
/// <summary>Expected average length of formatted data used for an individual interpolation expression result.</summary>
/// <remarks>
/// This is inherited from string.Format, and could be changed based on further data.
/// string.Format actually uses `format.Length + args.Length * 8`, but format.Length
/// includes the format items themselves, e.g. "{0}", and since it's rare to have double-digit
/// numbers of items, we bump the 8 up to 11 to account for the three extra characters in "{d}",
/// since the compiler-provided base length won't include the equivalent character count.
/// </remarks>
private const int GuessedLengthPerHole = 11;
/// <summary>Minimum size array to rent from the pool.</summary>
/// <remarks>Same as stack-allocation size used today by string.Format.</remarks>
private const int MinimumArrayPoolLength = 256;
/// <summary>Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.</summary>
private readonly IFormatProvider? _provider;
/// <summary>Array rented from the array pool and used to back <see cref="_chars"/>.</summary>
private char[]? _arrayToReturnToPool;
/// <summary>The span to write into.</summary>
private Span<char> _chars;
/// <summary>Position at which to write the next character.</summary>
private int _pos;
/// <summary>Whether <see cref="_provider"/> provides an ICustomFormatter.</summary>
/// <remarks>
/// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive
/// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field
/// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider
/// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a
/// formatter, we pay for the extra interface call on each AppendFormatted that needs it.
/// </remarks>
private readonly bool _hasCustomFormatter;
/// <summary>Creates a handler used to translate an interpolated string into a <see cref="string"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_provider = null;
_chars = _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(GetDefaultLength(literalLength, formattedCount));
_pos = 0;
_hasCustomFormatter = false;
}
/// <summary>Creates a handler used to translate an interpolated string into a <see cref="string"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)
{
_provider = provider;
_chars = _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(GetDefaultLength(literalLength, formattedCount));
_pos = 0;
_hasCustomFormatter = provider is not null && HasCustomFormatter(provider);
}
/// <summary>Creates a handler used to translate an interpolated string into a <see cref="string"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="initialBuffer">A buffer temporarily transferred to the handler for use as part of its formatting. Contents may be overwritten.</param>
/// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span<char> initialBuffer)
{
_provider = provider;
_chars = initialBuffer;
_arrayToReturnToPool = null;
_pos = 0;
_hasCustomFormatter = provider is not null && HasCustomFormatter(provider);
}
/// <summary>Derives a default length with which to seed the handler.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // becomes a constant when inputs are constant
internal static int GetDefaultLength(int literalLength, int formattedCount) =>
Math.Max(MinimumArrayPoolLength, literalLength + (formattedCount * GuessedLengthPerHole));
/// <summary>Gets the built <see cref="string"/>.</summary>
/// <returns>The built string.</returns>
public override string ToString() => new string(Text);
/// <summary>Gets the built <see cref="string"/> and clears the handler.</summary>
/// <returns>The built string.</returns>
/// <remarks>
/// This releases any resources used by the handler. The method should be invoked only
/// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,
/// and may destabilize the process, as may using any other copies of the handler after ToStringAndClear
/// is called on any one of them.
/// </remarks>
public string ToStringAndClear()
{
string result = new string(Text);
Clear();
return result;
}
/// <summary>Clears the handler, returning any rented array to the pool.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // used only on a few hot paths
internal void Clear()
{
char[]? toReturn = _arrayToReturnToPool;
this = default; // defensive clear
if (toReturn is not null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
/// <summary>Gets a span of the written characters thus far.</summary>
internal ReadOnlySpan<char> Text => _chars.Slice(0, _pos);
/// <summary>Writes the specified string to the handler.</summary>
/// <param name="value">The string to write.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AppendLiteral(string value)
{
// AppendLiteral is expected to always be called by compiler-generated code with a literal string.
// By inlining it, the method body is exposed to the constant length of that literal, allowing the JIT to
// prune away the irrelevant cases. This effectively enables multiple implementations of AppendLiteral,
// special-cased on and optimized for the literal's length. We special-case lengths 1 and 2 because
// they're very common, e.g.
// 1: ' ', '.', '-', '\t', etc.
// 2: ", ", "0x", "=>", ": ", etc.
// but we refrain from adding more because, in the rare case where AppendLiteral is called with a non-literal,
// there is a lot of code here to be inlined.
// TODO: https://github.com/dotnet/runtime/issues/41692#issuecomment-685192193
// What we really want here is to be able to add a bunch of additional special-cases based on length,
// e.g. a switch with a case for each length <= 8, not mark the method as AggressiveInlining, and have
// it inlined when provided with a string literal such that all the other cases evaporate but not inlined
// if called directly with something that doesn't enable pruning. Even better, if "literal".TryCopyTo
// could be unrolled based on the literal, ala https://github.com/dotnet/runtime/pull/46392, we might
// be able to remove all special-casing here.
if (value.Length == 1)
{
Span<char> chars = _chars;
int pos = _pos;
if ((uint)pos < (uint)chars.Length)
{
chars[pos] = value[0];
_pos = pos + 1;
}
else
{
GrowThenCopyString(value);
}
return;
}
if (value.Length == 2)
{
Span<char> chars = _chars;
int pos = _pos;
if ((uint)pos < chars.Length - 1)
{
Unsafe.WriteUnaligned(
ref Unsafe.As<char, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(chars), pos)),
Unsafe.ReadUnaligned<int>(ref Unsafe.As<char, byte>(ref value.GetRawStringData())));
_pos = pos + 2;
}
else
{
GrowThenCopyString(value);
}
return;
}
AppendStringDirect(value);
}
/// <summary>Writes the specified string to the handler.</summary>
/// <param name="value">The string to write.</param>
private void AppendStringDirect(string value)
{
if (value.TryCopyTo(_chars.Slice(_pos)))
{
_pos += value.Length;
}
else
{
GrowThenCopyString(value);
}
}
#region AppendFormatted
// Design note:
// The compiler requires a AppendFormatted overload for anything that might be within an interpolation expression;
// if it can't find an appropriate overload, for handlers in general it'll simply fail to compile.
// (For target-typing to string where it uses DefaultInterpolatedStringHandler implicitly, it'll instead fall back to
// its other mechanisms, e.g. using string.Format. This fallback has the benefit that if we miss a case,
// interpolated strings will still work, but it has the downside that a developer generally won't know
// if the fallback is happening and they're paying more.)
//
// At a minimum, then, we would need an overload that accepts:
// (object value, int alignment = 0, string? format = null)
// Such an overload would provide the same expressiveness as string.Format. However, this has several
// shortcomings:
// - Every value type in an interpolation expression would be boxed.
// - ReadOnlySpan<char> could not be used in interpolation expressions.
// - Every AppendFormatted call would have three arguments at the call site, bloating the IL further.
// - Every invocation would be more expensive, due to lack of specialization, every call needing to account
// for alignment and format, etc.
//
// To address that, we could just have overloads for T and ReadOnlySpan<char>:
// (T)
// (T, int alignment)
// (T, string? format)
// (T, int alignment, string? format)
// (ReadOnlySpan<char>)
// (ReadOnlySpan<char>, int alignment)
// (ReadOnlySpan<char>, string? format)
// (ReadOnlySpan<char>, int alignment, string? format)
// but this also has shortcomings:
// - Some expressions that would have worked with an object overload will now force a fallback to string.Format
// (or fail to compile if the handler is used in places where the fallback isn't provided), because the compiler
// can't always target type to T, e.g. `b switch { true => 1, false => null }` where `b` is a bool can successfully
// be passed as an argument of type `object` but not of type `T`.
// - Reference types get no benefit from going through the generic code paths, and actually incur some overheads
// from doing so.
// - Nullable value types also pay a heavy price, in particular around interface checks that would generally evaporate
// at compile time for value types but don't (currently) if the Nullable<T> goes through the same code paths
// (see https://github.com/dotnet/runtime/issues/50915).
//
// We could try to take a more elaborate approach for DefaultInterpolatedStringHandler, since it is the most common handler
// and we want to minimize overheads both at runtime and in IL size, e.g. have a complete set of overloads for each of:
// (T, ...) where T : struct
// (T?, ...) where T : struct
// (object, ...)
// (ReadOnlySpan<char>, ...)
// (string, ...)
// but this also has shortcomings, most importantly:
// - If you have an unconstrained T that happens to be a value type, it'll now end up getting boxed to use the object overload.
// This also necessitates the T? overload, since nullable value types don't meet a T : struct constraint, so without those
// they'd all map to the object overloads as well.
// - Any reference type with an implicit cast to ROS<char> will fail to compile due to ambiguities between the overloads. string
// is one such type, hence needing dedicated overloads for it that can be bound to more tightly.
//
// A middle ground we've settled on, which is likely to be the right approach for most other handlers as well, would be the set:
// (T, ...) with no constraint
// (ReadOnlySpan<char>) and (ReadOnlySpan<char>, int)
// (object, int alignment = 0, string? format = null)
// (string) and (string, int)
// This would address most of the concerns, at the expense of:
// - Most reference types going through the generic code paths and so being a bit more expensive.
// - Nullable types being more expensive until https://github.com/dotnet/runtime/issues/50915 is addressed.
// We could choose to add a T? where T : struct set of overloads if necessary.
// Strings don't require their own overloads here, but as they're expected to be very common and as we can
// optimize them in several ways (can copy the contents directly, don't need to do any interface checks, don't
// need to pay the shared generic overheads, etc.) we can add overloads specifically to optimize for them.
//
// Hole values are formatted according to the following policy:
// 1. If an IFormatProvider was supplied and it provides an ICustomFormatter, use ICustomFormatter.Format (even if the value is null).
// 2. If the type implements ISpanFormattable, use ISpanFormattable.TryFormat.
// 3. If the type implements IFormattable, use IFormattable.ToString.
// 4. Otherwise, use object.ToString.
// This matches the behavior of string.Format, StringBuilder.AppendFormat, etc. The only overloads for which this doesn't
// apply is ReadOnlySpan<char>, which isn't supported by either string.Format nor StringBuilder.AppendFormat, but more
// importantly which can't be boxed to be passed to ICustomFormatter.Format.
#region AppendFormatted T
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value)
{
// This method could delegate to AppendFormatted with a null format, but explicitly passing
// default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined,
// e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format.
// If there's a custom formatter, always use it.
if (_hasCustomFormatter)
{
AppendCustomFormatter(value, format: null);
return;
}
// Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter
// requires the former. For value types, it won't matter as the type checks devolve into
// JIT-time constants. For reference types, they're more likely to implement IFormattable
// than they are to implement ISpanFormattable: if they don't implement either, we save an
// interface check over first checking for ISpanFormattable and then for IFormattable, and
// if it only implements IFormattable, we come out even: only if it implements both do we
// end up paying for an extra interface check.
string? s;
if (value is IFormattable)
{
// If the value can format itself directly into our buffer, do so.
if (value is ISpanFormattable)
{
int charsWritten;
while (!((ISpanFormattable)value).TryFormat(_chars.Slice(_pos), out charsWritten, default, _provider)) // constrained call avoiding boxing for value types
{
Grow();
}
_pos += charsWritten;
return;
}
s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types
}
else
{
s = value?.ToString();
}
if (s is not null)
{
AppendStringDirect(s);
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value, string? format)
{
// If there's a custom formatter, always use it.
if (_hasCustomFormatter)
{
AppendCustomFormatter(value, format);
return;
}
// Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter
// requires the former. For value types, it won't matter as the type checks devolve into
// JIT-time constants. For reference types, they're more likely to implement IFormattable
// than they are to implement ISpanFormattable: if they don't implement either, we save an
// interface check over first checking for ISpanFormattable and then for IFormattable, and
// if it only implements IFormattable, we come out even: only if it implements both do we
// end up paying for an extra interface check.
string? s;
if (value is IFormattable)
{
// If the value can format itself directly into our buffer, do so.
if (value is ISpanFormattable)
{
int charsWritten;
while (!((ISpanFormattable)value).TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) // constrained call avoiding boxing for value types
{
Grow();
}
_pos += charsWritten;
return;
}
s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types
}
else
{
s = value?.ToString();
}
if (s is not null)
{
AppendStringDirect(s);
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value, int alignment)
{
int startingPos = _pos;
AppendFormatted(value);
if (alignment != 0)
{
AppendOrInsertAlignmentIfNeeded(startingPos, alignment);
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value, int alignment, string? format)
{
int startingPos = _pos;
AppendFormatted(value, format);
if (alignment != 0)
{
AppendOrInsertAlignmentIfNeeded(startingPos, alignment);
}
}
#endregion
#region AppendFormatted ReadOnlySpan<char>
/// <summary>Writes the specified character span to the handler.</summary>
/// <param name="value">The span to write.</param>
public void AppendFormatted(ReadOnlySpan<char> value)
{
// Fast path for when the value fits in the current buffer
if (value.TryCopyTo(_chars.Slice(_pos)))
{
_pos += value.Length;
}
else
{
GrowThenCopySpan(value);
}
}
/// <summary>Writes the specified string of chars to the handler.</summary>
/// <param name="value">The span to write.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <param name="format">The format string.</param>
public void AppendFormatted(ReadOnlySpan<char> value, int alignment = 0, string? format = null)
{
bool leftAlign = false;
if (alignment < 0)
{
leftAlign = true;
alignment = -alignment;
}
int paddingRequired = alignment - value.Length;
if (paddingRequired <= 0)
{
// The value is as large or larger than the required amount of padding,
// so just write the value.
AppendFormatted(value);
return;
}
// Write the value along with the appropriate padding.
EnsureCapacityForAdditionalChars(value.Length + paddingRequired);
if (leftAlign)
{
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
_chars.Slice(_pos, paddingRequired).Fill(' ');
_pos += paddingRequired;
}
else
{
_chars.Slice(_pos, paddingRequired).Fill(' ');
_pos += paddingRequired;
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
}
#endregion
#region AppendFormatted string
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
public void AppendFormatted(string? value)
{
// Fast-path for no custom formatter and a non-null string that fits in the current destination buffer.
if (!_hasCustomFormatter &&
value is not null &&
value.TryCopyTo(_chars.Slice(_pos)))
{
_pos += value.Length;
}
else
{
AppendFormattedSlow(value);
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <remarks>
/// Slow path to handle a custom formatter, potentially null value,
/// or a string that doesn't fit in the current buffer.
/// </remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
private void AppendFormattedSlow(string? value)
{
if (_hasCustomFormatter)
{
AppendCustomFormatter(value, format: null);
}
else if (value is not null)
{
EnsureCapacityForAdditionalChars(value.Length);
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <param name="format">The format string.</param>
public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>
// Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload
// simply to disambiguate between ROS<char> and object, just in case someone does specify a format, as
// string is implicitly convertible to both. Just delegate to the T-based implementation.
AppendFormatted<string?>(value, alignment, format);
#endregion
#region AppendFormatted object
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="alignment">Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
/// <param name="format">The format string.</param>
public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>
// This overload is expected to be used rarely, only if either a) something strongly typed as object is
// formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It
// exists purely to help make cases from (b) compile. Just delegate to the T-based implementation.
AppendFormatted<object?>(value, alignment, format);
#endregion
#endregion
/// <summary>Gets whether the provider provides a custom formatter.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // only used in a few hot path call sites
internal static bool HasCustomFormatter(IFormatProvider provider)
{
Debug.Assert(provider is not null);
Debug.Assert(provider is not CultureInfo || provider.GetFormat(typeof(ICustomFormatter)) is null, "Expected CultureInfo to not provide a custom formatter");
return
provider.GetType() != typeof(CultureInfo) && // optimization to avoid GetFormat in the majority case
provider.GetFormat(typeof(ICustomFormatter)) != null;
}
/// <summary>Formats the value using the custom formatter from the provider.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
[MethodImpl(MethodImplOptions.NoInlining)]
private void AppendCustomFormatter<T>(T value, string? format)
{
// This case is very rare, but we need to handle it prior to the other checks in case
// a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.
// We do the cast here rather than in the ctor, even though this could be executed multiple times per
// formatting, to make the cast pay for play.
Debug.Assert(_hasCustomFormatter);
Debug.Assert(_provider != null);
ICustomFormatter? formatter = (ICustomFormatter?)_provider.GetFormat(typeof(ICustomFormatter));
Debug.Assert(formatter != null, "An incorrectly written provider said it implemented ICustomFormatter, and then didn't");
if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted)
{
AppendStringDirect(customFormatted);
}
}
/// <summary>Handles adding any padding required for aligning a formatted value in an interpolation expression.</summary>
/// <param name="startingPos">The position at which the written value started.</param>
/// <param name="alignment">Non-zero minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.</param>
private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)
{
Debug.Assert(startingPos >= 0 && startingPos <= _pos);
Debug.Assert(alignment != 0);
int charsWritten = _pos - startingPos;
bool leftAlign = false;
if (alignment < 0)
{
leftAlign = true;
alignment = -alignment;
}
int paddingNeeded = alignment - charsWritten;
if (paddingNeeded > 0)
{
EnsureCapacityForAdditionalChars(paddingNeeded);
if (leftAlign)
{
_chars.Slice(_pos, paddingNeeded).Fill(' ');
}
else
{
_chars.Slice(startingPos, charsWritten).CopyTo(_chars.Slice(startingPos + paddingNeeded));
_chars.Slice(startingPos, paddingNeeded).Fill(' ');
}
_pos += paddingNeeded;
}
}
/// <summary>Ensures <see cref="_chars"/> has the capacity to store <paramref name="additionalChars"/> beyond <see cref="_pos"/>.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacityForAdditionalChars(int additionalChars)
{
if (_chars.Length - _pos < additionalChars)
{
Grow(additionalChars);
}
}
/// <summary>Fallback for fast path in <see cref="AppendStringDirect"/> when there's not enough space in the destination.</summary>
/// <param name="value">The string to write.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowThenCopyString(string value)
{
Grow(value.Length);
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
/// <summary>Fallback for <see cref="AppendFormatted(ReadOnlySpan{char})"/> for when not enough space exists in the current buffer.</summary>
/// <param name="value">The span to write.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowThenCopySpan(ReadOnlySpan<char> value)
{
Grow(value.Length);
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
/// <summary>Grows <see cref="_chars"/> to have the capacity to store at least <paramref name="additionalChars"/> beyond <see cref="_pos"/>.</summary>
[MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible
private void Grow(int additionalChars)
{
// This method is called when the remaining space (_chars.Length - _pos) is
// insufficient to store a specific number of additional characters. Thus, we
// need to grow to at least that new total. GrowCore will handle growing by more
// than that if possible.
Debug.Assert(additionalChars > _chars.Length - _pos);
GrowCore((uint)_pos + (uint)additionalChars);
}
/// <summary>Grows the size of <see cref="_chars"/>.</summary>
[MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible
private void Grow()
{
// This method is called when the remaining space in _chars isn't sufficient to continue
// the operation. Thus, we need at least one character beyond _chars.Length. GrowCore
// will handle growing by more than that if possible.
GrowCore((uint)_chars.Length + 1);
}
/// <summary>Grow the size of <see cref="_chars"/> to at least the specified <paramref name="requiredMinCapacity"/>.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines
private void GrowCore(uint requiredMinCapacity)
{
// We want the max of how much space we actually required and doubling our capacity (without going beyond the max allowed length). We
// also want to avoid asking for small arrays, to reduce the number of times we need to grow, and since we're working with unsigned
// ints that could technically overflow if someone tried to, for example, append a huge string to a huge string, we also clamp to int.MaxValue.
// Even if the array creation fails in such a case, we may later fail in ToStringAndClear.
uint newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint)_chars.Length * 2, string.MaxLength));
int arraySize = (int)Math.Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue);
char[] newArray = ArrayPool<char>.Shared.Rent(arraySize);
_chars.Slice(0, _pos).CopyTo(newArray);
char[]? toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = newArray;
if (toReturn is not null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/CodeGenBringUpTests/And1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
public class BringUpTest_And1
{
const int Pass = 100;
const int Fail = -1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int And1(int x) { return x & 1; }
public static int Main()
{
int y = And1(17);
if (y == 1) return Pass;
else return Fail;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
public class BringUpTest_And1
{
const int Pass = 100;
const int Fail = -1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int And1(int x) { return x & 1; }
public static int Main()
{
int y = And1(17);
if (y == 1) return Pass;
else return Fail;
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.ComponentModel.Composition/tests/System/UnitTesting/ExpectationCollectionOfIO.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.ObjectModel;
namespace System.UnitTesting
{
public class ExpectationCollection<TInput, TOutput> : Collection<Expectation<TInput, TOutput>>
{
public void Add(TInput input, TOutput output)
{
Add(new Expectation<TInput, TOutput>(input, 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.Collections.ObjectModel;
namespace System.UnitTesting
{
public class ExpectationCollection<TInput, TOutput> : Collection<Expectation<TInput, TOutput>>
{
public void Add(TInput input, TOutput output)
{
Add(new Expectation<TInput, TOutput>(input, output));
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509RevocationFlag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
namespace System.Security.Cryptography.X509Certificates
{
public enum X509RevocationFlag
{
EndCertificateOnly = 0,
EntireChain = 1,
ExcludeRoot = 2,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
namespace System.Security.Cryptography.X509Certificates
{
public enum X509RevocationFlag
{
EndCertificateOnly = 0,
EntireChain = 1,
ExcludeRoot = 2,
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/RegexParserTests.netfx.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.Runtime.Serialization.Formatters.Binary;
using Xunit;
using Xunit.Sdk;
namespace System.Text.RegularExpressions.Tests
{
public partial class RegexParserTests
{
/// <summary>
/// Checks that action throws either a RegexParseException or an ArgumentException depending on the
/// environment and the supplied error.
/// </summary>
/// <param name="error">The expected parse error</param>
/// <param name="action">The action to invoke.</param>
static partial void Throws(string pattern, RegexOptions options, RegexParseError error, int offset, Action action)
{
try
{
action();
}
catch (ArgumentException)
{
// On NetFramework, all we care about is whether the exception is thrown.
return;
}
catch (Exception e)
{
throw new XunitException($"Expected ArgumentException -> Actual: {e}");
}
throw new XunitException($"Expected ArgumentException with error: ({error}) -> Actual: No exception thrown");
}
/// <summary>
/// Checks that action succeeds or throws either a RegexParseException or an ArgumentException depending on the
// environment and the action.
/// </summary>
/// <param name="action">The action to invoke.</param>
static partial void MayThrow(Action action)
{
if (Record.Exception(action) is Exception e && e is not ArgumentException)
{
throw new XunitException($"Expected ArgumentException or no exception -> Actual: ({e})");
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;
using Xunit.Sdk;
namespace System.Text.RegularExpressions.Tests
{
public partial class RegexParserTests
{
/// <summary>
/// Checks that action throws either a RegexParseException or an ArgumentException depending on the
/// environment and the supplied error.
/// </summary>
/// <param name="error">The expected parse error</param>
/// <param name="action">The action to invoke.</param>
static partial void Throws(string pattern, RegexOptions options, RegexParseError error, int offset, Action action)
{
try
{
action();
}
catch (ArgumentException)
{
// On NetFramework, all we care about is whether the exception is thrown.
return;
}
catch (Exception e)
{
throw new XunitException($"Expected ArgumentException -> Actual: {e}");
}
throw new XunitException($"Expected ArgumentException with error: ({error}) -> Actual: No exception thrown");
}
/// <summary>
/// Checks that action succeeds or throws either a RegexParseException or an ArgumentException depending on the
// environment and the action.
/// </summary>
/// <param name="action">The action to invoke.</param>
static partial void MayThrow(Action action)
{
if (Record.Exception(action) is Exception e && e is not ArgumentException)
{
throw new XunitException($"Expected ArgumentException or no exception -> Actual: ({e})");
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.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.Xml;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal abstract class DescendantBaseQuery : BaseAxisQuery
{
protected bool matchSelf;
protected bool abbrAxis;
public DescendantBaseQuery(Query qyParent, string Name, string Prefix, XPathNodeType Type, bool matchSelf, bool abbrAxis) : base(qyParent, Name, Prefix, Type)
{
this.matchSelf = matchSelf;
this.abbrAxis = abbrAxis;
}
public DescendantBaseQuery(DescendantBaseQuery other) : base(other)
{
this.matchSelf = other.matchSelf;
this.abbrAxis = other.abbrAxis;
}
public override XPathNavigator? MatchNode(XPathNavigator? context)
{
if (context != null)
{
if (!abbrAxis)
{
throw XPathException.Create(SR.Xp_InvalidPattern);
}
XPathNavigator? result;
if (matches(context))
{
if (matchSelf)
{
if ((result = qyInput.MatchNode(context)) != null)
{
return result;
}
}
XPathNavigator anc = context.Clone();
while (anc.MoveToParent())
{
if ((result = qyInput.MatchNode(anc)) != null)
{
return result;
}
}
}
}
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;
using System.Xml;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal abstract class DescendantBaseQuery : BaseAxisQuery
{
protected bool matchSelf;
protected bool abbrAxis;
public DescendantBaseQuery(Query qyParent, string Name, string Prefix, XPathNodeType Type, bool matchSelf, bool abbrAxis) : base(qyParent, Name, Prefix, Type)
{
this.matchSelf = matchSelf;
this.abbrAxis = abbrAxis;
}
public DescendantBaseQuery(DescendantBaseQuery other) : base(other)
{
this.matchSelf = other.matchSelf;
this.abbrAxis = other.abbrAxis;
}
public override XPathNavigator? MatchNode(XPathNavigator? context)
{
if (context != null)
{
if (!abbrAxis)
{
throw XPathException.Create(SR.Xp_InvalidPattern);
}
XPathNavigator? result;
if (matches(context))
{
if (matchSelf)
{
if ((result = qyInput.MatchNode(context)) != null)
{
return result;
}
}
XPathNavigator anc = context.Clone();
while (anc.MoveToParent())
{
if ((result = qyInput.MatchNode(anc)) != null)
{
return result;
}
}
}
}
return null;
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.SqlTypes
{
[XmlSchemaProvider("GetXsdType")]
public struct SqlBinary : INullable, IComparable, IXmlSerializable, IEquatable<SqlBinary>
{
// NOTE: If any instance fields change, update SqlTypeWorkarounds type in System.Data.SqlClient.
private byte[]? _value;
private SqlBinary(bool fNull)
{
_value = null;
}
/// <summary>
/// Initializes a new instance of the <see cref='SqlBinary'/> class with a binary object to be stored.
/// </summary>
public SqlBinary(byte[]? value)
{
// if value is null, this generates a SqlBinary.Null
if (value == null)
{
_value = null;
}
else
{
_value = new byte[value.Length];
value.CopyTo(_value, 0);
}
}
/// <summary>
/// Initializes a new instance of the <see cref='SqlBinary'/> class with a binary object to be stored. This constructor will not copy the value.
/// </summary>
internal SqlBinary(byte[]? value, bool ignored)
{
// if value is null, this generates a SqlBinary.Null
_value = value;
}
// INullable
/// <summary>
/// Gets whether or not <see cref='Value'/> is null.
/// </summary>
public bool IsNull => _value is null;
// property: Value
/// <summary>
/// Gets or sets the value of the SQL binary object retrieved.
/// </summary>
public byte[] Value
{
get
{
if (_value is null)
{
throw new SqlNullValueException();
}
var value = new byte[_value.Length];
_value.CopyTo(value, 0);
return value;
}
}
// class indexer
public byte this[int index]
{
get
{
if (_value is null)
{
throw new SqlNullValueException();
}
return _value[index];
}
}
// property: Length
/// <summary>
/// Gets the length in bytes of <see cref='Value'/>.
/// </summary>
public int Length
{
get
{
if (_value != null)
{
return _value.Length;
}
throw new SqlNullValueException();
}
}
// Implicit conversion from byte[] to SqlBinary
// Alternative: constructor SqlBinary(bytep[])
/// <summary>
/// Converts a binary object to a <see cref='SqlBinary'/>.
/// </summary>
public static implicit operator SqlBinary(byte[] x) => new SqlBinary(x);
// Explicit conversion from SqlBinary to byte[]. Throw exception if x is Null.
// Alternative: Value property
/// <summary>
/// Converts a <see cref='SqlBinary'/> to a binary object.
/// </summary>
public static explicit operator byte[]?(SqlBinary x) => x.Value;
/// <summary>
/// Returns a string describing a <see cref='SqlBinary'/> object.
/// </summary>
public override string ToString() => _value is null ? SQLResource.NullString : $"SqlBinary({_value.Length})";
// Unary operators
// Binary operators
// Arithmetic operators
/// <summary>
/// Adds two instances of <see cref='SqlBinary'/> together.
/// </summary>
// Alternative method: SqlBinary.Concat
public static SqlBinary operator +(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return Null;
byte[] rgbResult = new byte[x.Value.Length + y.Value.Length];
x.Value.CopyTo(rgbResult, 0);
y.Value.CopyTo(rgbResult, x.Value.Length);
return new SqlBinary(rgbResult);
}
// Comparisons
private static EComparison PerformCompareByte(byte[] x, byte[] y)
{
// the smaller length of two arrays
int len = (x.Length < y.Length) ? x.Length : y.Length;
int i;
for (i = 0; i < len; ++i)
{
if (x[i] != y[i])
{
if (x[i] < y[i])
return EComparison.LT;
else
return EComparison.GT;
}
}
if (x.Length == y.Length)
return EComparison.EQ;
else
{
// if the remaining bytes are all zeroes, they are still equal.
byte bZero = 0;
if (x.Length < y.Length)
{
// array X is shorter
for (i = len; i < y.Length; ++i)
{
if (y[i] != bZero)
return EComparison.LT;
}
}
else
{
// array Y is shorter
for (i = len; i < x.Length; ++i)
{
if (x[i] != bZero)
return EComparison.GT;
}
}
return EComparison.EQ;
}
}
// Explicit conversion from SqlGuid to SqlBinary
/// <summary>
/// Converts a <see cref='System.Data.SqlTypes.SqlGuid'/> to a <see cref='SqlBinary'/>.
/// </summary>
public static explicit operator SqlBinary(SqlGuid x) // Alternative method: SqlGuid.ToSqlBinary
{
return x.IsNull ? SqlBinary.Null : new SqlBinary(x.ToByteArray());
}
// Builtin functions
// Overloading comparison operators
/// <summary>
/// Compares two instances of <see cref='SqlBinary'/> for equality.
/// </summary>
public static SqlBoolean operator ==(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.EQ);
}
/// <summary>
/// Compares two instances of <see cref='SqlBinary'/>
/// for equality.
/// </summary>
public static SqlBoolean operator !=(SqlBinary x, SqlBinary y)
{
return !(x == y);
}
/// <summary>
/// Compares the first <see cref='SqlBinary'/> for being less than the
/// second <see cref='SqlBinary'/>.
/// </summary>
public static SqlBoolean operator <(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.LT);
}
/// <summary>
/// Compares the first <see cref='SqlBinary'/> for being greater than the second <see cref='SqlBinary'/>.
/// </summary>
public static SqlBoolean operator >(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.GT);
}
/// <summary>
/// Compares the first <see cref='SqlBinary'/> for being less than or equal to the second <see cref='SqlBinary'/>.
/// </summary>
public static SqlBoolean operator <=(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
EComparison cmpResult = PerformCompareByte(x.Value, y.Value);
return new SqlBoolean(cmpResult == EComparison.LT || cmpResult == EComparison.EQ);
}
/// <summary>
/// Compares the first <see cref='SqlBinary'/> for being greater than or equal the second <see cref='SqlBinary'/>.
/// </summary>
public static SqlBoolean operator >=(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
EComparison cmpResult = PerformCompareByte(x.Value, y.Value);
return new SqlBoolean(cmpResult == EComparison.GT || cmpResult == EComparison.EQ);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator +
public static SqlBinary Add(SqlBinary x, SqlBinary y)
{
return x + y;
}
public static SqlBinary Concat(SqlBinary x, SqlBinary y)
{
return x + y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlBinary x, SqlBinary y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlBinary x, SqlBinary y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlBinary x, SqlBinary y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlBinary x, SqlBinary y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlBinary x, SqlBinary y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlBinary x, SqlBinary y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlGuid ToSqlGuid()
{
return (SqlGuid)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object? value)
{
if (value is SqlBinary)
{
SqlBinary i = (SqlBinary)value;
return CompareTo(i);
}
throw ADP.WrongType(value!.GetType(), typeof(SqlBinary));
}
public int CompareTo(SqlBinary value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
public override bool Equals([NotNullWhen(true)] object? value) =>
value is SqlBinary other && Equals(other);
/// <summary>Indicates whether the current instance is equal to another instance of the same type.</summary>
/// <param name="other">An instance to compare with this instance.</param>
/// <returns>true if the current instance is equal to the other instance; otherwise, false.</returns>
public bool Equals(SqlBinary other) =>
other.IsNull || IsNull ? other.IsNull && IsNull :
(this == other).Value;
// Hash a byte array.
// Trailing zeroes/spaces would affect the hash value, so caller needs to
// perform trimming as necessary.
internal static int HashByteArray(byte[] rgbValue, int length)
{
Debug.Assert(length >= 0);
if (length <= 0)
return 0;
Debug.Assert(rgbValue.Length >= length);
int ulValue = 0;
int ulHi;
// Size of CRC window (hashing bytes, ssstr, sswstr, numeric)
const int x_cbCrcWindow = 4;
// const int iShiftVal = (sizeof ulValue) * (8*sizeof(char)) - x_cbCrcWindow;
const int iShiftVal = 4 * 8 - x_cbCrcWindow;
for (int i = 0; i < length; i++)
{
ulHi = (ulValue >> iShiftVal) & 0xff;
ulValue <<= x_cbCrcWindow;
ulValue = ulValue ^ rgbValue[i] ^ ulHi;
}
return ulValue;
}
// For hashing purpose
public override int GetHashCode()
{
if (_value is null)
return 0;
//First trim off extra '\0's
int cbLen = _value.Length;
while (cbLen > 0 && _value[cbLen - 1] == 0)
--cbLen;
return HashByteArray(_value, cbLen);
}
XmlSchema? IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
_value = null;
}
else
{
string base64 = reader.ReadElementString();
if (base64 == null)
{
_value = Array.Empty<byte>();
}
else
{
base64 = base64.Trim();
if (base64.Length == 0)
{
_value = Array.Empty<byte>();
}
else
{
_value = Convert.FromBase64String(base64);
}
}
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (_value is null)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(Convert.ToBase64String(_value));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("base64Binary", XmlSchema.Namespace);
}
/// <summary>
/// Represents a null value that can be assigned to the <see cref='Value'/> property of an
/// instance of the <see cref='SqlBinary'/> class.
/// </summary>
public static readonly SqlBinary Null = new SqlBinary(true);
} // SqlBinary
} // namespace System.Data.SqlTypes
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.SqlTypes
{
[XmlSchemaProvider("GetXsdType")]
public struct SqlBinary : INullable, IComparable, IXmlSerializable, IEquatable<SqlBinary>
{
// NOTE: If any instance fields change, update SqlTypeWorkarounds type in System.Data.SqlClient.
private byte[]? _value;
private SqlBinary(bool fNull)
{
_value = null;
}
/// <summary>
/// Initializes a new instance of the <see cref='SqlBinary'/> class with a binary object to be stored.
/// </summary>
public SqlBinary(byte[]? value)
{
// if value is null, this generates a SqlBinary.Null
if (value == null)
{
_value = null;
}
else
{
_value = new byte[value.Length];
value.CopyTo(_value, 0);
}
}
/// <summary>
/// Initializes a new instance of the <see cref='SqlBinary'/> class with a binary object to be stored. This constructor will not copy the value.
/// </summary>
internal SqlBinary(byte[]? value, bool ignored)
{
// if value is null, this generates a SqlBinary.Null
_value = value;
}
// INullable
/// <summary>
/// Gets whether or not <see cref='Value'/> is null.
/// </summary>
public bool IsNull => _value is null;
// property: Value
/// <summary>
/// Gets or sets the value of the SQL binary object retrieved.
/// </summary>
public byte[] Value
{
get
{
if (_value is null)
{
throw new SqlNullValueException();
}
var value = new byte[_value.Length];
_value.CopyTo(value, 0);
return value;
}
}
// class indexer
public byte this[int index]
{
get
{
if (_value is null)
{
throw new SqlNullValueException();
}
return _value[index];
}
}
// property: Length
/// <summary>
/// Gets the length in bytes of <see cref='Value'/>.
/// </summary>
public int Length
{
get
{
if (_value != null)
{
return _value.Length;
}
throw new SqlNullValueException();
}
}
// Implicit conversion from byte[] to SqlBinary
// Alternative: constructor SqlBinary(bytep[])
/// <summary>
/// Converts a binary object to a <see cref='SqlBinary'/>.
/// </summary>
public static implicit operator SqlBinary(byte[] x) => new SqlBinary(x);
// Explicit conversion from SqlBinary to byte[]. Throw exception if x is Null.
// Alternative: Value property
/// <summary>
/// Converts a <see cref='SqlBinary'/> to a binary object.
/// </summary>
public static explicit operator byte[]?(SqlBinary x) => x.Value;
/// <summary>
/// Returns a string describing a <see cref='SqlBinary'/> object.
/// </summary>
public override string ToString() => _value is null ? SQLResource.NullString : $"SqlBinary({_value.Length})";
// Unary operators
// Binary operators
// Arithmetic operators
/// <summary>
/// Adds two instances of <see cref='SqlBinary'/> together.
/// </summary>
// Alternative method: SqlBinary.Concat
public static SqlBinary operator +(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return Null;
byte[] rgbResult = new byte[x.Value.Length + y.Value.Length];
x.Value.CopyTo(rgbResult, 0);
y.Value.CopyTo(rgbResult, x.Value.Length);
return new SqlBinary(rgbResult);
}
// Comparisons
private static EComparison PerformCompareByte(byte[] x, byte[] y)
{
// the smaller length of two arrays
int len = (x.Length < y.Length) ? x.Length : y.Length;
int i;
for (i = 0; i < len; ++i)
{
if (x[i] != y[i])
{
if (x[i] < y[i])
return EComparison.LT;
else
return EComparison.GT;
}
}
if (x.Length == y.Length)
return EComparison.EQ;
else
{
// if the remaining bytes are all zeroes, they are still equal.
byte bZero = 0;
if (x.Length < y.Length)
{
// array X is shorter
for (i = len; i < y.Length; ++i)
{
if (y[i] != bZero)
return EComparison.LT;
}
}
else
{
// array Y is shorter
for (i = len; i < x.Length; ++i)
{
if (x[i] != bZero)
return EComparison.GT;
}
}
return EComparison.EQ;
}
}
// Explicit conversion from SqlGuid to SqlBinary
/// <summary>
/// Converts a <see cref='System.Data.SqlTypes.SqlGuid'/> to a <see cref='SqlBinary'/>.
/// </summary>
public static explicit operator SqlBinary(SqlGuid x) // Alternative method: SqlGuid.ToSqlBinary
{
return x.IsNull ? SqlBinary.Null : new SqlBinary(x.ToByteArray());
}
// Builtin functions
// Overloading comparison operators
/// <summary>
/// Compares two instances of <see cref='SqlBinary'/> for equality.
/// </summary>
public static SqlBoolean operator ==(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.EQ);
}
/// <summary>
/// Compares two instances of <see cref='SqlBinary'/>
/// for equality.
/// </summary>
public static SqlBoolean operator !=(SqlBinary x, SqlBinary y)
{
return !(x == y);
}
/// <summary>
/// Compares the first <see cref='SqlBinary'/> for being less than the
/// second <see cref='SqlBinary'/>.
/// </summary>
public static SqlBoolean operator <(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.LT);
}
/// <summary>
/// Compares the first <see cref='SqlBinary'/> for being greater than the second <see cref='SqlBinary'/>.
/// </summary>
public static SqlBoolean operator >(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.GT);
}
/// <summary>
/// Compares the first <see cref='SqlBinary'/> for being less than or equal to the second <see cref='SqlBinary'/>.
/// </summary>
public static SqlBoolean operator <=(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
EComparison cmpResult = PerformCompareByte(x.Value, y.Value);
return new SqlBoolean(cmpResult == EComparison.LT || cmpResult == EComparison.EQ);
}
/// <summary>
/// Compares the first <see cref='SqlBinary'/> for being greater than or equal the second <see cref='SqlBinary'/>.
/// </summary>
public static SqlBoolean operator >=(SqlBinary x, SqlBinary y)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
EComparison cmpResult = PerformCompareByte(x.Value, y.Value);
return new SqlBoolean(cmpResult == EComparison.GT || cmpResult == EComparison.EQ);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator +
public static SqlBinary Add(SqlBinary x, SqlBinary y)
{
return x + y;
}
public static SqlBinary Concat(SqlBinary x, SqlBinary y)
{
return x + y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlBinary x, SqlBinary y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlBinary x, SqlBinary y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlBinary x, SqlBinary y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlBinary x, SqlBinary y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlBinary x, SqlBinary y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlBinary x, SqlBinary y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlGuid ToSqlGuid()
{
return (SqlGuid)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object? value)
{
if (value is SqlBinary)
{
SqlBinary i = (SqlBinary)value;
return CompareTo(i);
}
throw ADP.WrongType(value!.GetType(), typeof(SqlBinary));
}
public int CompareTo(SqlBinary value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
public override bool Equals([NotNullWhen(true)] object? value) =>
value is SqlBinary other && Equals(other);
/// <summary>Indicates whether the current instance is equal to another instance of the same type.</summary>
/// <param name="other">An instance to compare with this instance.</param>
/// <returns>true if the current instance is equal to the other instance; otherwise, false.</returns>
public bool Equals(SqlBinary other) =>
other.IsNull || IsNull ? other.IsNull && IsNull :
(this == other).Value;
// Hash a byte array.
// Trailing zeroes/spaces would affect the hash value, so caller needs to
// perform trimming as necessary.
internal static int HashByteArray(byte[] rgbValue, int length)
{
Debug.Assert(length >= 0);
if (length <= 0)
return 0;
Debug.Assert(rgbValue.Length >= length);
int ulValue = 0;
int ulHi;
// Size of CRC window (hashing bytes, ssstr, sswstr, numeric)
const int x_cbCrcWindow = 4;
// const int iShiftVal = (sizeof ulValue) * (8*sizeof(char)) - x_cbCrcWindow;
const int iShiftVal = 4 * 8 - x_cbCrcWindow;
for (int i = 0; i < length; i++)
{
ulHi = (ulValue >> iShiftVal) & 0xff;
ulValue <<= x_cbCrcWindow;
ulValue = ulValue ^ rgbValue[i] ^ ulHi;
}
return ulValue;
}
// For hashing purpose
public override int GetHashCode()
{
if (_value is null)
return 0;
//First trim off extra '\0's
int cbLen = _value.Length;
while (cbLen > 0 && _value[cbLen - 1] == 0)
--cbLen;
return HashByteArray(_value, cbLen);
}
XmlSchema? IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
_value = null;
}
else
{
string base64 = reader.ReadElementString();
if (base64 == null)
{
_value = Array.Empty<byte>();
}
else
{
base64 = base64.Trim();
if (base64.Length == 0)
{
_value = Array.Empty<byte>();
}
else
{
_value = Convert.FromBase64String(base64);
}
}
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (_value is null)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(Convert.ToBase64String(_value));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("base64Binary", XmlSchema.Namespace);
}
/// <summary>
/// Represents a null value that can be assigned to the <see cref='Value'/> property of an
/// instance of the <see cref='SqlBinary'/> class.
/// </summary>
public static readonly SqlBinary Null = new SqlBinary(true);
} // SqlBinary
} // namespace System.Data.SqlTypes
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/Arm/Dp/DotProductBySelectedQuadruplet.Vector64.Int32.Vector128.SByte.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 DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3()
{
var test = new SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_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__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_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(Int32[] inArray1, SByte[] inArray2, SByte[] inArray3, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<SByte, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector64<SByte> _fld2;
public Vector128<SByte> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3 testClass)
{
var result = Dp.DotProductBySelectedQuadruplet(_fld1, _fld2, _fld3, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3 testClass)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<SByte>* pFld2 = &_fld2)
fixed (Vector128<SByte>* pFld3 = &_fld3)
{
var result = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector128((SByte*)(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<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly byte Imm = 3;
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static SByte[] _data3 = new SByte[Op3ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector64<SByte> _clsVar2;
private static Vector128<SByte> _clsVar3;
private Vector64<Int32> _fld1;
private Vector64<SByte> _fld2;
private Vector128<SByte> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Dp.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Dp.DotProductBySelectedQuadruplet(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<SByte>>(_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 = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((SByte*)(_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(Dp).GetMethod(nameof(Dp.DotProductBySelectedQuadruplet), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<SByte>), typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray3Ptr),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Dp).GetMethod(nameof(Dp.DotProductBySelectedQuadruplet), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<SByte>), typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray3Ptr)),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Dp.DotProductBySelectedQuadruplet(
_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 (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector64<SByte>* pClsVar2 = &_clsVar2)
fixed (Vector128<SByte>* pClsVar3 = &_clsVar3)
{
var result = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector64((SByte*)(pClsVar2)),
AdvSimd.LoadVector128((SByte*)(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<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray3Ptr);
var result = Dp.DotProductBySelectedQuadruplet(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.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray3Ptr));
var result = Dp.DotProductBySelectedQuadruplet(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__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3();
var result = Dp.DotProductBySelectedQuadruplet(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__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector64<SByte>* pFld2 = &test._fld2)
fixed (Vector128<SByte>* pFld3 = &test._fld3)
{
var result = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector128((SByte*)(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 = Dp.DotProductBySelectedQuadruplet(_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 (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<SByte>* pFld2 = &_fld2)
fixed (Vector128<SByte>* pFld3 = &_fld3)
{
var result = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector128((SByte*)(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 = Dp.DotProductBySelectedQuadruplet(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 = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector64((SByte*)(&test._fld2)),
AdvSimd.LoadVector128((SByte*)(&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(Vector64<Int32> op1, Vector64<SByte> op2, Vector128<SByte> op3, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
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<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int32[] firstOp, SByte[] secondOp, SByte[] thirdOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.DotProduct(firstOp[i], secondOp, 4 * i, thirdOp, 4 * Imm) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Dp)}.{nameof(Dp.DotProductBySelectedQuadruplet)}<Int32>(Vector64<Int32>, Vector64<SByte>, Vector128<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3()
{
var test = new SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_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__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_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(Int32[] inArray1, SByte[] inArray2, SByte[] inArray3, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<SByte, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector64<SByte> _fld2;
public Vector128<SByte> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3 testClass)
{
var result = Dp.DotProductBySelectedQuadruplet(_fld1, _fld2, _fld3, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3 testClass)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<SByte>* pFld2 = &_fld2)
fixed (Vector128<SByte>* pFld3 = &_fld3)
{
var result = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector128((SByte*)(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<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly byte Imm = 3;
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static SByte[] _data3 = new SByte[Op3ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector64<SByte> _clsVar2;
private static Vector128<SByte> _clsVar3;
private Vector64<Int32> _fld1;
private Vector64<SByte> _fld2;
private Vector128<SByte> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleTernaryOpTest__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Dp.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Dp.DotProductBySelectedQuadruplet(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<SByte>>(_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 = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((SByte*)(_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(Dp).GetMethod(nameof(Dp.DotProductBySelectedQuadruplet), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<SByte>), typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray3Ptr),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Dp).GetMethod(nameof(Dp.DotProductBySelectedQuadruplet), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<SByte>), typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray3Ptr)),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Dp.DotProductBySelectedQuadruplet(
_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 (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector64<SByte>* pClsVar2 = &_clsVar2)
fixed (Vector128<SByte>* pClsVar3 = &_clsVar3)
{
var result = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector64((SByte*)(pClsVar2)),
AdvSimd.LoadVector128((SByte*)(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<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray3Ptr);
var result = Dp.DotProductBySelectedQuadruplet(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.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray3Ptr));
var result = Dp.DotProductBySelectedQuadruplet(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__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3();
var result = Dp.DotProductBySelectedQuadruplet(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__DotProductBySelectedQuadruplet_Vector64_Int32_Vector128_SByte_3();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector64<SByte>* pFld2 = &test._fld2)
fixed (Vector128<SByte>* pFld3 = &test._fld3)
{
var result = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector128((SByte*)(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 = Dp.DotProductBySelectedQuadruplet(_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 (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<SByte>* pFld2 = &_fld2)
fixed (Vector128<SByte>* pFld3 = &_fld3)
{
var result = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector128((SByte*)(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 = Dp.DotProductBySelectedQuadruplet(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 = Dp.DotProductBySelectedQuadruplet(
AdvSimd.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector64((SByte*)(&test._fld2)),
AdvSimd.LoadVector128((SByte*)(&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(Vector64<Int32> op1, Vector64<SByte> op2, Vector128<SByte> op3, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
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<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int32[] firstOp, SByte[] secondOp, SByte[] thirdOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.DotProduct(firstOp[i], secondOp, 4 * i, thirdOp, 4 * Imm) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Dp)}.{nameof(Dp.DotProductBySelectedQuadruplet)}<Int32>(Vector64<Int32>, Vector64<SByte>, Vector128<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/General/Vector256/Abs.SByte.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void AbsSByte()
{
var test = new VectorUnaryOpTest__AbsSByte();
// 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__AbsSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
return testStruct;
}
public void RunStructFldScenario(VectorUnaryOpTest__AbsSByte testClass)
{
var result = Vector256.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector256<SByte> _clsVar1;
private Vector256<SByte> _fld1;
private DataTable _dataTable;
static VectorUnaryOpTest__AbsSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
}
public VectorUnaryOpTest__AbsSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.Abs(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.Abs), new Type[] {
typeof(Vector256<SByte>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.Abs), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(SByte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr);
var result = Vector256.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__AbsSByte();
var result = Vector256.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != Math.Abs(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != Math.Abs(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Abs)}<SByte>(Vector256<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\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 AbsSByte()
{
var test = new VectorUnaryOpTest__AbsSByte();
// 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__AbsSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
return testStruct;
}
public void RunStructFldScenario(VectorUnaryOpTest__AbsSByte testClass)
{
var result = Vector256.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector256<SByte> _clsVar1;
private Vector256<SByte> _fld1;
private DataTable _dataTable;
static VectorUnaryOpTest__AbsSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
}
public VectorUnaryOpTest__AbsSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.Abs(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.Abs), new Type[] {
typeof(Vector256<SByte>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.Abs), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(SByte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr);
var result = Vector256.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__AbsSByte();
var result = Vector256.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != Math.Abs(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != Math.Abs(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Abs)}<SByte>(Vector256<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DesImplementation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Internal.Cryptography;
namespace System.Security.Cryptography
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "We are providing the implementation for DES, not consuming it.")]
internal sealed partial class DesImplementation : DES
{
private const int BitsPerByte = 8;
public override ICryptoTransform CreateDecryptor()
{
return CreateTransform(Key, IV, encrypting: false);
}
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: false);
}
public override ICryptoTransform CreateEncryptor()
{
return CreateTransform(Key, IV, encrypting: true);
}
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: true);
}
public override void GenerateIV()
{
IV = RandomNumberGenerator.GetBytes(BlockSize / BitsPerByte);
}
public sealed override void GenerateKey()
{
byte[] key = new byte[KeySize / BitsPerByte];
RandomNumberGenerator.Fill(key);
// Never hand back a weak or semi-weak key
while (IsWeakKey(key) || IsSemiWeakKey(key))
{
RandomNumberGenerator.Fill(key);
}
KeyValue = key;
}
private ICryptoTransform CreateTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting)
{
// note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again
long keySize = rgbKey.Length * (long)BitsPerByte;
if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(LegalKeySizes))
throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey));
if (IsWeakKey(rgbKey))
throw new CryptographicException(SR.Cryptography_InvalidKey_Weak, "DES");
if (IsSemiWeakKey(rgbKey))
throw new CryptographicException(SR.Cryptography_InvalidKey_SemiWeak, "DES");
if (rgbIV != null)
{
long ivSize = rgbIV.Length * (long)BitsPerByte;
if (ivSize != BlockSize)
throw new ArgumentException(SR.Cryptography_InvalidIVSize, nameof(rgbIV));
}
if (Mode == CipherMode.CFB)
{
ValidateCFBFeedbackSize(FeedbackSize);
}
return CreateTransformCore(
Mode,
Padding,
rgbKey,
rgbIV,
BlockSize / BitsPerByte,
FeedbackSize / BitsPerByte,
this.GetPaddingSize(Mode, FeedbackSize),
encrypting);
}
protected override bool TryDecryptEcbCore(
ReadOnlySpan<byte> ciphertext,
Span<byte> destination,
PaddingMode paddingMode,
out int bytesWritten)
{
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.ECB,
paddingMode,
Key,
iv: null,
blockSize: BlockSize / BitsPerByte,
0, /*feedback size */
paddingSize: BlockSize / BitsPerByte,
encrypting: false);
using (cipher)
{
return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten);
}
}
protected override bool TryEncryptEcbCore(
ReadOnlySpan<byte> plaintext,
Span<byte> destination,
PaddingMode paddingMode,
out int bytesWritten)
{
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.ECB,
paddingMode,
Key,
iv: null,
blockSize: BlockSize / BitsPerByte,
0, /*feedback size */
paddingSize: BlockSize / BitsPerByte,
encrypting: true);
using (cipher)
{
return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten);
}
}
protected override bool TryEncryptCbcCore(
ReadOnlySpan<byte> plaintext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode,
out int bytesWritten)
{
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.CBC,
paddingMode,
Key,
iv,
blockSize: BlockSize / BitsPerByte,
0, /*feedback size */
paddingSize: BlockSize / BitsPerByte,
encrypting: true);
using (cipher)
{
return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten);
}
}
protected override bool TryDecryptCbcCore(
ReadOnlySpan<byte> ciphertext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode,
out int bytesWritten)
{
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.CBC,
paddingMode,
Key,
iv,
blockSize: BlockSize / BitsPerByte,
0, /*feedback size */
paddingSize: BlockSize / BitsPerByte,
encrypting: false);
using (cipher)
{
return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten);
}
}
protected override bool TryDecryptCfbCore(
ReadOnlySpan<byte> ciphertext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode,
int feedbackSizeInBits,
out int bytesWritten)
{
ValidateCFBFeedbackSize(feedbackSizeInBits);
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.CFB,
paddingMode,
Key,
iv,
blockSize: BlockSize / BitsPerByte,
feedbackSizeInBits / BitsPerByte,
paddingSize: feedbackSizeInBits / BitsPerByte,
encrypting: false);
using (cipher)
{
return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten);
}
}
protected override bool TryEncryptCfbCore(
ReadOnlySpan<byte> plaintext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode,
int feedbackSizeInBits,
out int bytesWritten)
{
ValidateCFBFeedbackSize(feedbackSizeInBits);
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.CFB,
paddingMode,
Key,
iv,
blockSize: BlockSize / BitsPerByte,
feedbackSizeInBits / BitsPerByte,
paddingSize: feedbackSizeInBits / BitsPerByte,
encrypting: true);
using (cipher)
{
return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten);
}
}
private static void ValidateCFBFeedbackSize(int feedback)
{
// only 8bits feedback is available on all platforms
if (feedback != 8)
{
throw new CryptographicException(string.Format(SR.Cryptography_CipherModeFeedbackNotSupported, feedback, CipherMode.CFB));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Internal.Cryptography;
namespace System.Security.Cryptography
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "We are providing the implementation for DES, not consuming it.")]
internal sealed partial class DesImplementation : DES
{
private const int BitsPerByte = 8;
public override ICryptoTransform CreateDecryptor()
{
return CreateTransform(Key, IV, encrypting: false);
}
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: false);
}
public override ICryptoTransform CreateEncryptor()
{
return CreateTransform(Key, IV, encrypting: true);
}
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: true);
}
public override void GenerateIV()
{
IV = RandomNumberGenerator.GetBytes(BlockSize / BitsPerByte);
}
public sealed override void GenerateKey()
{
byte[] key = new byte[KeySize / BitsPerByte];
RandomNumberGenerator.Fill(key);
// Never hand back a weak or semi-weak key
while (IsWeakKey(key) || IsSemiWeakKey(key))
{
RandomNumberGenerator.Fill(key);
}
KeyValue = key;
}
private ICryptoTransform CreateTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting)
{
// note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again
long keySize = rgbKey.Length * (long)BitsPerByte;
if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(LegalKeySizes))
throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey));
if (IsWeakKey(rgbKey))
throw new CryptographicException(SR.Cryptography_InvalidKey_Weak, "DES");
if (IsSemiWeakKey(rgbKey))
throw new CryptographicException(SR.Cryptography_InvalidKey_SemiWeak, "DES");
if (rgbIV != null)
{
long ivSize = rgbIV.Length * (long)BitsPerByte;
if (ivSize != BlockSize)
throw new ArgumentException(SR.Cryptography_InvalidIVSize, nameof(rgbIV));
}
if (Mode == CipherMode.CFB)
{
ValidateCFBFeedbackSize(FeedbackSize);
}
return CreateTransformCore(
Mode,
Padding,
rgbKey,
rgbIV,
BlockSize / BitsPerByte,
FeedbackSize / BitsPerByte,
this.GetPaddingSize(Mode, FeedbackSize),
encrypting);
}
protected override bool TryDecryptEcbCore(
ReadOnlySpan<byte> ciphertext,
Span<byte> destination,
PaddingMode paddingMode,
out int bytesWritten)
{
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.ECB,
paddingMode,
Key,
iv: null,
blockSize: BlockSize / BitsPerByte,
0, /*feedback size */
paddingSize: BlockSize / BitsPerByte,
encrypting: false);
using (cipher)
{
return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten);
}
}
protected override bool TryEncryptEcbCore(
ReadOnlySpan<byte> plaintext,
Span<byte> destination,
PaddingMode paddingMode,
out int bytesWritten)
{
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.ECB,
paddingMode,
Key,
iv: null,
blockSize: BlockSize / BitsPerByte,
0, /*feedback size */
paddingSize: BlockSize / BitsPerByte,
encrypting: true);
using (cipher)
{
return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten);
}
}
protected override bool TryEncryptCbcCore(
ReadOnlySpan<byte> plaintext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode,
out int bytesWritten)
{
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.CBC,
paddingMode,
Key,
iv,
blockSize: BlockSize / BitsPerByte,
0, /*feedback size */
paddingSize: BlockSize / BitsPerByte,
encrypting: true);
using (cipher)
{
return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten);
}
}
protected override bool TryDecryptCbcCore(
ReadOnlySpan<byte> ciphertext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode,
out int bytesWritten)
{
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.CBC,
paddingMode,
Key,
iv,
blockSize: BlockSize / BitsPerByte,
0, /*feedback size */
paddingSize: BlockSize / BitsPerByte,
encrypting: false);
using (cipher)
{
return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten);
}
}
protected override bool TryDecryptCfbCore(
ReadOnlySpan<byte> ciphertext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode,
int feedbackSizeInBits,
out int bytesWritten)
{
ValidateCFBFeedbackSize(feedbackSizeInBits);
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.CFB,
paddingMode,
Key,
iv,
blockSize: BlockSize / BitsPerByte,
feedbackSizeInBits / BitsPerByte,
paddingSize: feedbackSizeInBits / BitsPerByte,
encrypting: false);
using (cipher)
{
return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten);
}
}
protected override bool TryEncryptCfbCore(
ReadOnlySpan<byte> plaintext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode,
int feedbackSizeInBits,
out int bytesWritten)
{
ValidateCFBFeedbackSize(feedbackSizeInBits);
ILiteSymmetricCipher cipher = CreateLiteCipher(
CipherMode.CFB,
paddingMode,
Key,
iv,
blockSize: BlockSize / BitsPerByte,
feedbackSizeInBits / BitsPerByte,
paddingSize: feedbackSizeInBits / BitsPerByte,
encrypting: true);
using (cipher)
{
return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten);
}
}
private static void ValidateCFBFeedbackSize(int feedback)
{
// only 8bits feedback is available on all platforms
if (feedback != 8)
{
throw new CryptographicException(string.Format(SR.Cryptography_CipherModeFeedbackNotSupported, feedback, CipherMode.CFB));
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/LeadingSignCount.Vector64.SByte.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LeadingSignCount_Vector64_SByte()
{
var test = new SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte testClass)
{
var result = AdvSimd.LeadingSignCount(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte testClass)
{
fixed (Vector64<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(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<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector64<SByte> _clsVar1;
private Vector64<SByte> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.LeadingSignCount(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingSignCount), new Type[] { typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingSignCount), new Type[] { typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.LeadingSignCount(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<SByte>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var result = AdvSimd.LeadingSignCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr));
var result = AdvSimd.LeadingSignCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte();
var result = AdvSimd.LeadingSignCount(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__LeadingSignCount_Vector64_SByte();
fixed (Vector64<SByte>* pFld1 = &test._fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.LeadingSignCount(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.LeadingSignCount(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.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.CountLeadingSignBits(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LeadingSignCount)}<SByte>(Vector64<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LeadingSignCount_Vector64_SByte()
{
var test = new SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte testClass)
{
var result = AdvSimd.LeadingSignCount(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte testClass)
{
fixed (Vector64<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(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<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector64<SByte> _clsVar1;
private Vector64<SByte> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.LeadingSignCount(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingSignCount), new Type[] { typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingSignCount), new Type[] { typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.LeadingSignCount(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<SByte>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var result = AdvSimd.LeadingSignCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr));
var result = AdvSimd.LeadingSignCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte();
var result = AdvSimd.LeadingSignCount(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__LeadingSignCount_Vector64_SByte();
fixed (Vector64<SByte>* pFld1 = &test._fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.LeadingSignCount(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.LeadingSignCount(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.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.CountLeadingSignBits(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LeadingSignCount)}<SByte>(Vector64<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.Xml.Linq/tests/TreeManipulation/XElementChangedNotificationTests.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.Xml;
using System.Xml.Linq;
using Xunit;
namespace XLinqTests
{
public class XElementChangedNotificationTests
{
public class SkipNotifyTests
{
[Fact]
public void AddEventXElementShouldBeNotified()
{
var el = new XElement("test");
bool changedNotification = false;
var handler = new EventHandler<XObjectChangeEventArgs>(
(sender, cea) =>
{
changedNotification = true;
}
);
el.Changed += handler;
var child = new XElement("test2");
el.Add(child);
Assert.True(changedNotification);
changedNotification = false;
child.Add(new XAttribute("a", "b"));
Assert.True(changedNotification);
}
[Fact]
public void AddRemoveEventXElementShouldNotBeNotified()
{
var el = new XElement("test");
bool changedNotification = false;
var handler = new EventHandler<XObjectChangeEventArgs>(
(sender, cea) =>
{
changedNotification = true;
}
);
el.Changed += handler;
el.Changed -= handler;
var child = new XElement("test2");
el.Add(child);
Assert.False(changedNotification);
changedNotification = false;
child.Add(new XAttribute("a", "b"));
Assert.False(changedNotification);
}
[Fact]
public void AddEventXElementShouldBeNotifiedWithAnnotations()
{
var el = new XElement("test");
bool changedNotification = false;
var handler = new EventHandler<XObjectChangeEventArgs>(
(sender, cea) =>
{
changedNotification = true;
}
);
el.AddAnnotation(new object());
el.Changed += handler;
var child = new XElement("test2");
el.Add(child);
Assert.True(changedNotification);
changedNotification = false;
child.Add(new XAttribute("a", "b"));
Assert.True(changedNotification);
}
[Fact]
public void AddRemoveEventXElementShouldNotBeNotifiedWithAnnotations()
{
var el = new XElement("test");
bool changedNotification = false;
var handler = new EventHandler<XObjectChangeEventArgs>(
(sender, cea) =>
{
changedNotification = true;
}
);
el.AddAnnotation(new object());
el.Changed += handler;
el.Changed -= handler;
var child = new XElement("test2");
el.Add(child);
Assert.False(changedNotification);
changedNotification = false;
child.Add(new XAttribute("a", "b"));
Assert.False(changedNotification);
}
}
}
}
| // 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.Xml;
using System.Xml.Linq;
using Xunit;
namespace XLinqTests
{
public class XElementChangedNotificationTests
{
public class SkipNotifyTests
{
[Fact]
public void AddEventXElementShouldBeNotified()
{
var el = new XElement("test");
bool changedNotification = false;
var handler = new EventHandler<XObjectChangeEventArgs>(
(sender, cea) =>
{
changedNotification = true;
}
);
el.Changed += handler;
var child = new XElement("test2");
el.Add(child);
Assert.True(changedNotification);
changedNotification = false;
child.Add(new XAttribute("a", "b"));
Assert.True(changedNotification);
}
[Fact]
public void AddRemoveEventXElementShouldNotBeNotified()
{
var el = new XElement("test");
bool changedNotification = false;
var handler = new EventHandler<XObjectChangeEventArgs>(
(sender, cea) =>
{
changedNotification = true;
}
);
el.Changed += handler;
el.Changed -= handler;
var child = new XElement("test2");
el.Add(child);
Assert.False(changedNotification);
changedNotification = false;
child.Add(new XAttribute("a", "b"));
Assert.False(changedNotification);
}
[Fact]
public void AddEventXElementShouldBeNotifiedWithAnnotations()
{
var el = new XElement("test");
bool changedNotification = false;
var handler = new EventHandler<XObjectChangeEventArgs>(
(sender, cea) =>
{
changedNotification = true;
}
);
el.AddAnnotation(new object());
el.Changed += handler;
var child = new XElement("test2");
el.Add(child);
Assert.True(changedNotification);
changedNotification = false;
child.Add(new XAttribute("a", "b"));
Assert.True(changedNotification);
}
[Fact]
public void AddRemoveEventXElementShouldNotBeNotifiedWithAnnotations()
{
var el = new XElement("test");
bool changedNotification = false;
var handler = new EventHandler<XObjectChangeEventArgs>(
(sender, cea) =>
{
changedNotification = true;
}
);
el.AddAnnotation(new object());
el.Changed += handler;
el.Changed -= handler;
var child = new XElement("test2");
el.Add(child);
Assert.False(changedNotification);
changedNotification = false;
child.Add(new XAttribute("a", "b"));
Assert.False(changedNotification);
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/Common/src/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static unsafe partial class Kernel32
{
internal const int LOCALE_NAME_MAX_LENGTH = 85;
[GeneratedDllImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static unsafe partial class Kernel32
{
internal const int LOCALE_NAME_MAX_LENGTH = 85;
[GeneratedDllImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName);
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Match.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;
using System.Diagnostics.CodeAnalysis;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents the results from a single regular expression match.
/// </summary>
/// <remarks>
/// Match is the result class for a regex search.
/// It returns the location, length, and substring for
/// the entire match as well as every captured group.
///
/// Match is also used during the search to keep track of each capture for each group. This is
/// done using the "_matches" array. _matches[x] represents an array of the captures for group x.
/// This array consists of start and length pairs, and may have empty entries at the end. _matchcount[x]
/// stores how many captures a group has. Note that _matchcount[x]*2 is the length of all the valid
/// values in _matches. _matchcount[x]*2-2 is the Start of the last capture, and _matchcount[x]*2-1 is the
/// Length of the last capture
///
/// For example, if group 2 has one capture starting at position 4 with length 6,
/// _matchcount[2] == 1
/// _matches[2][0] == 4
/// _matches[2][1] == 6
///
/// Values in the _matches array can also be negative. This happens when using the balanced match
/// construct, "(?<start-end>...)". When the "end" group matches, a capture is added for both the "start"
/// and "end" groups. The capture added for "start" receives the negative values, and these values point to
/// the next capture to be balanced. They do NOT point to the capture that "end" just balanced out. The negative
/// values are indices into the _matches array transformed by the formula -3-x. This formula also untransforms.
/// </remarks>
public class Match : Group
{
internal GroupCollection? _groupcoll;
// input to the match
internal Regex? _regex;
internal int _textbeg;
internal int _textpos;
internal int _textend;
internal int _textstart;
// output from the match
internal int[][] _matches;
internal int[] _matchcount;
internal bool _balancing; // whether we've done any balancing with this match. If we
// have done balancing, we'll need to do extra work in Tidy().
internal Match(Regex? regex, int capcount, string? text, int begpos, int len, int startpos) :
base(text, new int[2], 0, "0")
{
_regex = regex;
_matchcount = new int[capcount];
_matches = new int[capcount][];
_matches[0] = _caps;
_textbeg = begpos;
_textend = begpos + len;
_textstart = startpos;
_balancing = false;
}
/// <summary>Returns an empty Match object.</summary>
public static Match Empty { get; } = new Match(null, 1, string.Empty, 0, 0, 0);
internal void Reset(Regex regex, string? text, int textbeg, int textend, int textstart)
{
_regex = regex;
Text = text;
_textbeg = textbeg;
_textend = textend;
_textstart = textstart;
int[] matchcount = _matchcount;
for (int i = 0; i < matchcount.Length; i++)
{
matchcount[i] = 0;
}
_balancing = false;
_groupcoll?.Reset();
}
/// <summary>
/// Returns <see langword="true"/> if this object represents a successful match, and <see langword="false"/> otherwise.
/// </summary>
/// <remarks>
/// The main difference between the public <see cref="Group.Success"/> property and this one, is that <see cref="Group.Success"/> requires
/// for a <see cref="Match"/> to call <see cref="Match.Tidy(int)"/> first, in order to report the correct value, while this API will return
/// the correct value right after a Match gets calculated, meaning that it will return <see langword="true"/> right after <see cref="RegexRunner.Capture(int, int, int)"/>
/// </remarks>
internal bool FoundMatch => _matchcount[0] > 0;
public virtual GroupCollection Groups => _groupcoll ??= new GroupCollection(this, null);
/// <summary>
/// Returns a new Match with the results for the next match, starting
/// at the position at which the last match ended (at the character beyond the last
/// matched character).
/// </summary>
public Match NextMatch()
{
Regex? r = _regex;
Debug.Assert(Text != null);
return r != null ?
r.Run(false, Length, Text, _textbeg, _textend - _textbeg, _textpos)! :
this;
}
/// <summary>
/// Returns the expansion of the passed replacement pattern. For
/// example, if the replacement pattern is ?$1$2?, Result returns the concatenation
/// of Group(1).ToString() and Group(2).ToString().
/// </summary>
public virtual string Result(string replacement)
{
if (replacement is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.replacement);
}
Regex? regex = _regex;
if (regex is null)
{
throw new NotSupportedException(SR.NoResultOnFailed);
}
// Gets the weakly cached replacement helper or creates one if there isn't one already.
RegexReplacement repl = RegexReplacement.GetOrCreate(regex.RegexReplacementWeakReference, replacement, regex.caps!, regex.capsize, regex.capnames!, regex.roptions);
SegmentStringBuilder segments = SegmentStringBuilder.Create();
repl.ReplacementImpl(ref segments, this);
return segments.ToString();
}
internal ReadOnlyMemory<char> GroupToStringImpl(int groupnum)
{
int c = _matchcount[groupnum];
if (c == 0)
{
return default;
}
int[] matches = _matches[groupnum];
return Text.AsMemory(matches[(c - 1) * 2], matches[(c * 2) - 1]);
}
internal ReadOnlyMemory<char> LastGroupToStringImpl() =>
GroupToStringImpl(_matchcount.Length - 1);
/// <summary>
/// Returns a Match instance equivalent to the one supplied that is safe to share
/// between multiple threads.
/// </summary>
public static Match Synchronized(Match inner)
{
if (inner is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.inner);
}
int numgroups = inner._matchcount.Length;
// Populate all groups by looking at each one
for (int i = 0; i < numgroups; i++)
{
// Depends on the fact that Group.Synchronized just
// operates on and returns the same instance
Synchronized(inner.Groups[i]);
}
return inner;
}
/// <summary>Adds a capture to the group specified by "cap"</summary>
internal void AddMatch(int cap, int start, int len)
{
_matches[cap] ??= new int[2];
int[][] matches = _matches;
int[] matchcount = _matchcount;
int capcount = matchcount[cap];
if (capcount * 2 + 2 > matches[cap].Length)
{
int[] oldmatches = matches[cap];
int[] newmatches = new int[capcount * 8];
for (int j = 0; j < capcount * 2; j++)
{
newmatches[j] = oldmatches[j];
}
matches[cap] = newmatches;
}
matches[cap][capcount * 2] = start;
matches[cap][capcount * 2 + 1] = len;
matchcount[cap] = capcount + 1;
}
/// <summary>
/// Nonpublic builder: Add a capture to balance the specified group. This is used by the
/// balanced match construct. (?<foo-foo2>...)
/// If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(cap).
/// However, since we have backtracking, we need to keep track of everything.
/// </summary>
internal void BalanceMatch(int cap)
{
_balancing = true;
// we'll look at the last capture first
int capcount = _matchcount[cap];
int target = capcount * 2 - 2;
// first see if it is negative, and therefore is a reference to the next available
// capture group for balancing. If it is, we'll reset target to point to that capture.
int[][] matches = _matches;
if (matches[cap][target] < 0)
{
target = -3 - matches[cap][target];
}
// move back to the previous capture
target -= 2;
// if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it.
if (target >= 0 && matches[cap][target] < 0)
{
AddMatch(cap, matches[cap][target], matches[cap][target + 1]);
}
else
{
AddMatch(cap, -3 - target, -4 - target /* == -3 - (target + 1) */ );
}
}
/// <summary>Removes a group match by capnum</summary>
internal void RemoveMatch(int cap) => _matchcount[cap]--;
/// <summary>Tells if a group was matched by capnum</summary>
internal bool IsMatched(int cap)
{
int[] matchcount = _matchcount;
return
(uint)cap < (uint)matchcount.Length &&
matchcount[cap] > 0 &&
_matches[cap][matchcount[cap] * 2 - 1] != (-3 + 1);
}
/// <summary>
/// Returns the index of the last specified matched group by capnum
/// </summary>
internal int MatchIndex(int cap)
{
int[][] matches = _matches;
int i = matches[cap][_matchcount[cap] * 2 - 2];
return i >= 0 ? i : matches[cap][-3 - i];
}
/// <summary>
/// Returns the length of the last specified matched group by capnum
/// </summary>
internal int MatchLength(int cap)
{
int[][] matches = _matches;
int i = matches[cap][_matchcount[cap] * 2 - 1];
return i >= 0 ? i : matches[cap][-3 - i];
}
/// <summary>Tidy the match so that it can be used as an immutable result</summary>
internal void Tidy(int textpos)
{
_textpos = textpos;
_capcount = _matchcount[0];
int[] interval = _matches[0];
Index = interval[0];
Length = interval[1];
if (_balancing)
{
TidyBalancing();
}
}
private void TidyBalancing()
{
int[] matchcount = _matchcount;
int[][] matches = _matches;
// The idea here is that we want to compact all of our unbalanced captures. To do that we
// use j basically as a count of how many unbalanced captures we have at any given time
// (really j is an index, but j/2 is the count). First we skip past all of the real captures
// until we find a balance captures. Then we check each subsequent entry. If it's a balance
// capture (it's negative), we decrement j. If it's a real capture, we increment j and copy
// it down to the last free position.
for (int cap = 0; cap < matchcount.Length; cap++)
{
int limit;
int[] matcharray;
limit = matchcount[cap] * 2;
matcharray = matches[cap];
int i;
int j;
for (i = 0; i < limit; i++)
{
if (matcharray[i] < 0)
{
break;
}
}
for (j = i; i < limit; i++)
{
if (matcharray[i] < 0)
{
// skip negative values
j--;
}
else
{
// but if we find something positive (an actual capture), copy it back to the last
// unbalanced position.
if (i != j)
{
matcharray[j] = matcharray[i];
}
j++;
}
}
matchcount[cap] = j / 2;
}
_balancing = false;
}
}
/// <summary>
/// MatchSparse is for handling the case where slots are sparsely arranged (e.g., if somebody says use slot 100000)
/// </summary>
internal sealed class MatchSparse : Match
{
private new readonly Hashtable _caps;
internal MatchSparse(Regex regex, Hashtable caps, int capcount, string? text, int begpos, int len, int startpos) :
base(regex, capcount, text, begpos, len, startpos)
{
_caps = caps;
}
public override GroupCollection Groups => _groupcoll ??= new GroupCollection(this, _caps);
}
}
| // 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;
using System.Diagnostics.CodeAnalysis;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents the results from a single regular expression match.
/// </summary>
/// <remarks>
/// Match is the result class for a regex search.
/// It returns the location, length, and substring for
/// the entire match as well as every captured group.
///
/// Match is also used during the search to keep track of each capture for each group. This is
/// done using the "_matches" array. _matches[x] represents an array of the captures for group x.
/// This array consists of start and length pairs, and may have empty entries at the end. _matchcount[x]
/// stores how many captures a group has. Note that _matchcount[x]*2 is the length of all the valid
/// values in _matches. _matchcount[x]*2-2 is the Start of the last capture, and _matchcount[x]*2-1 is the
/// Length of the last capture
///
/// For example, if group 2 has one capture starting at position 4 with length 6,
/// _matchcount[2] == 1
/// _matches[2][0] == 4
/// _matches[2][1] == 6
///
/// Values in the _matches array can also be negative. This happens when using the balanced match
/// construct, "(?<start-end>...)". When the "end" group matches, a capture is added for both the "start"
/// and "end" groups. The capture added for "start" receives the negative values, and these values point to
/// the next capture to be balanced. They do NOT point to the capture that "end" just balanced out. The negative
/// values are indices into the _matches array transformed by the formula -3-x. This formula also untransforms.
/// </remarks>
public class Match : Group
{
internal GroupCollection? _groupcoll;
// input to the match
internal Regex? _regex;
internal int _textbeg;
internal int _textpos;
internal int _textend;
internal int _textstart;
// output from the match
internal int[][] _matches;
internal int[] _matchcount;
internal bool _balancing; // whether we've done any balancing with this match. If we
// have done balancing, we'll need to do extra work in Tidy().
internal Match(Regex? regex, int capcount, string? text, int begpos, int len, int startpos) :
base(text, new int[2], 0, "0")
{
_regex = regex;
_matchcount = new int[capcount];
_matches = new int[capcount][];
_matches[0] = _caps;
_textbeg = begpos;
_textend = begpos + len;
_textstart = startpos;
_balancing = false;
}
/// <summary>Returns an empty Match object.</summary>
public static Match Empty { get; } = new Match(null, 1, string.Empty, 0, 0, 0);
internal void Reset(Regex regex, string? text, int textbeg, int textend, int textstart)
{
_regex = regex;
Text = text;
_textbeg = textbeg;
_textend = textend;
_textstart = textstart;
int[] matchcount = _matchcount;
for (int i = 0; i < matchcount.Length; i++)
{
matchcount[i] = 0;
}
_balancing = false;
_groupcoll?.Reset();
}
/// <summary>
/// Returns <see langword="true"/> if this object represents a successful match, and <see langword="false"/> otherwise.
/// </summary>
/// <remarks>
/// The main difference between the public <see cref="Group.Success"/> property and this one, is that <see cref="Group.Success"/> requires
/// for a <see cref="Match"/> to call <see cref="Match.Tidy(int)"/> first, in order to report the correct value, while this API will return
/// the correct value right after a Match gets calculated, meaning that it will return <see langword="true"/> right after <see cref="RegexRunner.Capture(int, int, int)"/>
/// </remarks>
internal bool FoundMatch => _matchcount[0] > 0;
public virtual GroupCollection Groups => _groupcoll ??= new GroupCollection(this, null);
/// <summary>
/// Returns a new Match with the results for the next match, starting
/// at the position at which the last match ended (at the character beyond the last
/// matched character).
/// </summary>
public Match NextMatch()
{
Regex? r = _regex;
Debug.Assert(Text != null);
return r != null ?
r.Run(false, Length, Text, _textbeg, _textend - _textbeg, _textpos)! :
this;
}
/// <summary>
/// Returns the expansion of the passed replacement pattern. For
/// example, if the replacement pattern is ?$1$2?, Result returns the concatenation
/// of Group(1).ToString() and Group(2).ToString().
/// </summary>
public virtual string Result(string replacement)
{
if (replacement is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.replacement);
}
Regex? regex = _regex;
if (regex is null)
{
throw new NotSupportedException(SR.NoResultOnFailed);
}
// Gets the weakly cached replacement helper or creates one if there isn't one already.
RegexReplacement repl = RegexReplacement.GetOrCreate(regex.RegexReplacementWeakReference, replacement, regex.caps!, regex.capsize, regex.capnames!, regex.roptions);
SegmentStringBuilder segments = SegmentStringBuilder.Create();
repl.ReplacementImpl(ref segments, this);
return segments.ToString();
}
internal ReadOnlyMemory<char> GroupToStringImpl(int groupnum)
{
int c = _matchcount[groupnum];
if (c == 0)
{
return default;
}
int[] matches = _matches[groupnum];
return Text.AsMemory(matches[(c - 1) * 2], matches[(c * 2) - 1]);
}
internal ReadOnlyMemory<char> LastGroupToStringImpl() =>
GroupToStringImpl(_matchcount.Length - 1);
/// <summary>
/// Returns a Match instance equivalent to the one supplied that is safe to share
/// between multiple threads.
/// </summary>
public static Match Synchronized(Match inner)
{
if (inner is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.inner);
}
int numgroups = inner._matchcount.Length;
// Populate all groups by looking at each one
for (int i = 0; i < numgroups; i++)
{
// Depends on the fact that Group.Synchronized just
// operates on and returns the same instance
Synchronized(inner.Groups[i]);
}
return inner;
}
/// <summary>Adds a capture to the group specified by "cap"</summary>
internal void AddMatch(int cap, int start, int len)
{
_matches[cap] ??= new int[2];
int[][] matches = _matches;
int[] matchcount = _matchcount;
int capcount = matchcount[cap];
if (capcount * 2 + 2 > matches[cap].Length)
{
int[] oldmatches = matches[cap];
int[] newmatches = new int[capcount * 8];
for (int j = 0; j < capcount * 2; j++)
{
newmatches[j] = oldmatches[j];
}
matches[cap] = newmatches;
}
matches[cap][capcount * 2] = start;
matches[cap][capcount * 2 + 1] = len;
matchcount[cap] = capcount + 1;
}
/// <summary>
/// Nonpublic builder: Add a capture to balance the specified group. This is used by the
/// balanced match construct. (?<foo-foo2>...)
/// If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(cap).
/// However, since we have backtracking, we need to keep track of everything.
/// </summary>
internal void BalanceMatch(int cap)
{
_balancing = true;
// we'll look at the last capture first
int capcount = _matchcount[cap];
int target = capcount * 2 - 2;
// first see if it is negative, and therefore is a reference to the next available
// capture group for balancing. If it is, we'll reset target to point to that capture.
int[][] matches = _matches;
if (matches[cap][target] < 0)
{
target = -3 - matches[cap][target];
}
// move back to the previous capture
target -= 2;
// if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it.
if (target >= 0 && matches[cap][target] < 0)
{
AddMatch(cap, matches[cap][target], matches[cap][target + 1]);
}
else
{
AddMatch(cap, -3 - target, -4 - target /* == -3 - (target + 1) */ );
}
}
/// <summary>Removes a group match by capnum</summary>
internal void RemoveMatch(int cap) => _matchcount[cap]--;
/// <summary>Tells if a group was matched by capnum</summary>
internal bool IsMatched(int cap)
{
int[] matchcount = _matchcount;
return
(uint)cap < (uint)matchcount.Length &&
matchcount[cap] > 0 &&
_matches[cap][matchcount[cap] * 2 - 1] != (-3 + 1);
}
/// <summary>
/// Returns the index of the last specified matched group by capnum
/// </summary>
internal int MatchIndex(int cap)
{
int[][] matches = _matches;
int i = matches[cap][_matchcount[cap] * 2 - 2];
return i >= 0 ? i : matches[cap][-3 - i];
}
/// <summary>
/// Returns the length of the last specified matched group by capnum
/// </summary>
internal int MatchLength(int cap)
{
int[][] matches = _matches;
int i = matches[cap][_matchcount[cap] * 2 - 1];
return i >= 0 ? i : matches[cap][-3 - i];
}
/// <summary>Tidy the match so that it can be used as an immutable result</summary>
internal void Tidy(int textpos)
{
_textpos = textpos;
_capcount = _matchcount[0];
int[] interval = _matches[0];
Index = interval[0];
Length = interval[1];
if (_balancing)
{
TidyBalancing();
}
}
private void TidyBalancing()
{
int[] matchcount = _matchcount;
int[][] matches = _matches;
// The idea here is that we want to compact all of our unbalanced captures. To do that we
// use j basically as a count of how many unbalanced captures we have at any given time
// (really j is an index, but j/2 is the count). First we skip past all of the real captures
// until we find a balance captures. Then we check each subsequent entry. If it's a balance
// capture (it's negative), we decrement j. If it's a real capture, we increment j and copy
// it down to the last free position.
for (int cap = 0; cap < matchcount.Length; cap++)
{
int limit;
int[] matcharray;
limit = matchcount[cap] * 2;
matcharray = matches[cap];
int i;
int j;
for (i = 0; i < limit; i++)
{
if (matcharray[i] < 0)
{
break;
}
}
for (j = i; i < limit; i++)
{
if (matcharray[i] < 0)
{
// skip negative values
j--;
}
else
{
// but if we find something positive (an actual capture), copy it back to the last
// unbalanced position.
if (i != j)
{
matcharray[j] = matcharray[i];
}
j++;
}
}
matchcount[cap] = j / 2;
}
_balancing = false;
}
}
/// <summary>
/// MatchSparse is for handling the case where slots are sparsely arranged (e.g., if somebody says use slot 100000)
/// </summary>
internal sealed class MatchSparse : Match
{
private new readonly Hashtable _caps;
internal MatchSparse(Regex regex, Hashtable caps, int capcount, string? text, int begpos, int len, int startpos) :
base(regex, capcount, text, begpos, len, startpos)
{
_caps = caps;
}
public override GroupCollection Groups => _groupcoll ??= new GroupCollection(this, _caps);
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/tests/JIT/HardwareIntrinsics/General/Vector64/LessThanAny.Int64.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void LessThanAnyInt64()
{
var test = new VectorBooleanBinaryOpTest__LessThanAnyInt64();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBooleanBinaryOpTest__LessThanAnyInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public Vector64<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanAnyInt64 testClass)
{
var result = Vector64.LessThanAny(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector64<Int64> _clsVar1;
private static Vector64<Int64> _clsVar2;
private Vector64<Int64> _fld1;
private Vector64<Int64> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__LessThanAnyInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
}
public VectorBooleanBinaryOpTest__LessThanAnyInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.LessThanAny(
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.LessThanAny), new Type[] {
typeof(Vector64<Int64>),
typeof(Vector64<Int64>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.LessThanAny), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int64));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.LessThanAny(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr);
var result = Vector64.LessThanAny(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__LessThanAnyInt64();
var result = Vector64.LessThanAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.LessThanAny(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.LessThanAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<Int64> op1, Vector64<Int64> op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = false;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult |= (left[i] < right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.LessThanAny)}<Int64>(Vector64<Int64>, Vector64<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void LessThanAnyInt64()
{
var test = new VectorBooleanBinaryOpTest__LessThanAnyInt64();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBooleanBinaryOpTest__LessThanAnyInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public Vector64<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanAnyInt64 testClass)
{
var result = Vector64.LessThanAny(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector64<Int64> _clsVar1;
private static Vector64<Int64> _clsVar2;
private Vector64<Int64> _fld1;
private Vector64<Int64> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__LessThanAnyInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
}
public VectorBooleanBinaryOpTest__LessThanAnyInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.LessThanAny(
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.LessThanAny), new Type[] {
typeof(Vector64<Int64>),
typeof(Vector64<Int64>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.LessThanAny), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int64));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.LessThanAny(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr);
var result = Vector64.LessThanAny(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__LessThanAnyInt64();
var result = Vector64.LessThanAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.LessThanAny(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.LessThanAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<Int64> op1, Vector64<Int64> op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = false;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult |= (left[i] < right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.LessThanAny)}<Int64>(Vector64<Int64>, Vector64<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssembly/MethodBody0.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;
namespace ApplyUpdateReferencedAssembly
{
public class MethodBodyUnchangedAssembly {
public static string StaticMethod1 () {
Console.WriteLine("original");
return "ok";
}
}
}
| // 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;
namespace ApplyUpdateReferencedAssembly
{
public class MethodBodyUnchangedAssembly {
public static string StaticMethod1 () {
Console.WriteLine("original");
return "ok";
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.JS.Owned.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Threading.Tasks;
namespace System.Runtime.InteropServices.JavaScript
{
public static partial class Runtime
{
private static object JSOwnedObjectLock = new object();
// we use this to maintain identity of GCHandle for a managed object
private static Dictionary<object, int> GCHandleFromJSOwnedObject = new Dictionary<object, int>();
public static object GetJSOwnedObjectByGCHandle(int gcHandle)
{
GCHandle h = (GCHandle)(IntPtr)gcHandle;
return h.Target!;
}
// A JSOwnedObject is a managed object with its lifetime controlled by javascript.
// The managed side maintains a strong reference to the object, while the JS side
// maintains a weak reference and notifies the managed side if the JS wrapper object
// has been reclaimed by the JS GC. At that point, the managed side will release its
// strong references, allowing the managed object to be collected.
// This ensures that things like delegates and promises will never 'go away' while JS
// is expecting to be able to invoke or await them.
public static int GetJSOwnedObjectGCHandle(object obj)
{
if (obj == null)
return 0;
int result;
lock (JSOwnedObjectLock)
{
if (GCHandleFromJSOwnedObject.TryGetValue(obj, out result))
return result;
result = (int)(IntPtr)GCHandle.Alloc(obj, GCHandleType.Normal);
GCHandleFromJSOwnedObject[obj] = result;
return result;
}
}
// The JS layer invokes this method when the JS wrapper for a JS owned object
// has been collected by the JS garbage collector
public static void ReleaseJSOwnedObjectByGCHandle(int gcHandle)
{
GCHandle handle = (GCHandle)(IntPtr)gcHandle;
lock (JSOwnedObjectLock)
{
GCHandleFromJSOwnedObject.Remove(handle.Target!);
handle.Free();
}
}
public static int CreateTaskSource()
{
var tcs = new TaskCompletionSource<object>();
return GetJSOwnedObjectGCHandle(tcs);
}
public static void SetTaskSourceResult(int tcsGCHandle, object result)
{
GCHandle handle = (GCHandle)(IntPtr)tcsGCHandle;
// this is JS owned Normal handle. We always have a Target
TaskCompletionSource<object> tcs = (TaskCompletionSource<object>)handle.Target!;
tcs.SetResult(result);
}
public static void SetTaskSourceFailure(int tcsGCHandle, string reason)
{
GCHandle handle = (GCHandle)(IntPtr)tcsGCHandle;
// this is JS owned Normal handle. We always have a Target
TaskCompletionSource<object> tcs = (TaskCompletionSource<object>)handle.Target!;
tcs.SetException(new JSException(reason));
}
public static object GetTaskSourceTask(int tcsGCHandle)
{
GCHandle handle = (GCHandle)(IntPtr)tcsGCHandle;
// this is JS owned Normal handle. We always have a Target
TaskCompletionSource<object> tcs = (TaskCompletionSource<object>)handle.Target!;
return tcs.Task;
}
public static object TaskFromResult(object? obj)
{
return Task.FromResult(obj);
}
public static void SetupJSContinuation(Task task, JSObject continuationObj)
{
if (task.IsCompleted)
Complete();
else
task.GetAwaiter().OnCompleted(Complete);
void Complete()
{
try
{
if (task.Exception == null)
{
object? result;
Type task_type = task.GetType();
if (task_type == typeof(Task))
{
result = System.Array.Empty<object>();
}
else
{
result = GetTaskResultMethodInfo(task_type)?.Invoke(task, null);
}
continuationObj.Invoke("resolve", result);
}
else
{
continuationObj.Invoke("reject", task.Exception.ToString());
}
}
catch (Exception e)
{
continuationObj.Invoke("reject", e.ToString());
}
finally
{
continuationObj.Dispose();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Threading.Tasks;
namespace System.Runtime.InteropServices.JavaScript
{
public static partial class Runtime
{
private static object JSOwnedObjectLock = new object();
// we use this to maintain identity of GCHandle for a managed object
private static Dictionary<object, int> GCHandleFromJSOwnedObject = new Dictionary<object, int>();
public static object GetJSOwnedObjectByGCHandle(int gcHandle)
{
GCHandle h = (GCHandle)(IntPtr)gcHandle;
return h.Target!;
}
// A JSOwnedObject is a managed object with its lifetime controlled by javascript.
// The managed side maintains a strong reference to the object, while the JS side
// maintains a weak reference and notifies the managed side if the JS wrapper object
// has been reclaimed by the JS GC. At that point, the managed side will release its
// strong references, allowing the managed object to be collected.
// This ensures that things like delegates and promises will never 'go away' while JS
// is expecting to be able to invoke or await them.
public static int GetJSOwnedObjectGCHandle(object obj)
{
if (obj == null)
return 0;
int result;
lock (JSOwnedObjectLock)
{
if (GCHandleFromJSOwnedObject.TryGetValue(obj, out result))
return result;
result = (int)(IntPtr)GCHandle.Alloc(obj, GCHandleType.Normal);
GCHandleFromJSOwnedObject[obj] = result;
return result;
}
}
// The JS layer invokes this method when the JS wrapper for a JS owned object
// has been collected by the JS garbage collector
public static void ReleaseJSOwnedObjectByGCHandle(int gcHandle)
{
GCHandle handle = (GCHandle)(IntPtr)gcHandle;
lock (JSOwnedObjectLock)
{
GCHandleFromJSOwnedObject.Remove(handle.Target!);
handle.Free();
}
}
public static int CreateTaskSource()
{
var tcs = new TaskCompletionSource<object>();
return GetJSOwnedObjectGCHandle(tcs);
}
public static void SetTaskSourceResult(int tcsGCHandle, object result)
{
GCHandle handle = (GCHandle)(IntPtr)tcsGCHandle;
// this is JS owned Normal handle. We always have a Target
TaskCompletionSource<object> tcs = (TaskCompletionSource<object>)handle.Target!;
tcs.SetResult(result);
}
public static void SetTaskSourceFailure(int tcsGCHandle, string reason)
{
GCHandle handle = (GCHandle)(IntPtr)tcsGCHandle;
// this is JS owned Normal handle. We always have a Target
TaskCompletionSource<object> tcs = (TaskCompletionSource<object>)handle.Target!;
tcs.SetException(new JSException(reason));
}
public static object GetTaskSourceTask(int tcsGCHandle)
{
GCHandle handle = (GCHandle)(IntPtr)tcsGCHandle;
// this is JS owned Normal handle. We always have a Target
TaskCompletionSource<object> tcs = (TaskCompletionSource<object>)handle.Target!;
return tcs.Task;
}
public static object TaskFromResult(object? obj)
{
return Task.FromResult(obj);
}
public static void SetupJSContinuation(Task task, JSObject continuationObj)
{
if (task.IsCompleted)
Complete();
else
task.GetAwaiter().OnCompleted(Complete);
void Complete()
{
try
{
if (task.Exception == null)
{
object? result;
Type task_type = task.GetType();
if (task_type == typeof(Task))
{
result = System.Array.Empty<object>();
}
else
{
result = GetTaskResultMethodInfo(task_type)?.Invoke(task, null);
}
continuationObj.Invoke("resolve", result);
}
else
{
continuationObj.Invoke("reject", task.Exception.ToString());
}
}
catch (Exception e)
{
continuationObj.Invoke("reject", e.ToString());
}
finally
{
continuationObj.Dispose();
}
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
namespace System.Linq
{
public abstract class EnumerableQuery
{
internal abstract Expression Expression { get; }
internal abstract IEnumerable? Enumerable { get; }
internal EnumerableQuery() { }
[RequiresUnreferencedCode(Queryable.InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)]
internal static IQueryable Create(Type elementType, IEnumerable sequence)
{
Type seqType = typeof(EnumerableQuery<>).MakeGenericType(elementType);
return (IQueryable)Activator.CreateInstance(seqType, sequence)!;
}
[RequiresUnreferencedCode(Queryable.InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)]
internal static IQueryable Create(Type elementType, Expression expression)
{
Type seqType = typeof(EnumerableQuery<>).MakeGenericType(elementType);
return (IQueryable)Activator.CreateInstance(seqType, expression)!;
}
}
public class EnumerableQuery<T> : EnumerableQuery, IOrderedQueryable<T>, IQueryProvider
{
private readonly Expression _expression;
private IEnumerable<T>? _enumerable;
IQueryProvider IQueryable.Provider => this;
[RequiresUnreferencedCode(Queryable.InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)]
public EnumerableQuery(IEnumerable<T> enumerable)
{
_enumerable = enumerable;
_expression = Expression.Constant(this);
}
[RequiresUnreferencedCode(Queryable.InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)]
public EnumerableQuery(Expression expression)
{
_expression = expression;
}
internal override Expression Expression => _expression;
internal override IEnumerable? Enumerable => _enumerable;
Expression IQueryable.Expression => _expression;
Type IQueryable.ElementType => typeof(T);
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
IQueryable IQueryProvider.CreateQuery(Expression expression!!)
{
Type? iqType = TypeHelper.FindGenericType(typeof(IQueryable<>), expression.Type);
if (iqType == null)
throw Error.ArgumentNotValid(nameof(expression));
return Create(iqType.GetGenericArguments()[0], expression);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
IQueryable<TElement> IQueryProvider.CreateQuery<TElement>(Expression expression!!)
{
if (!typeof(IQueryable<TElement>).IsAssignableFrom(expression.Type))
{
throw Error.ArgumentNotValid(nameof(expression));
}
return new EnumerableQuery<TElement>(expression);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
object? IQueryProvider.Execute(Expression expression!!)
{
return EnumerableExecutor.Create(expression).ExecuteBoxed();
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
TElement IQueryProvider.Execute<TElement>(Expression expression!!)
{
if (!typeof(TElement).IsAssignableFrom(expression.Type))
throw Error.ArgumentNotValid(nameof(expression));
return new EnumerableExecutor<TElement>(expression).Execute();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
private IEnumerator<T> GetEnumerator()
{
if (_enumerable == null)
{
EnumerableRewriter rewriter = new EnumerableRewriter();
Expression body = rewriter.Visit(_expression);
Expression<Func<IEnumerable<T>>> f = Expression.Lambda<Func<IEnumerable<T>>>(body, (IEnumerable<ParameterExpression>?)null);
IEnumerable<T> enumerable = f.Compile()();
if (enumerable == this)
throw Error.EnumeratingNullEnumerableExpression();
_enumerable = enumerable;
}
return _enumerable.GetEnumerator();
}
public override string? ToString()
{
if (_expression is ConstantExpression c && c.Value == this)
{
if (_enumerable != null)
return _enumerable.ToString();
return "null";
}
return _expression.ToString();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
namespace System.Linq
{
public abstract class EnumerableQuery
{
internal abstract Expression Expression { get; }
internal abstract IEnumerable? Enumerable { get; }
internal EnumerableQuery() { }
[RequiresUnreferencedCode(Queryable.InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)]
internal static IQueryable Create(Type elementType, IEnumerable sequence)
{
Type seqType = typeof(EnumerableQuery<>).MakeGenericType(elementType);
return (IQueryable)Activator.CreateInstance(seqType, sequence)!;
}
[RequiresUnreferencedCode(Queryable.InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)]
internal static IQueryable Create(Type elementType, Expression expression)
{
Type seqType = typeof(EnumerableQuery<>).MakeGenericType(elementType);
return (IQueryable)Activator.CreateInstance(seqType, expression)!;
}
}
public class EnumerableQuery<T> : EnumerableQuery, IOrderedQueryable<T>, IQueryProvider
{
private readonly Expression _expression;
private IEnumerable<T>? _enumerable;
IQueryProvider IQueryable.Provider => this;
[RequiresUnreferencedCode(Queryable.InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)]
public EnumerableQuery(IEnumerable<T> enumerable)
{
_enumerable = enumerable;
_expression = Expression.Constant(this);
}
[RequiresUnreferencedCode(Queryable.InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)]
public EnumerableQuery(Expression expression)
{
_expression = expression;
}
internal override Expression Expression => _expression;
internal override IEnumerable? Enumerable => _enumerable;
Expression IQueryable.Expression => _expression;
Type IQueryable.ElementType => typeof(T);
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
IQueryable IQueryProvider.CreateQuery(Expression expression!!)
{
Type? iqType = TypeHelper.FindGenericType(typeof(IQueryable<>), expression.Type);
if (iqType == null)
throw Error.ArgumentNotValid(nameof(expression));
return Create(iqType.GetGenericArguments()[0], expression);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
IQueryable<TElement> IQueryProvider.CreateQuery<TElement>(Expression expression!!)
{
if (!typeof(IQueryable<TElement>).IsAssignableFrom(expression.Type))
{
throw Error.ArgumentNotValid(nameof(expression));
}
return new EnumerableQuery<TElement>(expression);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
object? IQueryProvider.Execute(Expression expression!!)
{
return EnumerableExecutor.Create(expression).ExecuteBoxed();
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
TElement IQueryProvider.Execute<TElement>(Expression expression!!)
{
if (!typeof(TElement).IsAssignableFrom(expression.Type))
throw Error.ArgumentNotValid(nameof(expression));
return new EnumerableExecutor<TElement>(expression).Execute();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")]
private IEnumerator<T> GetEnumerator()
{
if (_enumerable == null)
{
EnumerableRewriter rewriter = new EnumerableRewriter();
Expression body = rewriter.Visit(_expression);
Expression<Func<IEnumerable<T>>> f = Expression.Lambda<Func<IEnumerable<T>>>(body, (IEnumerable<ParameterExpression>?)null);
IEnumerable<T> enumerable = f.Compile()();
if (enumerable == this)
throw Error.EnumeratingNullEnumerableExpression();
_enumerable = enumerable;
}
return _enumerable.GetEnumerator();
}
public override string? ToString()
{
if (_expression is ConstantExpression c && c.Value == this)
{
if (_enumerable != null)
return _enumerable.ToString();
return "null";
}
return _expression.ToString();
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Security.Permissions/src/System/Security/Permissions/DataProtectionPermissionFlags.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Security.Permissions
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[Flags]
public enum DataProtectionPermissionFlags
{
NoFlags = 0x00,
ProtectData = 0x01,
UnprotectData = 0x02,
ProtectMemory = 0x04,
UnprotectMemory = 0x08,
AllFlags = 0x0F
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Security.Permissions
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[Flags]
public enum DataProtectionPermissionFlags
{
NoFlags = 0x00,
ProtectData = 0x01,
UnprotectData = 0x02,
ProtectMemory = 0x04,
UnprotectMemory = 0x08,
AllFlags = 0x0F
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.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.ComponentModel;
namespace System.DirectoryServices.ActiveDirectory
{
public enum ForestTrustDomainStatus
{
Enabled = 0,
SidAdminDisabled = 1,
SidConflictDisabled = 2,
NetBiosNameAdminDisabled = 4,
NetBiosNameConflictDisabled = 8
}
public class ForestTrustDomainInformation
{
private ForestTrustDomainStatus _status;
internal LARGE_INTEGER time;
internal ForestTrustDomainInformation(int flag, LSA_FOREST_TRUST_DOMAIN_INFO domainInfo, LARGE_INTEGER time)
{
_status = (ForestTrustDomainStatus)flag;
DnsName = Marshal.PtrToStringUni(domainInfo.DNSNameBuffer, domainInfo.DNSNameLength / 2);
NetBiosName = Marshal.PtrToStringUni(domainInfo.NetBIOSNameBuffer, domainInfo.NetBIOSNameLength / 2);
string sidLocal;
global::Interop.BOOL result = global::Interop.Advapi32.ConvertSidToStringSid(domainInfo.sid, out sidLocal);
if (result == global::Interop.BOOL.FALSE)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
DomainSid = sidLocal;
this.time = time;
}
public string DnsName { get; }
public string NetBiosName { get; }
public string DomainSid { get; }
public ForestTrustDomainStatus Status
{
get => _status;
set
{
if (value != ForestTrustDomainStatus.Enabled &&
value != ForestTrustDomainStatus.SidAdminDisabled &&
value != ForestTrustDomainStatus.SidConflictDisabled &&
value != ForestTrustDomainStatus.NetBiosNameAdminDisabled &&
value != ForestTrustDomainStatus.NetBiosNameConflictDisabled)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ForestTrustDomainStatus));
_status = 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.Runtime.InteropServices;
using System.ComponentModel;
namespace System.DirectoryServices.ActiveDirectory
{
public enum ForestTrustDomainStatus
{
Enabled = 0,
SidAdminDisabled = 1,
SidConflictDisabled = 2,
NetBiosNameAdminDisabled = 4,
NetBiosNameConflictDisabled = 8
}
public class ForestTrustDomainInformation
{
private ForestTrustDomainStatus _status;
internal LARGE_INTEGER time;
internal ForestTrustDomainInformation(int flag, LSA_FOREST_TRUST_DOMAIN_INFO domainInfo, LARGE_INTEGER time)
{
_status = (ForestTrustDomainStatus)flag;
DnsName = Marshal.PtrToStringUni(domainInfo.DNSNameBuffer, domainInfo.DNSNameLength / 2);
NetBiosName = Marshal.PtrToStringUni(domainInfo.NetBIOSNameBuffer, domainInfo.NetBIOSNameLength / 2);
string sidLocal;
global::Interop.BOOL result = global::Interop.Advapi32.ConvertSidToStringSid(domainInfo.sid, out sidLocal);
if (result == global::Interop.BOOL.FALSE)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
DomainSid = sidLocal;
this.time = time;
}
public string DnsName { get; }
public string NetBiosName { get; }
public string DomainSid { get; }
public ForestTrustDomainStatus Status
{
get => _status;
set
{
if (value != ForestTrustDomainStatus.Enabled &&
value != ForestTrustDomainStatus.SidAdminDisabled &&
value != ForestTrustDomainStatus.SidConflictDisabled &&
value != ForestTrustDomainStatus.NetBiosNameAdminDisabled &&
value != ForestTrustDomainStatus.NetBiosNameConflictDisabled)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ForestTrustDomainStatus));
_status = value;
}
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/InfiniteIntConverter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.ComponentModel;
using System.Diagnostics;
namespace System.Configuration
{
public sealed class InfiniteIntConverter : ConfigurationConverterBase
{
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
{
ValidateType(value, typeof(int));
return (int)value == int.MaxValue ? "Infinite" : ((int)value).ToString(CultureInfo.InvariantCulture);
}
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
Debug.Assert(data is string, "data is string");
return (string)data == "Infinite" ? int.MaxValue : Convert.ToInt32((string)data, 10);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.ComponentModel;
using System.Diagnostics;
namespace System.Configuration
{
public sealed class InfiniteIntConverter : ConfigurationConverterBase
{
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
{
ValidateType(value, typeof(int));
return (int)value == int.MaxValue ? "Infinite" : ((int)value).ToString(CultureInfo.InvariantCulture);
}
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
Debug.Assert(data is string, "data is string");
return (string)data == "Infinite" ? int.MaxValue : Convert.ToInt32((string)data, 10);
}
}
}
| -1 |
dotnet/runtime | 66,248 | Fix issues related to JsonSerializerOptions mutation and caching. | Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | eiriktsarpalis | 2022-03-05T19:59:48Z | 2022-03-07T19:44:14Z | 44ec3c9474b3a93eb4f71791a43d8bb5c0b08a58 | 8b4eaf94140f488743d0c78caa3afec3b9c5d789 | Fix issues related to JsonSerializerOptions mutation and caching.. Second attempt at merging https://github.com/dotnet/runtime/pull/65863. Original PR introduced test failures in netfx and was reverted in https://github.com/dotnet/runtime/pull/66235.
cc @jkotas | ./src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/TargetRegisterMap.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis.X64
{
/// <summary>
/// Maps logical registers to physical registers on a specified OS.
/// </summary>
public struct TargetRegisterMap
{
public readonly Register Arg0;
public readonly Register Arg1;
public readonly Register Arg2;
public readonly Register Arg3;
public readonly Register Result;
public TargetRegisterMap(TargetOS os)
{
switch (os)
{
case TargetOS.Windows:
Arg0 = Register.RCX;
Arg1 = Register.RDX;
Arg2 = Register.R8;
Arg3 = Register.R9;
Result = Register.RAX;
break;
case TargetOS.Linux:
case TargetOS.OSX:
case TargetOS.FreeBSD:
case TargetOS.SunOS:
case TargetOS.NetBSD:
Arg0 = Register.RDI;
Arg1 = Register.RSI;
Arg2 = Register.RDX;
Arg3 = Register.RCX;
Result = Register.RAX;
break;
default:
throw new NotImplementedException();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis.X64
{
/// <summary>
/// Maps logical registers to physical registers on a specified OS.
/// </summary>
public struct TargetRegisterMap
{
public readonly Register Arg0;
public readonly Register Arg1;
public readonly Register Arg2;
public readonly Register Arg3;
public readonly Register Result;
public TargetRegisterMap(TargetOS os)
{
switch (os)
{
case TargetOS.Windows:
Arg0 = Register.RCX;
Arg1 = Register.RDX;
Arg2 = Register.R8;
Arg3 = Register.R9;
Result = Register.RAX;
break;
case TargetOS.Linux:
case TargetOS.OSX:
case TargetOS.FreeBSD:
case TargetOS.SunOS:
case TargetOS.NetBSD:
Arg0 = Register.RDI;
Arg1 = Register.RSI;
Arg2 = Register.RDX;
Arg3 = Register.RCX;
Result = Register.RAX;
break;
default:
throw new NotImplementedException();
}
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.