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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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="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="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>
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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.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);
}
}
| // 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);
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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 (!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));
}
}
| // 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));
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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 (!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!;
}
}
}
| // 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!;
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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.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;
}
}
}
| // 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;
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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 => _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);
}
}
| // 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);
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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);
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
}
}
}
| // 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
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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;
// 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;
}
}
}
| // 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;
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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();
// 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;
}
}
}
| // 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;
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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.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);
}
}
}
| // 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);
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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 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 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));
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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
// - 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
{
}
}
}
| // 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
{
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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))]
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;
}
}
}
}
| // 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;
}
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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 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>);
}
}
[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!));
}
}
}
| // 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!));
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./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()));
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;
}
}
}
}
}
| // 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;
}
}
}
}
}
| 1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlKnownDtds.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.Resolvers
{
//
// XmlPreloadedResolver is an XmlResolver that which can be pre-loaded with data.
// By default it contains well-known DTDs for XHTML 1.0 and RSS 0.91.
// Custom mappings of URIs to data can be added with the Add method.
//
[Flags]
public enum XmlKnownDtds
{
None = 0x00,
Xhtml10 = 0x01,
Rss091 = 0x02,
All = 0xFFFF,
}
}
| // 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.Resolvers
{
//
// XmlPreloadedResolver is an XmlResolver that which can be pre-loaded with data.
// By default it contains well-known DTDs for XHTML 1.0 and RSS 0.91.
// Custom mappings of URIs to data can be added with the Add method.
//
[Flags]
public enum XmlKnownDtds
{
None = 0x00,
Xhtml10 = 0x01,
Rss091 = 0x02,
All = 0xFFFF,
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/X86/Sse41/TestNotZAndNotC.Int32.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestNotZAndNotCInt32()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestNotZAndNotCInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCInt32 testClass)
{
var result = Sse41.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.TestNotZAndNotC(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.TestNotZAndNotC(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse41.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestNotZAndNotCInt32()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestNotZAndNotCInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCInt32 testClass)
{
var result = Sse41.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.TestNotZAndNotC(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.TestNotZAndNotC(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse41.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Abs.Vector64.Int16.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Abs_Vector64_Int16()
{
var test = new SimpleUnaryOpTest__Abs_Vector64_Int16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__Abs_Vector64_Int16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
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<Int16, 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<Int16> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-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>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__Abs_Vector64_Int16 testClass)
{
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__Abs_Vector64_Int16 testClass)
{
fixed (Vector64<Int16>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector64((Int16*)(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<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Vector64<Int16> _clsVar1;
private Vector64<Int16> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__Abs_Vector64_Int16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-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>>());
}
public SimpleUnaryOpTest__Abs_Vector64_Int16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-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 < Op1ElementCount; i++) { _data1[i] = (short)-TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Abs(
Unsafe.Read<Vector64<Int16>>(_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.Abs(
AdvSimd.LoadVector64((Int16*)(_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.Abs), new Type[] { typeof(Vector64<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector64<Int16>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int16>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector64((Int16*)(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<Int16>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__Abs_Vector64_Int16();
var result = AdvSimd.Abs(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__Abs_Vector64_Int16();
fixed (Vector64<Int16>* pFld1 = &test._fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector64((Int16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int16>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector64((Int16*)(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.Abs(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.Abs(
AdvSimd.LoadVector64((Int16*)(&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<Int16> op1, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
UInt16[] outArray = new UInt16[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<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Abs(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<UInt16>(Vector64<Int16>): {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 Abs_Vector64_Int16()
{
var test = new SimpleUnaryOpTest__Abs_Vector64_Int16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__Abs_Vector64_Int16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
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<Int16, 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<Int16> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-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>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__Abs_Vector64_Int16 testClass)
{
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__Abs_Vector64_Int16 testClass)
{
fixed (Vector64<Int16>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector64((Int16*)(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<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Vector64<Int16> _clsVar1;
private Vector64<Int16> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__Abs_Vector64_Int16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-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>>());
}
public SimpleUnaryOpTest__Abs_Vector64_Int16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-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 < Op1ElementCount; i++) { _data1[i] = (short)-TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Abs(
Unsafe.Read<Vector64<Int16>>(_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.Abs(
AdvSimd.LoadVector64((Int16*)(_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.Abs), new Type[] { typeof(Vector64<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector64<Int16>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int16>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector64((Int16*)(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<Int16>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__Abs_Vector64_Int16();
var result = AdvSimd.Abs(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__Abs_Vector64_Int16();
fixed (Vector64<Int16>* pFld1 = &test._fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector64((Int16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int16>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector64((Int16*)(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.Abs(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.Abs(
AdvSimd.LoadVector64((Int16*)(&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<Int16> op1, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
UInt16[] outArray = new UInt16[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<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Abs(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<UInt16>(Vector64<Int16>): {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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/LocalAppContextSwitches.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.CompilerServices;
namespace System
{
internal static partial class LocalAppContextSwitches
{
public static bool DefaultActivityIdFormatIsHierarchial { get; } = InitializeDefaultActivityIdFormat();
private static bool InitializeDefaultActivityIdFormat()
{
bool defaultActivityIdFormatIsHierarchial = false;
if (!LocalAppContextSwitches.GetSwitchValue("System.Diagnostics.DefaultActivityIdFormatIsHierarchial", ref defaultActivityIdFormatIsHierarchial))
{
string? switchValue = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_DIAGNOSTICS_DEFAULTACTIVITYIDFORMATISHIERARCHIAL");
if (switchValue != null)
{
defaultActivityIdFormatIsHierarchial = IsTrueStringIgnoreCase(switchValue) || switchValue.Equals("1");
}
}
return defaultActivityIdFormatIsHierarchial;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsTrueStringIgnoreCase(string value)
{
return value.Length == 4 &&
(value[0] == 't' || value[0] == 'T') &&
(value[1] == 'r' || value[1] == 'R') &&
(value[2] == 'u' || value[2] == 'U') &&
(value[3] == 'e' || value[3] == '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.Runtime.CompilerServices;
namespace System
{
internal static partial class LocalAppContextSwitches
{
public static bool DefaultActivityIdFormatIsHierarchial { get; } = InitializeDefaultActivityIdFormat();
private static bool InitializeDefaultActivityIdFormat()
{
bool defaultActivityIdFormatIsHierarchial = false;
if (!LocalAppContextSwitches.GetSwitchValue("System.Diagnostics.DefaultActivityIdFormatIsHierarchial", ref defaultActivityIdFormatIsHierarchial))
{
string? switchValue = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_DIAGNOSTICS_DEFAULTACTIVITYIDFORMATISHIERARCHIAL");
if (switchValue != null)
{
defaultActivityIdFormatIsHierarchial = IsTrueStringIgnoreCase(switchValue) || switchValue.Equals("1");
}
}
return defaultActivityIdFormatIsHierarchial;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsTrueStringIgnoreCase(string value)
{
return value.Length == 4 &&
(value[0] == 't' || value[0] == 'T') &&
(value[1] == 'r' || value[1] == 'R') &&
(value[2] == 'u' || value[2] == 'U') &&
(value[3] == 'e' || value[3] == 'E');
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/General/Vector256/GreaterThanOrEqualAll.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 GreaterThanOrEqualAllInt16()
{
var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16();
// 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__GreaterThanOrEqualAllInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
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<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 Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16 testClass)
{
var result = Vector256.GreaterThanOrEqualAll(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.GreaterThanOrEqualAll(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanOrEqualAll), new Type[] {
typeof(Vector256<Int16>),
typeof(Vector256<Int16>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanOrEqualAll), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int16));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.GreaterThanOrEqualAll(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Vector256.GreaterThanOrEqualAll(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16();
var result = Vector256.GreaterThanOrEqualAll(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.GreaterThanOrEqualAll(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.GreaterThanOrEqualAll(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= (left[i] >= right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.GreaterThanOrEqualAll)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({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 GreaterThanOrEqualAllInt16()
{
var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16();
// 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__GreaterThanOrEqualAllInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
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<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 Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16 testClass)
{
var result = Vector256.GreaterThanOrEqualAll(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.GreaterThanOrEqualAll(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanOrEqualAll), new Type[] {
typeof(Vector256<Int16>),
typeof(Vector256<Int16>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanOrEqualAll), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int16));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.GreaterThanOrEqualAll(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Vector256.GreaterThanOrEqualAll(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllInt16();
var result = Vector256.GreaterThanOrEqualAll(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.GreaterThanOrEqualAll(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.GreaterThanOrEqualAll(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= (left[i] >= right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.GreaterThanOrEqualAll)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AddHighNarrowingUpper.Vector128.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.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 AddHighNarrowingUpper_Vector128_UInt32()
{
var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32();
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__AddHighNarrowingUpper_Vector128_UInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt64[] inArray2, UInt64[] inArray3, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt64, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* 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<UInt32> _fld1;
public Vector128<UInt64> _fld2;
public Vector128<UInt64> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<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.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>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32 testClass)
{
var result = AdvSimd.AddHighNarrowingUpper(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32 testClass)
{
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
fixed (Vector128<UInt64>* pFld3 = &_fld3)
{
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2)),
AdvSimd.LoadVector128((UInt64*)(pFld3))
);
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<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static UInt64[] _data3 = new UInt64[Op3ElementCount];
private static Vector64<UInt32> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private static Vector128<UInt64> _clsVar3;
private Vector64<UInt32> _fld1;
private Vector128<UInt64> _fld2;
private Vector128<UInt64> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32()
{
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.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32()
{
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.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 < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.AddHighNarrowingUpper(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingUpper), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingUpper), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddHighNarrowingUpper(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
fixed (Vector128<UInt64>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(pClsVar2)),
AdvSimd.LoadVector128((UInt64*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr);
var result = AdvSimd.AddHighNarrowingUpper(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray3Ptr));
var result = AdvSimd.AddHighNarrowingUpper(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32();
var result = AdvSimd.AddHighNarrowingUpper(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32();
fixed (Vector64<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
fixed (Vector128<UInt64>* pFld3 = &test._fld3)
{
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2)),
AdvSimd.LoadVector128((UInt64*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddHighNarrowingUpper(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
fixed (Vector128<UInt64>* pFld3 = &_fld3)
{
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2)),
AdvSimd.LoadVector128((UInt64*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AddHighNarrowingUpper(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&test._fld2)),
AdvSimd.LoadVector128((UInt64*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt32> op1, Vector128<UInt64> op2, Vector128<UInt64> op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] inArray3 = new UInt64[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] inArray3 = new UInt64[Op3ElementCount];
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<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt64[] secondOp, UInt64[] thirdOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AddHighNarrowingUpper(firstOp, secondOp, thirdOp, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddHighNarrowingUpper)}<UInt32>(Vector64<UInt32>, Vector128<UInt64>, Vector128<UInt64>): {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 AddHighNarrowingUpper_Vector128_UInt32()
{
var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32();
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__AddHighNarrowingUpper_Vector128_UInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt64[] inArray2, UInt64[] inArray3, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt64, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* 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<UInt32> _fld1;
public Vector128<UInt64> _fld2;
public Vector128<UInt64> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<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.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>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32 testClass)
{
var result = AdvSimd.AddHighNarrowingUpper(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32 testClass)
{
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
fixed (Vector128<UInt64>* pFld3 = &_fld3)
{
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2)),
AdvSimd.LoadVector128((UInt64*)(pFld3))
);
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<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static UInt64[] _data3 = new UInt64[Op3ElementCount];
private static Vector64<UInt32> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private static Vector128<UInt64> _clsVar3;
private Vector64<UInt32> _fld1;
private Vector128<UInt64> _fld2;
private Vector128<UInt64> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32()
{
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.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32()
{
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.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 < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.AddHighNarrowingUpper(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingUpper), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingUpper), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddHighNarrowingUpper(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
fixed (Vector128<UInt64>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(pClsVar2)),
AdvSimd.LoadVector128((UInt64*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray3Ptr);
var result = AdvSimd.AddHighNarrowingUpper(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray3Ptr));
var result = AdvSimd.AddHighNarrowingUpper(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32();
var result = AdvSimd.AddHighNarrowingUpper(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_UInt32();
fixed (Vector64<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
fixed (Vector128<UInt64>* pFld3 = &test._fld3)
{
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2)),
AdvSimd.LoadVector128((UInt64*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddHighNarrowingUpper(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
fixed (Vector128<UInt64>* pFld3 = &_fld3)
{
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2)),
AdvSimd.LoadVector128((UInt64*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AddHighNarrowingUpper(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.AddHighNarrowingUpper(
AdvSimd.LoadVector64((UInt32*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&test._fld2)),
AdvSimd.LoadVector128((UInt64*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt32> op1, Vector128<UInt64> op2, Vector128<UInt64> op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] inArray3 = new UInt64[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] inArray3 = new UInt64[Op3ElementCount];
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<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt64[] secondOp, UInt64[] thirdOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AddHighNarrowingUpper(firstOp, secondOp, thirdOp, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddHighNarrowingUpper)}<UInt32>(Vector64<UInt32>, Vector128<UInt64>, Vector128<UInt64>): {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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/Directed/StructABI/StructWithOverlappingFields.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// This test originally showed incorrect VN for different fields with the same offset.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Opt_Error
{
[StructLayout(LayoutKind.Explicit, Pack = 1)]
public class FourByteClass
{
[FieldOffset(0)]
public int val;
[FieldOffset(0)]
public uint uval;
[FieldOffset(0)]
public float fval;
[FieldOffset(0)]
public byte b0;
[FieldOffset(1)]
public byte b1;
[FieldOffset(2)]
public byte b2;
[FieldOffset(3)]
public byte b3;
public FourByteClass(int val)
{
val = val;
}
}
[StructLayout(LayoutKind.Explicit, Pack = 1)]
public struct FourByteStruct
{
[FieldOffset(0)]
public int val;
[FieldOffset(0)]
public uint uval;
[FieldOffset(0)]
public float fval;
[FieldOffset(0)]
public byte b0;
[FieldOffset(1)]
public byte b1;
[FieldOffset(2)]
public byte b2;
[FieldOffset(3)]
public byte b3;
public FourByteStruct(int val)
{
this.val = 0;
uval = 0;
fval = 0;
b0 = 0;
b1 = 0;
b2 = 0;
b3 = 0;
this.val = val;
}
}
class Program
{
static void TestClass(int initVal)
{
FourByteClass fb = new FourByteClass(initVal);
fb.fval = 0;
fb.b0 = 1;
fb.uval = 2;
int cseb0_1 = fb.b0 * 5 + 3;
uint cse_uval_1 = fb.uval * 2 - 5 + fb.uval;
int cse_val_1 = fb.val * 7 - 4 + fb.val * 7;
Console.WriteLine("First result: " + cseb0_1 + ", " + cse_uval_1 + ", " + cse_val_1 + ";");
Debug.Assert(cseb0_1 == 13);
Debug.Assert(cse_uval_1 == 1);
Debug.Assert(cse_val_1 == 24);
fb.val = 4;
int cseb0_2 = fb.b0 * 5 + 3;
uint cse_uval_2 = fb.uval * 2 - 5 + fb.uval;
int cse_val_2 = fb.val * 7 - 4 + fb.val * 7;
Console.WriteLine("Second result: " + cseb0_2 + ", " + cse_uval_2 + ", " + cse_val_2 + ";");
Debug.Assert(cseb0_2 == 23);
Debug.Assert(cse_uval_2 == 7);
Debug.Assert(cse_val_2 == 52);
}
static void TestStruct(int initVal)
{
FourByteStruct fb = new FourByteStruct(initVal);
fb.fval = 0;
fb.b0 = 1;
fb.uval = 2;
int cseb0_1 = fb.b0 * 5 + 3;
uint cse_uval_1 = fb.uval * 2 - 5 + fb.uval;
int cse_val_1 = fb.val * 7 - 4 + fb.val * 7;
Console.WriteLine("First result: " + cseb0_1 + ", " + cse_uval_1 + ", " + cse_val_1 + ";");
Debug.Assert(cseb0_1 == 13);
Debug.Assert(cse_uval_1 == 1);
Debug.Assert(cse_val_1 == 24);
fb.val = 4;
int cseb0_2 = fb.b0 * 5 + 3;
uint cse_uval_2 = fb.uval * 2 - 5 + fb.uval;
int cse_val_2 = fb.val * 7 - 4 + fb.val * 7;
Console.WriteLine("Second result: " + cseb0_2 + ", " + cse_uval_2 + ", " + cse_val_2 + ";");
Debug.Assert(cseb0_2 == 23);
Debug.Assert(cse_uval_2 == 7);
Debug.Assert(cse_val_2 == 52);
}
static int Main(string[] args)
{
TestClass(2);
TestStruct(2);
return 100;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// This test originally showed incorrect VN for different fields with the same offset.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Opt_Error
{
[StructLayout(LayoutKind.Explicit, Pack = 1)]
public class FourByteClass
{
[FieldOffset(0)]
public int val;
[FieldOffset(0)]
public uint uval;
[FieldOffset(0)]
public float fval;
[FieldOffset(0)]
public byte b0;
[FieldOffset(1)]
public byte b1;
[FieldOffset(2)]
public byte b2;
[FieldOffset(3)]
public byte b3;
public FourByteClass(int val)
{
val = val;
}
}
[StructLayout(LayoutKind.Explicit, Pack = 1)]
public struct FourByteStruct
{
[FieldOffset(0)]
public int val;
[FieldOffset(0)]
public uint uval;
[FieldOffset(0)]
public float fval;
[FieldOffset(0)]
public byte b0;
[FieldOffset(1)]
public byte b1;
[FieldOffset(2)]
public byte b2;
[FieldOffset(3)]
public byte b3;
public FourByteStruct(int val)
{
this.val = 0;
uval = 0;
fval = 0;
b0 = 0;
b1 = 0;
b2 = 0;
b3 = 0;
this.val = val;
}
}
class Program
{
static void TestClass(int initVal)
{
FourByteClass fb = new FourByteClass(initVal);
fb.fval = 0;
fb.b0 = 1;
fb.uval = 2;
int cseb0_1 = fb.b0 * 5 + 3;
uint cse_uval_1 = fb.uval * 2 - 5 + fb.uval;
int cse_val_1 = fb.val * 7 - 4 + fb.val * 7;
Console.WriteLine("First result: " + cseb0_1 + ", " + cse_uval_1 + ", " + cse_val_1 + ";");
Debug.Assert(cseb0_1 == 13);
Debug.Assert(cse_uval_1 == 1);
Debug.Assert(cse_val_1 == 24);
fb.val = 4;
int cseb0_2 = fb.b0 * 5 + 3;
uint cse_uval_2 = fb.uval * 2 - 5 + fb.uval;
int cse_val_2 = fb.val * 7 - 4 + fb.val * 7;
Console.WriteLine("Second result: " + cseb0_2 + ", " + cse_uval_2 + ", " + cse_val_2 + ";");
Debug.Assert(cseb0_2 == 23);
Debug.Assert(cse_uval_2 == 7);
Debug.Assert(cse_val_2 == 52);
}
static void TestStruct(int initVal)
{
FourByteStruct fb = new FourByteStruct(initVal);
fb.fval = 0;
fb.b0 = 1;
fb.uval = 2;
int cseb0_1 = fb.b0 * 5 + 3;
uint cse_uval_1 = fb.uval * 2 - 5 + fb.uval;
int cse_val_1 = fb.val * 7 - 4 + fb.val * 7;
Console.WriteLine("First result: " + cseb0_1 + ", " + cse_uval_1 + ", " + cse_val_1 + ";");
Debug.Assert(cseb0_1 == 13);
Debug.Assert(cse_uval_1 == 1);
Debug.Assert(cse_val_1 == 24);
fb.val = 4;
int cseb0_2 = fb.b0 * 5 + 3;
uint cse_uval_2 = fb.uval * 2 - 5 + fb.uval;
int cse_val_2 = fb.val * 7 - 4 + fb.val * 7;
Console.WriteLine("Second result: " + cseb0_2 + ", " + cse_uval_2 + ", " + cse_val_2 + ";");
Debug.Assert(cseb0_2 == 23);
Debug.Assert(cse_uval_2 == 7);
Debug.Assert(cse_val_2 == 52);
}
static int Main(string[] args)
{
TestClass(2);
TestStruct(2);
return 100;
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableInterlocked.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.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Collections.Immutable
{
/// <summary>
/// Contains interlocked exchange mechanisms for immutable collections.
/// </summary>
public static class ImmutableInterlocked
{
/// <summary>
/// Mutates a value in-place with optimistic locking transaction semantics
/// via a specified transformation function.
/// The transformation is retried as many times as necessary to win the optimistic locking race.
/// </summary>
/// <typeparam name="T">The type of data.</typeparam>
/// <param name="location">
/// The variable or field to be changed, which may be accessed by multiple threads.
/// </param>
/// <param name="transformer">
/// A function that mutates the value. This function should be side-effect free,
/// as it may run multiple times when races occur with other threads.</param>
/// <returns>
/// <c>true</c> if the location's value is changed by applying the result of the
/// <paramref name="transformer"/> function;
/// <c>false</c> if the location's value remained the same because the last
/// invocation of <paramref name="transformer"/> returned the existing value.
/// </returns>
public static bool Update<T>(ref T location, Func<T, T> transformer) where T : class?
{
Requires.NotNull(transformer, nameof(transformer));
bool successful;
T oldValue = Volatile.Read(ref location);
do
{
T newValue = transformer(oldValue);
if (ReferenceEquals(oldValue, newValue))
{
// No change was actually required.
return false;
}
T interlockedResult = Interlocked.CompareExchange(ref location, newValue, oldValue);
successful = ReferenceEquals(oldValue, interlockedResult);
oldValue = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
return true;
}
/// <summary>
/// Mutates a value in-place with optimistic locking transaction semantics
/// via a specified transformation function.
/// The transformation is retried as many times as necessary to win the optimistic locking race.
/// </summary>
/// <typeparam name="T">The type of data.</typeparam>
/// <typeparam name="TArg">The type of argument passed to the <paramref name="transformer"/>.</typeparam>
/// <param name="location">
/// The variable or field to be changed, which may be accessed by multiple threads.
/// </param>
/// <param name="transformer">
/// A function that mutates the value. This function should be side-effect free,
/// as it may run multiple times when races occur with other threads.</param>
/// <param name="transformerArgument">The argument to pass to <paramref name="transformer"/>.</param>
/// <returns>
/// <c>true</c> if the location's value is changed by applying the result of the
/// <paramref name="transformer"/> function;
/// <c>false</c> if the location's value remained the same because the last
/// invocation of <paramref name="transformer"/> returned the existing value.
/// </returns>
public static bool Update<T, TArg>(ref T location, Func<T, TArg, T> transformer, TArg transformerArgument) where T : class?
{
Requires.NotNull(transformer, nameof(transformer));
bool successful;
T oldValue = Volatile.Read(ref location);
do
{
T newValue = transformer(oldValue, transformerArgument);
if (ReferenceEquals(oldValue, newValue))
{
// No change was actually required.
return false;
}
T interlockedResult = Interlocked.CompareExchange(ref location, newValue, oldValue);
successful = ReferenceEquals(oldValue, interlockedResult);
oldValue = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
return true;
}
/// <summary>
/// Mutates an immutable array in-place with optimistic locking transaction semantics
/// via a specified transformation function.
/// The transformation is retried as many times as necessary to win the optimistic locking race.
/// </summary>
/// <typeparam name="T">The type of data in the immutable array.</typeparam>
/// <param name="location">
/// The immutable array to be changed.
/// </param>
/// <param name="transformer">
/// A function that produces the new array from the old. This function should be side-effect free,
/// as it may run multiple times when races occur with other threads.</param>
/// <returns>
/// <c>true</c> if the location's value is changed by applying the result of the
/// <paramref name="transformer"/> function;
/// <c>false</c> if the location's value remained the same because the last
/// invocation of <paramref name="transformer"/> returned the existing value.
/// </returns>
public static bool Update<T>(ref ImmutableArray<T> location, Func<ImmutableArray<T>, ImmutableArray<T>> transformer)
{
Requires.NotNull(transformer, nameof(transformer));
bool successful;
T[]? oldArray = Volatile.Read(ref Unsafe.AsRef(in location.array));
do
{
ImmutableArray<T> newImmutableArray = transformer(new ImmutableArray<T>(oldArray));
if (ReferenceEquals(oldArray, newImmutableArray.array))
{
// No change was actually required.
return false;
}
T[]? interlockedResult = Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), newImmutableArray.array, oldArray);
successful = ReferenceEquals(oldArray, interlockedResult);
oldArray = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
return true;
}
/// <summary>
/// Mutates an immutable array in-place with optimistic locking transaction semantics
/// via a specified transformation function.
/// The transformation is retried as many times as necessary to win the optimistic locking race.
/// </summary>
/// <typeparam name="T">The type of data in the immutable array.</typeparam>
/// <typeparam name="TArg">The type of argument passed to the <paramref name="transformer"/>.</typeparam>
/// <param name="location">
/// The immutable array to be changed.
/// </param>
/// <param name="transformer">
/// A function that produces the new array from the old. This function should be side-effect free,
/// as it may run multiple times when races occur with other threads.</param>
/// <param name="transformerArgument">The argument to pass to <paramref name="transformer"/>.</param>
/// <returns>
/// <c>true</c> if the location's value is changed by applying the result of the
/// <paramref name="transformer"/> function;
/// <c>false</c> if the location's value remained the same because the last
/// invocation of <paramref name="transformer"/> returned the existing value.
/// </returns>
public static bool Update<T, TArg>(ref ImmutableArray<T> location, Func<ImmutableArray<T>, TArg, ImmutableArray<T>> transformer, TArg transformerArgument)
{
Requires.NotNull(transformer, nameof(transformer));
bool successful;
T[]? oldArray = Volatile.Read(ref Unsafe.AsRef(in location.array));
do
{
ImmutableArray<T> newImmutableArray = transformer(new ImmutableArray<T>(oldArray), transformerArgument);
if (ReferenceEquals(oldArray, newImmutableArray.array))
{
// No change was actually required.
return false;
}
T[]? interlockedResult = Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), newImmutableArray.array, oldArray);
successful = ReferenceEquals(oldArray, interlockedResult);
oldArray = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
return true;
}
#region ImmutableArray<T> members
/// <summary>
/// Assigns a field or variable containing an immutable array to the specified value and returns the previous value.
/// </summary>
/// <typeparam name="T">The type of element stored by the array.</typeparam>
/// <param name="location">The field or local variable to change.</param>
/// <param name="value">The new value to assign.</param>
/// <returns>The prior value at the specified <paramref name="location"/>.</returns>
public static ImmutableArray<T> InterlockedExchange<T>(ref ImmutableArray<T> location, ImmutableArray<T> value)
{
return new ImmutableArray<T>(Interlocked.Exchange(ref Unsafe.AsRef(in location.array), value.array));
}
/// <summary>
/// Assigns a field or variable containing an immutable array to the specified value
/// if it is currently equal to another specified value. Returns the previous value.
/// </summary>
/// <typeparam name="T">The type of element stored by the array.</typeparam>
/// <param name="location">The field or local variable to change.</param>
/// <param name="value">The new value to assign.</param>
/// <param name="comparand">The value to check equality for before assigning.</param>
/// <returns>The prior value at the specified <paramref name="location"/>.</returns>
public static ImmutableArray<T> InterlockedCompareExchange<T>(ref ImmutableArray<T> location, ImmutableArray<T> value, ImmutableArray<T> comparand)
{
return new ImmutableArray<T>(Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), value.array, comparand.array));
}
/// <summary>
/// Assigns a field or variable containing an immutable array to the specified value
/// if it is has not yet been initialized.
/// </summary>
/// <typeparam name="T">The type of element stored by the array.</typeparam>
/// <param name="location">The field or local variable to change.</param>
/// <param name="value">The new value to assign.</param>
/// <returns>True if the field was assigned the specified value; <c>false</c> if it was previously initialized.</returns>
public static bool InterlockedInitialize<T>(ref ImmutableArray<T> location, ImmutableArray<T> value)
{
return InterlockedCompareExchange(ref location, value, default(ImmutableArray<T>)).IsDefault;
}
#endregion
#region ImmutableDictionary<TKey, TValue> members
/// <summary>
/// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <typeparam name="TArg">The type of argument supplied to the value factory.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to retrieve or add.</param>
/// <param name="valueFactory">The function to execute to obtain the value to insert into the dictionary if the key is not found.</param>
/// <param name="factoryArgument">The argument to pass to the value factory.</param>
/// <returns>The value obtained from the dictionary or <paramref name="valueFactory"/> if it was not present.</returns>
public static TValue GetOrAdd<TKey, TValue, TArg>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument) where TKey : notnull
{
Requires.NotNull(valueFactory, nameof(valueFactory));
var map = Volatile.Read(ref location);
Requires.NotNull(map, nameof(location));
TValue value;
if (map.TryGetValue(key, out value!))
{
return value;
}
value = valueFactory(key, factoryArgument);
return GetOrAdd(ref location, key, value);
}
/// <summary>
/// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to retrieve or add.</param>
/// <param name="valueFactory">
/// The function to execute to obtain the value to insert into the dictionary if the key is not found.
/// This delegate will not be invoked more than once.
/// </param>
/// <returns>The value obtained from the dictionary or <paramref name="valueFactory"/> if it was not present.</returns>
public static TValue GetOrAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TValue> valueFactory) where TKey : notnull
{
Requires.NotNull(valueFactory, nameof(valueFactory));
var map = Volatile.Read(ref location);
Requires.NotNull(map, nameof(location));
TValue value;
if (map.TryGetValue(key, out value!))
{
return value;
}
value = valueFactory(key);
return GetOrAdd(ref location, key, value);
}
/// <summary>
/// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to retrieve or add.</param>
/// <param name="value">The value to add to the dictionary if one is not already present.</param>
/// <returns>The value obtained from the dictionary or <paramref name="value"/> if it was not present.</returns>
public static TValue GetOrAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue value) where TKey : notnull
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
TValue oldValue;
if (priorCollection.TryGetValue(key, out oldValue!))
{
return oldValue;
}
var updatedCollection = priorCollection.Add(key, value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
// We won the race-condition and have updated the collection.
// Return the value that is in the collection (as of the Interlocked operation).
return value;
}
/// <summary>
/// Obtains the value from a dictionary after having added it or updated an existing entry.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to add or update.</param>
/// <param name="addValueFactory">The function that receives the key and returns a new value to add to the dictionary when no value previously exists.</param>
/// <param name="updateValueFactory">The function that receives the key and prior value and returns the new value with which to update the dictionary.</param>
/// <returns>The added or updated value.</returns>
public static TValue AddOrUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory) where TKey : notnull
{
Requires.NotNull(addValueFactory, nameof(addValueFactory));
Requires.NotNull(updateValueFactory, nameof(updateValueFactory));
TValue newValue;
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
TValue oldValue;
if (priorCollection.TryGetValue(key, out oldValue!))
{
newValue = updateValueFactory(key, oldValue);
}
else
{
newValue = addValueFactory(key);
}
var updatedCollection = priorCollection.SetItem(key, newValue);
if (object.ReferenceEquals(priorCollection, updatedCollection))
{
return oldValue;
}
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
// We won the race-condition and have updated the collection.
// Return the value that is in the collection (as of the Interlocked operation).
return newValue;
}
/// <summary>
/// Obtains the value from a dictionary after having added it or updated an existing entry.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to add or update.</param>
/// <param name="addValue">The value to use if no previous value exists.</param>
/// <param name="updateValueFactory">The function that receives the key and prior value and returns the new value with which to update the dictionary.</param>
/// <returns>The added or updated value.</returns>
public static TValue AddOrUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory) where TKey : notnull
{
Requires.NotNull(updateValueFactory, nameof(updateValueFactory));
TValue newValue;
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
TValue oldValue;
if (priorCollection.TryGetValue(key, out oldValue!))
{
newValue = updateValueFactory(key, oldValue);
}
else
{
newValue = addValue;
}
var updatedCollection = priorCollection.SetItem(key, newValue);
if (object.ReferenceEquals(priorCollection, updatedCollection))
{
return oldValue;
}
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
// We won the race-condition and have updated the collection.
// Return the value that is in the collection (as of the Interlocked operation).
return newValue;
}
/// <summary>
/// Adds the specified key and value to the dictionary if no colliding key already exists in the dictionary.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key to add, if is not already defined in the dictionary.</param>
/// <param name="value">The value to add.</param>
/// <returns><c>true</c> if the key was not previously set in the dictionary and the value was set; <c>false</c> otherwise.</returns>
public static bool TryAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue value) where TKey : notnull
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
if (priorCollection.ContainsKey(key))
{
return false;
}
var updatedCollection = priorCollection.Add(key, value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
/// <summary>
/// Sets the specified key to the given value if the key already is set to a specific value.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key to update.</param>
/// <param name="newValue">The new value to set.</param>
/// <param name="comparisonValue">The value that must already be set in the dictionary in order for the update to succeed.</param>
/// <returns><c>true</c> if the key and comparison value were present in the dictionary and the update was made; <c>false</c> otherwise.</returns>
public static bool TryUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue newValue, TValue comparisonValue) where TKey : notnull
{
var valueComparer = EqualityComparer<TValue>.Default;
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
TValue priorValue;
if (!priorCollection.TryGetValue(key, out priorValue!) || !valueComparer.Equals(priorValue, comparisonValue))
{
// The key isn't in the dictionary, or its current value doesn't match what the caller expected.
return false;
}
var updatedCollection = priorCollection.SetItem(key, newValue);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
/// <summary>
/// Removes an entry from the dictionary with the specified key if it is defined and returns its value.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key to remove.</param>
/// <param name="value">Receives the value from the pre-existing entry, if one exists.</param>
/// <returns><c>true</c> if the key was found and removed; <c>false</c> otherwise.</returns>
public static bool TryRemove<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, [MaybeNullWhen(false)] out TValue value) where TKey : notnull
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
if (!priorCollection.TryGetValue(key, out value!))
{
return false;
}
var updatedCollection = priorCollection.Remove(key);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
#endregion
#region ImmutableStack<T> members
/// <summary>
/// Pops the top element off a stack and returns it to the caller, if the stack is not empty.
/// </summary>
/// <typeparam name="T">The type of elements stored in the stack.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
/// <param name="value">The value popped from the stack, if it was non-empty.</param>
/// <returns><c>true</c> if an element was removed from the stack; <c>false</c> otherwise.</returns>
public static bool TryPop<T>(ref ImmutableStack<T> location, [MaybeNullWhen(false)] out T value)
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
if (priorCollection.IsEmpty)
{
value = default;
return false;
}
var updatedCollection = priorCollection.Pop(out value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
/// <summary>
/// Pushes a new element onto a stack.
/// </summary>
/// <typeparam name="T">The type of elements stored in the stack.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
/// <param name="value">The value to push.</param>
public static void Push<T>(ref ImmutableStack<T> location, T value)
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
var updatedCollection = priorCollection.Push(value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
}
#endregion
#region ImmutableQueue<T> members
/// <summary>
/// Atomically removes the element at the head of a queue and returns it to the caller, if the queue is not empty.
/// </summary>
/// <typeparam name="T">The type of element stored in the queue.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
/// <param name="value">Receives the value from the head of the queue, if the queue is non-empty.</param>
/// <returns><c>true</c> if the queue was not empty and the head element was removed; <c>false</c> otherwise.</returns>
public static bool TryDequeue<T>(ref ImmutableQueue<T> location, [MaybeNullWhen(false)] out T value)
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
if (priorCollection.IsEmpty)
{
value = default;
return false;
}
var updatedCollection = priorCollection.Dequeue(out value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
/// <summary>
/// Atomically enqueues an element to the tail of a queue.
/// </summary>
/// <typeparam name="T">The type of element stored in the queue.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
/// <param name="value">The value to enqueue.</param>
public static void Enqueue<T>(ref ImmutableQueue<T> location, T value)
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
var updatedCollection = priorCollection.Enqueue(value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
}
#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.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Collections.Immutable
{
/// <summary>
/// Contains interlocked exchange mechanisms for immutable collections.
/// </summary>
public static class ImmutableInterlocked
{
/// <summary>
/// Mutates a value in-place with optimistic locking transaction semantics
/// via a specified transformation function.
/// The transformation is retried as many times as necessary to win the optimistic locking race.
/// </summary>
/// <typeparam name="T">The type of data.</typeparam>
/// <param name="location">
/// The variable or field to be changed, which may be accessed by multiple threads.
/// </param>
/// <param name="transformer">
/// A function that mutates the value. This function should be side-effect free,
/// as it may run multiple times when races occur with other threads.</param>
/// <returns>
/// <c>true</c> if the location's value is changed by applying the result of the
/// <paramref name="transformer"/> function;
/// <c>false</c> if the location's value remained the same because the last
/// invocation of <paramref name="transformer"/> returned the existing value.
/// </returns>
public static bool Update<T>(ref T location, Func<T, T> transformer) where T : class?
{
Requires.NotNull(transformer, nameof(transformer));
bool successful;
T oldValue = Volatile.Read(ref location);
do
{
T newValue = transformer(oldValue);
if (ReferenceEquals(oldValue, newValue))
{
// No change was actually required.
return false;
}
T interlockedResult = Interlocked.CompareExchange(ref location, newValue, oldValue);
successful = ReferenceEquals(oldValue, interlockedResult);
oldValue = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
return true;
}
/// <summary>
/// Mutates a value in-place with optimistic locking transaction semantics
/// via a specified transformation function.
/// The transformation is retried as many times as necessary to win the optimistic locking race.
/// </summary>
/// <typeparam name="T">The type of data.</typeparam>
/// <typeparam name="TArg">The type of argument passed to the <paramref name="transformer"/>.</typeparam>
/// <param name="location">
/// The variable or field to be changed, which may be accessed by multiple threads.
/// </param>
/// <param name="transformer">
/// A function that mutates the value. This function should be side-effect free,
/// as it may run multiple times when races occur with other threads.</param>
/// <param name="transformerArgument">The argument to pass to <paramref name="transformer"/>.</param>
/// <returns>
/// <c>true</c> if the location's value is changed by applying the result of the
/// <paramref name="transformer"/> function;
/// <c>false</c> if the location's value remained the same because the last
/// invocation of <paramref name="transformer"/> returned the existing value.
/// </returns>
public static bool Update<T, TArg>(ref T location, Func<T, TArg, T> transformer, TArg transformerArgument) where T : class?
{
Requires.NotNull(transformer, nameof(transformer));
bool successful;
T oldValue = Volatile.Read(ref location);
do
{
T newValue = transformer(oldValue, transformerArgument);
if (ReferenceEquals(oldValue, newValue))
{
// No change was actually required.
return false;
}
T interlockedResult = Interlocked.CompareExchange(ref location, newValue, oldValue);
successful = ReferenceEquals(oldValue, interlockedResult);
oldValue = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
return true;
}
/// <summary>
/// Mutates an immutable array in-place with optimistic locking transaction semantics
/// via a specified transformation function.
/// The transformation is retried as many times as necessary to win the optimistic locking race.
/// </summary>
/// <typeparam name="T">The type of data in the immutable array.</typeparam>
/// <param name="location">
/// The immutable array to be changed.
/// </param>
/// <param name="transformer">
/// A function that produces the new array from the old. This function should be side-effect free,
/// as it may run multiple times when races occur with other threads.</param>
/// <returns>
/// <c>true</c> if the location's value is changed by applying the result of the
/// <paramref name="transformer"/> function;
/// <c>false</c> if the location's value remained the same because the last
/// invocation of <paramref name="transformer"/> returned the existing value.
/// </returns>
public static bool Update<T>(ref ImmutableArray<T> location, Func<ImmutableArray<T>, ImmutableArray<T>> transformer)
{
Requires.NotNull(transformer, nameof(transformer));
bool successful;
T[]? oldArray = Volatile.Read(ref Unsafe.AsRef(in location.array));
do
{
ImmutableArray<T> newImmutableArray = transformer(new ImmutableArray<T>(oldArray));
if (ReferenceEquals(oldArray, newImmutableArray.array))
{
// No change was actually required.
return false;
}
T[]? interlockedResult = Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), newImmutableArray.array, oldArray);
successful = ReferenceEquals(oldArray, interlockedResult);
oldArray = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
return true;
}
/// <summary>
/// Mutates an immutable array in-place with optimistic locking transaction semantics
/// via a specified transformation function.
/// The transformation is retried as many times as necessary to win the optimistic locking race.
/// </summary>
/// <typeparam name="T">The type of data in the immutable array.</typeparam>
/// <typeparam name="TArg">The type of argument passed to the <paramref name="transformer"/>.</typeparam>
/// <param name="location">
/// The immutable array to be changed.
/// </param>
/// <param name="transformer">
/// A function that produces the new array from the old. This function should be side-effect free,
/// as it may run multiple times when races occur with other threads.</param>
/// <param name="transformerArgument">The argument to pass to <paramref name="transformer"/>.</param>
/// <returns>
/// <c>true</c> if the location's value is changed by applying the result of the
/// <paramref name="transformer"/> function;
/// <c>false</c> if the location's value remained the same because the last
/// invocation of <paramref name="transformer"/> returned the existing value.
/// </returns>
public static bool Update<T, TArg>(ref ImmutableArray<T> location, Func<ImmutableArray<T>, TArg, ImmutableArray<T>> transformer, TArg transformerArgument)
{
Requires.NotNull(transformer, nameof(transformer));
bool successful;
T[]? oldArray = Volatile.Read(ref Unsafe.AsRef(in location.array));
do
{
ImmutableArray<T> newImmutableArray = transformer(new ImmutableArray<T>(oldArray), transformerArgument);
if (ReferenceEquals(oldArray, newImmutableArray.array))
{
// No change was actually required.
return false;
}
T[]? interlockedResult = Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), newImmutableArray.array, oldArray);
successful = ReferenceEquals(oldArray, interlockedResult);
oldArray = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
return true;
}
#region ImmutableArray<T> members
/// <summary>
/// Assigns a field or variable containing an immutable array to the specified value and returns the previous value.
/// </summary>
/// <typeparam name="T">The type of element stored by the array.</typeparam>
/// <param name="location">The field or local variable to change.</param>
/// <param name="value">The new value to assign.</param>
/// <returns>The prior value at the specified <paramref name="location"/>.</returns>
public static ImmutableArray<T> InterlockedExchange<T>(ref ImmutableArray<T> location, ImmutableArray<T> value)
{
return new ImmutableArray<T>(Interlocked.Exchange(ref Unsafe.AsRef(in location.array), value.array));
}
/// <summary>
/// Assigns a field or variable containing an immutable array to the specified value
/// if it is currently equal to another specified value. Returns the previous value.
/// </summary>
/// <typeparam name="T">The type of element stored by the array.</typeparam>
/// <param name="location">The field or local variable to change.</param>
/// <param name="value">The new value to assign.</param>
/// <param name="comparand">The value to check equality for before assigning.</param>
/// <returns>The prior value at the specified <paramref name="location"/>.</returns>
public static ImmutableArray<T> InterlockedCompareExchange<T>(ref ImmutableArray<T> location, ImmutableArray<T> value, ImmutableArray<T> comparand)
{
return new ImmutableArray<T>(Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), value.array, comparand.array));
}
/// <summary>
/// Assigns a field or variable containing an immutable array to the specified value
/// if it is has not yet been initialized.
/// </summary>
/// <typeparam name="T">The type of element stored by the array.</typeparam>
/// <param name="location">The field or local variable to change.</param>
/// <param name="value">The new value to assign.</param>
/// <returns>True if the field was assigned the specified value; <c>false</c> if it was previously initialized.</returns>
public static bool InterlockedInitialize<T>(ref ImmutableArray<T> location, ImmutableArray<T> value)
{
return InterlockedCompareExchange(ref location, value, default(ImmutableArray<T>)).IsDefault;
}
#endregion
#region ImmutableDictionary<TKey, TValue> members
/// <summary>
/// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <typeparam name="TArg">The type of argument supplied to the value factory.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to retrieve or add.</param>
/// <param name="valueFactory">The function to execute to obtain the value to insert into the dictionary if the key is not found.</param>
/// <param name="factoryArgument">The argument to pass to the value factory.</param>
/// <returns>The value obtained from the dictionary or <paramref name="valueFactory"/> if it was not present.</returns>
public static TValue GetOrAdd<TKey, TValue, TArg>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument) where TKey : notnull
{
Requires.NotNull(valueFactory, nameof(valueFactory));
var map = Volatile.Read(ref location);
Requires.NotNull(map, nameof(location));
TValue value;
if (map.TryGetValue(key, out value!))
{
return value;
}
value = valueFactory(key, factoryArgument);
return GetOrAdd(ref location, key, value);
}
/// <summary>
/// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to retrieve or add.</param>
/// <param name="valueFactory">
/// The function to execute to obtain the value to insert into the dictionary if the key is not found.
/// This delegate will not be invoked more than once.
/// </param>
/// <returns>The value obtained from the dictionary or <paramref name="valueFactory"/> if it was not present.</returns>
public static TValue GetOrAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TValue> valueFactory) where TKey : notnull
{
Requires.NotNull(valueFactory, nameof(valueFactory));
var map = Volatile.Read(ref location);
Requires.NotNull(map, nameof(location));
TValue value;
if (map.TryGetValue(key, out value!))
{
return value;
}
value = valueFactory(key);
return GetOrAdd(ref location, key, value);
}
/// <summary>
/// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to retrieve or add.</param>
/// <param name="value">The value to add to the dictionary if one is not already present.</param>
/// <returns>The value obtained from the dictionary or <paramref name="value"/> if it was not present.</returns>
public static TValue GetOrAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue value) where TKey : notnull
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
TValue oldValue;
if (priorCollection.TryGetValue(key, out oldValue!))
{
return oldValue;
}
var updatedCollection = priorCollection.Add(key, value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
// We won the race-condition and have updated the collection.
// Return the value that is in the collection (as of the Interlocked operation).
return value;
}
/// <summary>
/// Obtains the value from a dictionary after having added it or updated an existing entry.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to add or update.</param>
/// <param name="addValueFactory">The function that receives the key and returns a new value to add to the dictionary when no value previously exists.</param>
/// <param name="updateValueFactory">The function that receives the key and prior value and returns the new value with which to update the dictionary.</param>
/// <returns>The added or updated value.</returns>
public static TValue AddOrUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory) where TKey : notnull
{
Requires.NotNull(addValueFactory, nameof(addValueFactory));
Requires.NotNull(updateValueFactory, nameof(updateValueFactory));
TValue newValue;
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
TValue oldValue;
if (priorCollection.TryGetValue(key, out oldValue!))
{
newValue = updateValueFactory(key, oldValue);
}
else
{
newValue = addValueFactory(key);
}
var updatedCollection = priorCollection.SetItem(key, newValue);
if (object.ReferenceEquals(priorCollection, updatedCollection))
{
return oldValue;
}
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
// We won the race-condition and have updated the collection.
// Return the value that is in the collection (as of the Interlocked operation).
return newValue;
}
/// <summary>
/// Obtains the value from a dictionary after having added it or updated an existing entry.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key for the value to add or update.</param>
/// <param name="addValue">The value to use if no previous value exists.</param>
/// <param name="updateValueFactory">The function that receives the key and prior value and returns the new value with which to update the dictionary.</param>
/// <returns>The added or updated value.</returns>
public static TValue AddOrUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory) where TKey : notnull
{
Requires.NotNull(updateValueFactory, nameof(updateValueFactory));
TValue newValue;
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
TValue oldValue;
if (priorCollection.TryGetValue(key, out oldValue!))
{
newValue = updateValueFactory(key, oldValue);
}
else
{
newValue = addValue;
}
var updatedCollection = priorCollection.SetItem(key, newValue);
if (object.ReferenceEquals(priorCollection, updatedCollection))
{
return oldValue;
}
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
while (!successful);
// We won the race-condition and have updated the collection.
// Return the value that is in the collection (as of the Interlocked operation).
return newValue;
}
/// <summary>
/// Adds the specified key and value to the dictionary if no colliding key already exists in the dictionary.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key to add, if is not already defined in the dictionary.</param>
/// <param name="value">The value to add.</param>
/// <returns><c>true</c> if the key was not previously set in the dictionary and the value was set; <c>false</c> otherwise.</returns>
public static bool TryAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue value) where TKey : notnull
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
if (priorCollection.ContainsKey(key))
{
return false;
}
var updatedCollection = priorCollection.Add(key, value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
/// <summary>
/// Sets the specified key to the given value if the key already is set to a specific value.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key to update.</param>
/// <param name="newValue">The new value to set.</param>
/// <param name="comparisonValue">The value that must already be set in the dictionary in order for the update to succeed.</param>
/// <returns><c>true</c> if the key and comparison value were present in the dictionary and the update was made; <c>false</c> otherwise.</returns>
public static bool TryUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue newValue, TValue comparisonValue) where TKey : notnull
{
var valueComparer = EqualityComparer<TValue>.Default;
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
TValue priorValue;
if (!priorCollection.TryGetValue(key, out priorValue!) || !valueComparer.Equals(priorValue, comparisonValue))
{
// The key isn't in the dictionary, or its current value doesn't match what the caller expected.
return false;
}
var updatedCollection = priorCollection.SetItem(key, newValue);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
/// <summary>
/// Removes an entry from the dictionary with the specified key if it is defined and returns its value.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param>
/// <param name="key">The key to remove.</param>
/// <param name="value">Receives the value from the pre-existing entry, if one exists.</param>
/// <returns><c>true</c> if the key was found and removed; <c>false</c> otherwise.</returns>
public static bool TryRemove<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, [MaybeNullWhen(false)] out TValue value) where TKey : notnull
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
if (!priorCollection.TryGetValue(key, out value!))
{
return false;
}
var updatedCollection = priorCollection.Remove(key);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
#endregion
#region ImmutableStack<T> members
/// <summary>
/// Pops the top element off a stack and returns it to the caller, if the stack is not empty.
/// </summary>
/// <typeparam name="T">The type of elements stored in the stack.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
/// <param name="value">The value popped from the stack, if it was non-empty.</param>
/// <returns><c>true</c> if an element was removed from the stack; <c>false</c> otherwise.</returns>
public static bool TryPop<T>(ref ImmutableStack<T> location, [MaybeNullWhen(false)] out T value)
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
if (priorCollection.IsEmpty)
{
value = default;
return false;
}
var updatedCollection = priorCollection.Pop(out value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
/// <summary>
/// Pushes a new element onto a stack.
/// </summary>
/// <typeparam name="T">The type of elements stored in the stack.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
/// <param name="value">The value to push.</param>
public static void Push<T>(ref ImmutableStack<T> location, T value)
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
var updatedCollection = priorCollection.Push(value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
}
#endregion
#region ImmutableQueue<T> members
/// <summary>
/// Atomically removes the element at the head of a queue and returns it to the caller, if the queue is not empty.
/// </summary>
/// <typeparam name="T">The type of element stored in the queue.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
/// <param name="value">Receives the value from the head of the queue, if the queue is non-empty.</param>
/// <returns><c>true</c> if the queue was not empty and the head element was removed; <c>false</c> otherwise.</returns>
public static bool TryDequeue<T>(ref ImmutableQueue<T> location, [MaybeNullWhen(false)] out T value)
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
if (priorCollection.IsEmpty)
{
value = default;
return false;
}
var updatedCollection = priorCollection.Dequeue(out value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
return true;
}
/// <summary>
/// Atomically enqueues an element to the tail of a queue.
/// </summary>
/// <typeparam name="T">The type of element stored in the queue.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
/// <param name="value">The value to enqueue.</param>
public static void Enqueue<T>(ref ImmutableQueue<T> location, T value)
{
var priorCollection = Volatile.Read(ref location);
bool successful;
do
{
Requires.NotNull(priorCollection, nameof(location));
var updatedCollection = priorCollection.Enqueue(value);
var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection);
successful = object.ReferenceEquals(priorCollection, interlockedResult);
priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop
} while (!successful);
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/PInvokeMethodFixupNode.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 Internal.IL.Stubs;
using Internal.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// Represents a single PInvoke MethodFixupCell as defined in the core library.
/// </summary>
public class PInvokeMethodFixupNode : ObjectNode, ISymbolDefinitionNode
{
private readonly PInvokeMethodData _pInvokeMethodData;
public PInvokeMethodFixupNode(PInvokeMethodData pInvokeMethodData)
{
_pInvokeMethodData = pInvokeMethodData;
}
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append("__pinvoke_");
_pInvokeMethodData.AppendMangledName(nameMangler, sb);
}
public int Offset => 0;
public override bool IsShareable => true;
protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);
public override ObjectNodeSection Section => ObjectNodeSection.DataSection;
public override bool StaticDependenciesAreComputed => true;
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);
builder.RequireInitialPointerAlignment();
builder.AddSymbol(this);
//
// Emit a MethodFixupCell struct
//
// Address (to be fixed up at runtime)
builder.EmitZeroPointer();
// Entry point name
string entryPointName = _pInvokeMethodData.EntryPointName;
if (factory.Target.IsWindows && entryPointName.StartsWith("#", StringComparison.OrdinalIgnoreCase))
{
// Windows-specific ordinal import
// CLR-compatible behavior: Strings that can't be parsed as a signed integer are treated as zero.
int entrypointOrdinal;
if (!int.TryParse(entryPointName.Substring(1), out entrypointOrdinal))
entrypointOrdinal = 0;
// CLR-compatible behavior: Ordinal imports are 16-bit on Windows. Discard rest of the bits.
builder.EmitNaturalInt((ushort)entrypointOrdinal);
}
else
{
// Import by name
builder.EmitPointerReloc(factory.ConstantUtf8String(entryPointName));
}
// Module fixup cell
builder.EmitPointerReloc(factory.PInvokeModuleFixup(_pInvokeMethodData.ModuleData));
builder.EmitInt((int)_pInvokeMethodData.CharSetMangling);
return builder.ToObjectData();
}
public override int ClassCode => -1592006940;
public override int CompareToImpl(ISortableNode other, CompilerComparer comparer)
{
return _pInvokeMethodData.CompareTo(((PInvokeMethodFixupNode)other)._pInvokeMethodData, comparer);
}
}
public readonly struct PInvokeMethodData : IEquatable<PInvokeMethodData>
{
public readonly PInvokeModuleData ModuleData;
public readonly string EntryPointName;
public readonly CharSet CharSetMangling;
public PInvokeMethodData(PInvokeLazyFixupField pInvokeLazyFixupField)
{
PInvokeMetadata metadata = pInvokeLazyFixupField.PInvokeMetadata;
ModuleDesc declaringModule = ((MetadataType)pInvokeLazyFixupField.TargetMethod.OwningType).Module;
DllImportSearchPath? dllImportSearchPath = default;
if (declaringModule.Assembly is EcmaAssembly asm)
{
// We look for [assembly:DefaultDllImportSearchPaths(...)]
var attrHandle = asm.MetadataReader.GetCustomAttributeHandle(asm.AssemblyDefinition.GetCustomAttributes(),
"System.Runtime.InteropServices", "DefaultDllImportSearchPathsAttribute");
if (!attrHandle.IsNil)
{
var attr = asm.MetadataReader.GetCustomAttribute(attrHandle);
var decoded = attr.DecodeValue(new CustomAttributeTypeProvider(asm));
if (decoded.FixedArguments.Length == 1 &&
decoded.FixedArguments[0].Value is int searchPath)
{
dllImportSearchPath = (DllImportSearchPath)searchPath;
}
}
}
ModuleData = new PInvokeModuleData(metadata.Module, dllImportSearchPath, declaringModule);
EntryPointName = metadata.Name;
CharSet charSetMangling = default;
if (declaringModule.Context.Target.IsWindows && !metadata.Flags.ExactSpelling)
{
// Mirror CharSet normalization from Marshaller.CreateMarshaller
bool isAnsi = metadata.Flags.CharSet switch
{
CharSet.Ansi => true,
CharSet.Unicode => false,
CharSet.Auto => false,
_ => true
};
charSetMangling = isAnsi ? CharSet.Ansi : CharSet.Unicode;
}
CharSetMangling = charSetMangling;
}
public bool Equals(PInvokeMethodData other)
{
return ModuleData.Equals(other.ModuleData) &&
EntryPointName == other.EntryPointName &&
CharSetMangling == other.CharSetMangling;
}
public override bool Equals(object obj)
{
return obj is PInvokeMethodData other && Equals(other);
}
public override int GetHashCode()
{
return ModuleData.GetHashCode() ^ EntryPointName.GetHashCode();
}
public int CompareTo(PInvokeMethodData other, CompilerComparer comparer)
{
var entryPointCompare = StringComparer.Ordinal.Compare(EntryPointName, other.EntryPointName);
if (entryPointCompare != 0)
return entryPointCompare;
var moduleCompare = ModuleData.CompareTo(other.ModuleData, comparer);
if (moduleCompare != 0)
return moduleCompare;
return CharSetMangling.CompareTo(other.CharSetMangling);
}
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
ModuleData.AppendMangledName(nameMangler, sb);
sb.Append("__");
sb.Append(EntryPointName);
if (CharSetMangling != default)
{
sb.Append("__");
sb.Append(CharSetMangling.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;
using System.Runtime.InteropServices;
using Internal.IL.Stubs;
using Internal.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// Represents a single PInvoke MethodFixupCell as defined in the core library.
/// </summary>
public class PInvokeMethodFixupNode : ObjectNode, ISymbolDefinitionNode
{
private readonly PInvokeMethodData _pInvokeMethodData;
public PInvokeMethodFixupNode(PInvokeMethodData pInvokeMethodData)
{
_pInvokeMethodData = pInvokeMethodData;
}
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append("__pinvoke_");
_pInvokeMethodData.AppendMangledName(nameMangler, sb);
}
public int Offset => 0;
public override bool IsShareable => true;
protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);
public override ObjectNodeSection Section => ObjectNodeSection.DataSection;
public override bool StaticDependenciesAreComputed => true;
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);
builder.RequireInitialPointerAlignment();
builder.AddSymbol(this);
//
// Emit a MethodFixupCell struct
//
// Address (to be fixed up at runtime)
builder.EmitZeroPointer();
// Entry point name
string entryPointName = _pInvokeMethodData.EntryPointName;
if (factory.Target.IsWindows && entryPointName.StartsWith("#", StringComparison.OrdinalIgnoreCase))
{
// Windows-specific ordinal import
// CLR-compatible behavior: Strings that can't be parsed as a signed integer are treated as zero.
int entrypointOrdinal;
if (!int.TryParse(entryPointName.Substring(1), out entrypointOrdinal))
entrypointOrdinal = 0;
// CLR-compatible behavior: Ordinal imports are 16-bit on Windows. Discard rest of the bits.
builder.EmitNaturalInt((ushort)entrypointOrdinal);
}
else
{
// Import by name
builder.EmitPointerReloc(factory.ConstantUtf8String(entryPointName));
}
// Module fixup cell
builder.EmitPointerReloc(factory.PInvokeModuleFixup(_pInvokeMethodData.ModuleData));
builder.EmitInt((int)_pInvokeMethodData.CharSetMangling);
return builder.ToObjectData();
}
public override int ClassCode => -1592006940;
public override int CompareToImpl(ISortableNode other, CompilerComparer comparer)
{
return _pInvokeMethodData.CompareTo(((PInvokeMethodFixupNode)other)._pInvokeMethodData, comparer);
}
}
public readonly struct PInvokeMethodData : IEquatable<PInvokeMethodData>
{
public readonly PInvokeModuleData ModuleData;
public readonly string EntryPointName;
public readonly CharSet CharSetMangling;
public PInvokeMethodData(PInvokeLazyFixupField pInvokeLazyFixupField)
{
PInvokeMetadata metadata = pInvokeLazyFixupField.PInvokeMetadata;
ModuleDesc declaringModule = ((MetadataType)pInvokeLazyFixupField.TargetMethod.OwningType).Module;
DllImportSearchPath? dllImportSearchPath = default;
if (declaringModule.Assembly is EcmaAssembly asm)
{
// We look for [assembly:DefaultDllImportSearchPaths(...)]
var attrHandle = asm.MetadataReader.GetCustomAttributeHandle(asm.AssemblyDefinition.GetCustomAttributes(),
"System.Runtime.InteropServices", "DefaultDllImportSearchPathsAttribute");
if (!attrHandle.IsNil)
{
var attr = asm.MetadataReader.GetCustomAttribute(attrHandle);
var decoded = attr.DecodeValue(new CustomAttributeTypeProvider(asm));
if (decoded.FixedArguments.Length == 1 &&
decoded.FixedArguments[0].Value is int searchPath)
{
dllImportSearchPath = (DllImportSearchPath)searchPath;
}
}
}
ModuleData = new PInvokeModuleData(metadata.Module, dllImportSearchPath, declaringModule);
EntryPointName = metadata.Name;
CharSet charSetMangling = default;
if (declaringModule.Context.Target.IsWindows && !metadata.Flags.ExactSpelling)
{
// Mirror CharSet normalization from Marshaller.CreateMarshaller
bool isAnsi = metadata.Flags.CharSet switch
{
CharSet.Ansi => true,
CharSet.Unicode => false,
CharSet.Auto => false,
_ => true
};
charSetMangling = isAnsi ? CharSet.Ansi : CharSet.Unicode;
}
CharSetMangling = charSetMangling;
}
public bool Equals(PInvokeMethodData other)
{
return ModuleData.Equals(other.ModuleData) &&
EntryPointName == other.EntryPointName &&
CharSetMangling == other.CharSetMangling;
}
public override bool Equals(object obj)
{
return obj is PInvokeMethodData other && Equals(other);
}
public override int GetHashCode()
{
return ModuleData.GetHashCode() ^ EntryPointName.GetHashCode();
}
public int CompareTo(PInvokeMethodData other, CompilerComparer comparer)
{
var entryPointCompare = StringComparer.Ordinal.Compare(EntryPointName, other.EntryPointName);
if (entryPointCompare != 0)
return entryPointCompare;
var moduleCompare = ModuleData.CompareTo(other.ModuleData, comparer);
if (moduleCompare != 0)
return moduleCompare;
return CharSetMangling.CompareTo(other.CharSetMangling);
}
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
ModuleData.AppendMangledName(nameMangler, sb);
sb.Append("__");
sb.Append(EntryPointName);
if (CharSetMangling != default)
{
sb.Append("__");
sb.Append(CharSetMangling.ToString());
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.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.TypeSystem;
namespace Internal.IL.Stubs
{
// Functionality related to deterministic ordering of types
partial class StructMarshallingThunk
{
protected override int ClassCode => 340834018;
protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer)
{
var otherMethod = (StructMarshallingThunk)other;
int result = ThunkType - otherMethod.ThunkType;
if (result != 0)
return result;
return comparer.Compare(ManagedType, otherMethod.ManagedType);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Internal.TypeSystem;
namespace Internal.IL.Stubs
{
// Functionality related to deterministic ordering of types
partial class StructMarshallingThunk
{
protected override int ClassCode => 340834018;
protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer)
{
var otherMethod = (StructMarshallingThunk)other;
int result = ThunkType - otherMethod.ThunkType;
if (result != 0)
return result;
return comparer.Compare(ManagedType, otherMethod.ManagedType);
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/General/Vector128/Subtract.Int32.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void SubtractInt32()
{
var test = new VectorBinaryOpTest__SubtractInt32();
// 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__SubtractInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 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<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__SubtractInt32 testClass)
{
var result = Vector128.Subtract(_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<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__SubtractInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public VectorBinaryOpTest__SubtractInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.Subtract(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.Subtract), new Type[] {
typeof(Vector128<Int32>),
typeof(Vector128<Int32>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.Subtract), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int32));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.Subtract(
_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<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Vector128.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__SubtractInt32();
var result = Vector128.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.Subtract(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<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (int)(left[0] - right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (int)(left[i] - right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Subtract)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\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 SubtractInt32()
{
var test = new VectorBinaryOpTest__SubtractInt32();
// 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__SubtractInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 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<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__SubtractInt32 testClass)
{
var result = Vector128.Subtract(_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<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__SubtractInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public VectorBinaryOpTest__SubtractInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.Subtract(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.Subtract), new Type[] {
typeof(Vector128<Int32>),
typeof(Vector128<Int32>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.Subtract), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int32));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.Subtract(
_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<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Vector128.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__SubtractInt32();
var result = Vector128.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.Subtract(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<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (int)(left[0] - right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (int)(left[i] - right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Subtract)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoTests.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 Xunit;
namespace System.Globalization.Tests
{
public class DateTimeFormatInfoMiscTests
{
public static IEnumerable<object[]> DateTimeFormatInfo_TestData()
{
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("en-US").DateTimeFormat.Clone(), new GregorianCalendar(), "Gregorian Calendar" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("ar-SA").DateTimeFormat.Clone(), new HijriCalendar(), "\u0627\u0644\u062a\u0642\u0648\u064a\u0645\u00a0\u0627\u0644\u0647\u062c\u0631\u064a" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("ar-SA").DateTimeFormat.Clone(), new UmAlQuraCalendar(), "\u062a\u0642\u0648\u064a\u0645\u0020\u0627\u0645\u0020\u0627\u0644\u0642\u0631\u0649" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("ja-JP").DateTimeFormat.Clone(), new JapaneseCalendar(), "\u548c\u66a6" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("th-TH").DateTimeFormat.Clone(), new ThaiBuddhistCalendar(), "\u0e1e\u0e38\u0e17\u0e18\u0e28\u0e31\u0e01\u0e23\u0e32\u0e0a" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("he-IL").DateTimeFormat.Clone(), new HebrewCalendar(), "\u05dc\u05d5\u05d7\u00a0\u05e9\u05e0\u05d4\u00a0\u05e2\u05d1\u05e8\u05d9" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("ko-KR").DateTimeFormat.Clone(), new KoreanCalendar(), "\ub2e8\uae30" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("fa-IR").DateTimeFormat.Clone(), new PersianCalendar(), "\u062a\u0642\u0648\u06cc\u0645\u0020\u0647\u062c\u0631\u06cc\u0020\u0634\u0645\u0633\u06cc" };
}
public static IEnumerable<object[]> CultureNames_TestData()
{
yield return new object[] { "" };
yield return new object[] { "en-US" };
yield return new object[] { "ja-JP" };
yield return new object[] { "zh-CN" };
yield return new object[] { "ar-SA" };
yield return new object[] { "ko-KR" };
yield return new object[] { "he-IL" };
}
[Fact]
public void DateSeparatorTimeSeparator_Get_ReturnsExpected()
{
DateTimeFormatInfo dtfi = (DateTimeFormatInfo) CultureInfo.InvariantCulture.DateTimeFormat.Clone();
Assert.False(dtfi.IsReadOnly, "IsReadOnly expected to be false");
string dateSep = dtfi.DateSeparator;
string timeSep = dtfi.TimeSeparator;
Assert.True(dtfi.ShortDatePattern.IndexOf(dateSep) > 0, "dtfi.ShortDatePattern should be greater than 0");
Assert.True(dtfi.ShortTimePattern.IndexOf(timeSep) > 0, "dtfi.ShortTimePattern should be greater than 0");
DateTime d = DateTime.Now;
string formattedDate = d.ToString("MM/dd/yyyy", dtfi);
Assert.True(formattedDate.IndexOf(dateSep) > 0, "Expected to find date separator in the formatted string");
dtfi.DateSeparator = "-";
string expectedFormattedString = formattedDate.Replace(dateSep, dtfi.DateSeparator);
Assert.Equal(expectedFormattedString, d.ToString("MM/dd/yyyy", dtfi));
string formattedTime = d.ToString("HH:mm:ss", dtfi);
Assert.True(formattedTime.IndexOf(timeSep) > 0, "Expected to find time separator in the formatted string");
dtfi.TimeSeparator = ".";
expectedFormattedString = formattedTime.Replace(timeSep, dtfi.TimeSeparator);
Assert.Equal(expectedFormattedString, d.ToString("HH:mm:ss", dtfi));
}
[Theory]
[MemberData(nameof(DateTimeFormatInfo_TestData))]
public void NativeCalendarName_Get_ReturnsExpected(DateTimeFormatInfo dtfi, Calendar calendar, string nativeCalendarName)
{
try
{
dtfi.Calendar = calendar;
if (PlatformDetection.IsNotUsingLimitedCultures)
{
// Mobile / Browser ICU doesn't contain NativeCalendarName,
Assert.Equal(nativeCalendarName, dtfi.NativeCalendarName);
}
}
catch
{
if (PlatformDetection.IsNlsGlobalization)
{
// Persian calendar is recently supported as one of the optional calendars for fa-IR
Assert.True(calendar is PersianCalendar, "Exception can occur only with PersianCalendar");
}
else // !PlatformDetection.IsNlsGlobalization
{
Assert.True(calendar is HijriCalendar || calendar is UmAlQuraCalendar || calendar is ThaiBuddhistCalendar ||
calendar is HebrewCalendar || calendar is KoreanCalendar, "failed to set the calendar on DTFI");
}
}
}
[Theory]
[MemberData(nameof(CultureNames_TestData))]
public void GetAllDateTimePatterns_Invoke_ReturnsExpected(string cultureName)
{
char[] formats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'o', 'r', 's', 't', 'T', 'u', 'U', 'y' };
DateTimeFormatInfo dtfi = (DateTimeFormatInfo)new CultureInfo(cultureName).DateTimeFormat.Clone();
var allPatterns = dtfi.GetAllDateTimePatterns();
Dictionary<string, string> dic = new Dictionary<string, string>();
string value = "";
foreach (char format in formats)
{
foreach (string pattern in dtfi.GetAllDateTimePatterns(format))
{
if (!dic.TryGetValue(pattern, out value))
{
dic.Add(pattern, "");
}
}
}
foreach (string pattern in allPatterns)
{
Assert.True(dic.TryGetValue(pattern, out value), "Couldn't find the pattern in the patterns list");
}
char[] setterFormats = { 'd', 'D', 't', 'T', 'y', 'Y' };
foreach (char format in setterFormats)
{
var formatPatterns = dtfi.GetAllDateTimePatterns(format);
string [] newPatterns = new string[1] { formatPatterns[formatPatterns.Length - 1] };
dtfi.SetAllDateTimePatterns(newPatterns, format);
Assert.Equal(newPatterns, dtfi.GetAllDateTimePatterns(format));
}
}
[Theory]
[MemberData(nameof(CultureNames_TestData))]
public void GetShortestDayName_Invoke_ReturnsExpected(string cultureName)
{
DateTimeFormatInfo dtfi = new CultureInfo(cultureName).DateTimeFormat;
string [] shortestDayNames = dtfi.ShortestDayNames;
for (DayOfWeek day = DayOfWeek.Sunday; day <= DayOfWeek.Saturday; day++)
{
Assert.Equal(shortestDayNames[(int) day], dtfi.GetShortestDayName(day));
}
}
[Fact]
public void Months_GetHebrew_ReturnsExpected()
{
CultureInfo ci = new CultureInfo("he-IL");
ci.DateTimeFormat.Calendar = new HebrewCalendar();
Assert.Equal(13, ci.DateTimeFormat.MonthNames.Length);
Assert.Equal(13, ci.DateTimeFormat.MonthGenitiveNames.Length);
Assert.Equal(13, ci.DateTimeFormat.AbbreviatedMonthNames.Length);
Assert.Equal(13, ci.DateTimeFormat.AbbreviatedMonthGenitiveNames.Length);
DateTime dt = ci.DateTimeFormat.Calendar.ToDateTime(5779, 1, 1, 0, 0, 0, 0); // leap year
for (int i = 0; i < 13; i++)
{
string formatted = dt.ToString(ci.DateTimeFormat.LongDatePattern, ci);
Assert.Equal(dt, DateTime.ParseExact(formatted, ci.DateTimeFormat.LongDatePattern, ci));
dt = ci.DateTimeFormat.Calendar.AddMonths(dt, 1);
}
dt = ci.DateTimeFormat.Calendar.ToDateTime(5778, 1, 1, 0, 0, 0, 0); // non leap year
for (int i = 0; i < 12; i++)
{
string formatted = dt.ToString(ci.DateTimeFormat.LongDatePattern, ci);
Assert.Equal(dt, DateTime.ParseExact(formatted, ci.DateTimeFormat.LongDatePattern, ci));
dt = ci.DateTimeFormat.Calendar.AddMonths(dt, 1);
}
}
[Fact]
public void TestFirstYearOfJapaneseEra()
{
DateTimeFormatInfo jpnFormat = new CultureInfo("ja-JP").DateTimeFormat;
jpnFormat.Calendar = new JapaneseCalendar();
string pattern = "gg yyyy'\u5E74' MM'\u6708' dd'\u65E5'";
DateTime dt = new DateTime(1989, 01, 08); // Start of Heisei Era
string formattedDateWithGannen = "\u5E73\u6210 \u5143\u5E74 01\u6708 08\u65E5";
string formattedDate = dt.ToString(pattern, jpnFormat);
Assert.True(DateTime.TryParseExact(formattedDate, pattern, jpnFormat, DateTimeStyles.None, out DateTime parsedDate));
Assert.Equal(dt, parsedDate);
// If the formatting with Gan-nen is supported, then parsing should succeed. otherwise parsing should fail.
Assert.True(formattedDate.IndexOf("\u5143", StringComparison.Ordinal) >= 0 ==
DateTime.TryParseExact(formattedDateWithGannen, pattern, jpnFormat, DateTimeStyles.None, out parsedDate),
$"Parsing '{formattedDateWithGannen}' result should match if '{formattedDate}' has Gan-nen symbol"
);
}
[Fact]
public void JapaneseAbbreviatedEnglishEraNamesTest()
{
string [] eraNames = { "M", "T", "S", "H", "R" };
var ci = new CultureInfo("ja-JP") { DateTimeFormat = { Calendar = new JapaneseCalendar() }};
int eraNumber = ci.DateTimeFormat.GetEra("Q");
if (eraNumber == 4 || eraNumber == 5)
{
// Skip the test on Windows versions which have wrong Japanese Era information.
// Windows at some point used "Q" as fake era name before getting the official name.
return;
}
int numberOfErasToTest = Math.Min(eraNames.Length, ci.DateTimeFormat.Calendar.Eras.Length);
for (int i = 0; i < numberOfErasToTest; i++)
{
Assert.Equal(i + 1, ci.DateTimeFormat.GetEra(eraNames[i]));
}
}
[Fact]
public void TestFrenchCanadaTimeFormat()
{
CultureInfo ci = CultureInfo.GetCultureInfo("fr-CA");
Assert.Equal(":", ci.DateTimeFormat.TimeSeparator);
DateTime time = new DateTime(2021, 10, 1, 5, 36, 50);
string formattedTime = time.ToString("HH 'h' mm 'min' ss 's'", ci);
DateTime dt = DateTime.Parse(formattedTime, ci);
Assert.Equal(time.TimeOfDay, dt.TimeOfDay);
}
}
}
| // 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 Xunit;
namespace System.Globalization.Tests
{
public class DateTimeFormatInfoMiscTests
{
public static IEnumerable<object[]> DateTimeFormatInfo_TestData()
{
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("en-US").DateTimeFormat.Clone(), new GregorianCalendar(), "Gregorian Calendar" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("ar-SA").DateTimeFormat.Clone(), new HijriCalendar(), "\u0627\u0644\u062a\u0642\u0648\u064a\u0645\u00a0\u0627\u0644\u0647\u062c\u0631\u064a" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("ar-SA").DateTimeFormat.Clone(), new UmAlQuraCalendar(), "\u062a\u0642\u0648\u064a\u0645\u0020\u0627\u0645\u0020\u0627\u0644\u0642\u0631\u0649" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("ja-JP").DateTimeFormat.Clone(), new JapaneseCalendar(), "\u548c\u66a6" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("th-TH").DateTimeFormat.Clone(), new ThaiBuddhistCalendar(), "\u0e1e\u0e38\u0e17\u0e18\u0e28\u0e31\u0e01\u0e23\u0e32\u0e0a" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("he-IL").DateTimeFormat.Clone(), new HebrewCalendar(), "\u05dc\u05d5\u05d7\u00a0\u05e9\u05e0\u05d4\u00a0\u05e2\u05d1\u05e8\u05d9" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("ko-KR").DateTimeFormat.Clone(), new KoreanCalendar(), "\ub2e8\uae30" };
yield return new object[] { (DateTimeFormatInfo)new CultureInfo("fa-IR").DateTimeFormat.Clone(), new PersianCalendar(), "\u062a\u0642\u0648\u06cc\u0645\u0020\u0647\u062c\u0631\u06cc\u0020\u0634\u0645\u0633\u06cc" };
}
public static IEnumerable<object[]> CultureNames_TestData()
{
yield return new object[] { "" };
yield return new object[] { "en-US" };
yield return new object[] { "ja-JP" };
yield return new object[] { "zh-CN" };
yield return new object[] { "ar-SA" };
yield return new object[] { "ko-KR" };
yield return new object[] { "he-IL" };
}
[Fact]
public void DateSeparatorTimeSeparator_Get_ReturnsExpected()
{
DateTimeFormatInfo dtfi = (DateTimeFormatInfo) CultureInfo.InvariantCulture.DateTimeFormat.Clone();
Assert.False(dtfi.IsReadOnly, "IsReadOnly expected to be false");
string dateSep = dtfi.DateSeparator;
string timeSep = dtfi.TimeSeparator;
Assert.True(dtfi.ShortDatePattern.IndexOf(dateSep) > 0, "dtfi.ShortDatePattern should be greater than 0");
Assert.True(dtfi.ShortTimePattern.IndexOf(timeSep) > 0, "dtfi.ShortTimePattern should be greater than 0");
DateTime d = DateTime.Now;
string formattedDate = d.ToString("MM/dd/yyyy", dtfi);
Assert.True(formattedDate.IndexOf(dateSep) > 0, "Expected to find date separator in the formatted string");
dtfi.DateSeparator = "-";
string expectedFormattedString = formattedDate.Replace(dateSep, dtfi.DateSeparator);
Assert.Equal(expectedFormattedString, d.ToString("MM/dd/yyyy", dtfi));
string formattedTime = d.ToString("HH:mm:ss", dtfi);
Assert.True(formattedTime.IndexOf(timeSep) > 0, "Expected to find time separator in the formatted string");
dtfi.TimeSeparator = ".";
expectedFormattedString = formattedTime.Replace(timeSep, dtfi.TimeSeparator);
Assert.Equal(expectedFormattedString, d.ToString("HH:mm:ss", dtfi));
}
[Theory]
[MemberData(nameof(DateTimeFormatInfo_TestData))]
public void NativeCalendarName_Get_ReturnsExpected(DateTimeFormatInfo dtfi, Calendar calendar, string nativeCalendarName)
{
try
{
dtfi.Calendar = calendar;
if (PlatformDetection.IsNotUsingLimitedCultures)
{
// Mobile / Browser ICU doesn't contain NativeCalendarName,
Assert.Equal(nativeCalendarName, dtfi.NativeCalendarName);
}
}
catch
{
if (PlatformDetection.IsNlsGlobalization)
{
// Persian calendar is recently supported as one of the optional calendars for fa-IR
Assert.True(calendar is PersianCalendar, "Exception can occur only with PersianCalendar");
}
else // !PlatformDetection.IsNlsGlobalization
{
Assert.True(calendar is HijriCalendar || calendar is UmAlQuraCalendar || calendar is ThaiBuddhistCalendar ||
calendar is HebrewCalendar || calendar is KoreanCalendar, "failed to set the calendar on DTFI");
}
}
}
[Theory]
[MemberData(nameof(CultureNames_TestData))]
public void GetAllDateTimePatterns_Invoke_ReturnsExpected(string cultureName)
{
char[] formats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'o', 'r', 's', 't', 'T', 'u', 'U', 'y' };
DateTimeFormatInfo dtfi = (DateTimeFormatInfo)new CultureInfo(cultureName).DateTimeFormat.Clone();
var allPatterns = dtfi.GetAllDateTimePatterns();
Dictionary<string, string> dic = new Dictionary<string, string>();
string value = "";
foreach (char format in formats)
{
foreach (string pattern in dtfi.GetAllDateTimePatterns(format))
{
if (!dic.TryGetValue(pattern, out value))
{
dic.Add(pattern, "");
}
}
}
foreach (string pattern in allPatterns)
{
Assert.True(dic.TryGetValue(pattern, out value), "Couldn't find the pattern in the patterns list");
}
char[] setterFormats = { 'd', 'D', 't', 'T', 'y', 'Y' };
foreach (char format in setterFormats)
{
var formatPatterns = dtfi.GetAllDateTimePatterns(format);
string [] newPatterns = new string[1] { formatPatterns[formatPatterns.Length - 1] };
dtfi.SetAllDateTimePatterns(newPatterns, format);
Assert.Equal(newPatterns, dtfi.GetAllDateTimePatterns(format));
}
}
[Theory]
[MemberData(nameof(CultureNames_TestData))]
public void GetShortestDayName_Invoke_ReturnsExpected(string cultureName)
{
DateTimeFormatInfo dtfi = new CultureInfo(cultureName).DateTimeFormat;
string [] shortestDayNames = dtfi.ShortestDayNames;
for (DayOfWeek day = DayOfWeek.Sunday; day <= DayOfWeek.Saturday; day++)
{
Assert.Equal(shortestDayNames[(int) day], dtfi.GetShortestDayName(day));
}
}
[Fact]
public void Months_GetHebrew_ReturnsExpected()
{
CultureInfo ci = new CultureInfo("he-IL");
ci.DateTimeFormat.Calendar = new HebrewCalendar();
Assert.Equal(13, ci.DateTimeFormat.MonthNames.Length);
Assert.Equal(13, ci.DateTimeFormat.MonthGenitiveNames.Length);
Assert.Equal(13, ci.DateTimeFormat.AbbreviatedMonthNames.Length);
Assert.Equal(13, ci.DateTimeFormat.AbbreviatedMonthGenitiveNames.Length);
DateTime dt = ci.DateTimeFormat.Calendar.ToDateTime(5779, 1, 1, 0, 0, 0, 0); // leap year
for (int i = 0; i < 13; i++)
{
string formatted = dt.ToString(ci.DateTimeFormat.LongDatePattern, ci);
Assert.Equal(dt, DateTime.ParseExact(formatted, ci.DateTimeFormat.LongDatePattern, ci));
dt = ci.DateTimeFormat.Calendar.AddMonths(dt, 1);
}
dt = ci.DateTimeFormat.Calendar.ToDateTime(5778, 1, 1, 0, 0, 0, 0); // non leap year
for (int i = 0; i < 12; i++)
{
string formatted = dt.ToString(ci.DateTimeFormat.LongDatePattern, ci);
Assert.Equal(dt, DateTime.ParseExact(formatted, ci.DateTimeFormat.LongDatePattern, ci));
dt = ci.DateTimeFormat.Calendar.AddMonths(dt, 1);
}
}
[Fact]
public void TestFirstYearOfJapaneseEra()
{
DateTimeFormatInfo jpnFormat = new CultureInfo("ja-JP").DateTimeFormat;
jpnFormat.Calendar = new JapaneseCalendar();
string pattern = "gg yyyy'\u5E74' MM'\u6708' dd'\u65E5'";
DateTime dt = new DateTime(1989, 01, 08); // Start of Heisei Era
string formattedDateWithGannen = "\u5E73\u6210 \u5143\u5E74 01\u6708 08\u65E5";
string formattedDate = dt.ToString(pattern, jpnFormat);
Assert.True(DateTime.TryParseExact(formattedDate, pattern, jpnFormat, DateTimeStyles.None, out DateTime parsedDate));
Assert.Equal(dt, parsedDate);
// If the formatting with Gan-nen is supported, then parsing should succeed. otherwise parsing should fail.
Assert.True(formattedDate.IndexOf("\u5143", StringComparison.Ordinal) >= 0 ==
DateTime.TryParseExact(formattedDateWithGannen, pattern, jpnFormat, DateTimeStyles.None, out parsedDate),
$"Parsing '{formattedDateWithGannen}' result should match if '{formattedDate}' has Gan-nen symbol"
);
}
[Fact]
public void JapaneseAbbreviatedEnglishEraNamesTest()
{
string [] eraNames = { "M", "T", "S", "H", "R" };
var ci = new CultureInfo("ja-JP") { DateTimeFormat = { Calendar = new JapaneseCalendar() }};
int eraNumber = ci.DateTimeFormat.GetEra("Q");
if (eraNumber == 4 || eraNumber == 5)
{
// Skip the test on Windows versions which have wrong Japanese Era information.
// Windows at some point used "Q" as fake era name before getting the official name.
return;
}
int numberOfErasToTest = Math.Min(eraNames.Length, ci.DateTimeFormat.Calendar.Eras.Length);
for (int i = 0; i < numberOfErasToTest; i++)
{
Assert.Equal(i + 1, ci.DateTimeFormat.GetEra(eraNames[i]));
}
}
[Fact]
public void TestFrenchCanadaTimeFormat()
{
CultureInfo ci = CultureInfo.GetCultureInfo("fr-CA");
Assert.Equal(":", ci.DateTimeFormat.TimeSeparator);
DateTime time = new DateTime(2021, 10, 1, 5, 36, 50);
string formattedTime = time.ToString("HH 'h' mm 'min' ss 's'", ci);
DateTime dt = DateTime.Parse(formattedTime, ci);
Assert.Equal(time.TimeOfDay, dt.TimeOfDay);
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAEncryptionPaddingMode.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.Cryptography
{
/// <summary>
/// Specifies the padding mode to use with RSA encryption or decryption operations.
/// </summary>
public enum RSAEncryptionPaddingMode
{
/// <summary>
/// PKCS #1 v1.5.
/// </summary>
/// <remarks>
/// This mode corresponds to the RSAES-PKCS1-v1_5 encryption scheme described in the PKCS #1 RSA Encryption Standard.
/// It is supported for compatibility with existing applications.
/// </remarks>
Pkcs1,
/// <summary>
/// Optimal Asymmetric Encryption Padding.
/// </summary>
/// <remarks>
/// This mode corresponds to the RSAES-OEAP encryption scheme described in the PKCS #1 RSA Encryption Standard.
/// It is recommended for new applications.
/// </remarks>
Oaep,
}
}
| // 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.Cryptography
{
/// <summary>
/// Specifies the padding mode to use with RSA encryption or decryption operations.
/// </summary>
public enum RSAEncryptionPaddingMode
{
/// <summary>
/// PKCS #1 v1.5.
/// </summary>
/// <remarks>
/// This mode corresponds to the RSAES-PKCS1-v1_5 encryption scheme described in the PKCS #1 RSA Encryption Standard.
/// It is supported for compatibility with existing applications.
/// </remarks>
Pkcs1,
/// <summary>
/// Optimal Asymmetric Encryption Padding.
/// </summary>
/// <remarks>
/// This mode corresponds to the RSAES-OEAP encryption scheme described in the PKCS #1 RSA Encryption Standard.
/// It is recommended for new applications.
/// </remarks>
Oaep,
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/General/Vector64/EqualsAny.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 EqualsAnyUInt32()
{
var test = new VectorBooleanBinaryOpTest__EqualsAnyUInt32();
// 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__EqualsAnyUInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
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<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 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<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(VectorBooleanBinaryOpTest__EqualsAnyUInt32 testClass)
{
var result = Vector64.EqualsAny(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
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 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 VectorBooleanBinaryOpTest__EqualsAnyUInt32()
{
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 VectorBooleanBinaryOpTest__EqualsAnyUInt32()
{
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, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.EqualsAny(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_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.EqualsAny), new Type[] {
typeof(Vector64<UInt32>),
typeof(Vector64<UInt32>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.EqualsAny), 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)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.EqualsAny(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
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.EqualsAny(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__EqualsAnyUInt32();
var result = Vector64.EqualsAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.EqualsAny(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.EqualsAny(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<UInt32> op1, Vector64<UInt32> op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
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>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt32[] left, UInt32[] 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.EqualsAny)}<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: ({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 EqualsAnyUInt32()
{
var test = new VectorBooleanBinaryOpTest__EqualsAnyUInt32();
// 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__EqualsAnyUInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
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<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 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<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(VectorBooleanBinaryOpTest__EqualsAnyUInt32 testClass)
{
var result = Vector64.EqualsAny(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
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 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 VectorBooleanBinaryOpTest__EqualsAnyUInt32()
{
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 VectorBooleanBinaryOpTest__EqualsAnyUInt32()
{
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, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.EqualsAny(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_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.EqualsAny), new Type[] {
typeof(Vector64<UInt32>),
typeof(Vector64<UInt32>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.EqualsAny), 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)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.EqualsAny(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
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.EqualsAny(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__EqualsAnyUInt32();
var result = Vector64.EqualsAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.EqualsAny(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.EqualsAny(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<UInt32> op1, Vector64<UInt32> op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
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>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt32[] left, UInt32[] 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.EqualsAny)}<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: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/mono/sample/mbr/apple/Program.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
public static class Program
{
// Defined in main.m
[DllImport("__Internal")]
private static extern void ios_set_text(string value);
[DllImport("__Internal")]
unsafe private static extern void ios_register_button_click(delegate* unmanaged<void> callback);
[DllImport("__Internal")]
unsafe private static extern void ios_register_applyupdate_click(delegate* unmanaged<void> callback);
private static int counter = 0;
// Called by native code, see main.m
[UnmanagedCallersOnly]
private static void OnButtonClick()
{
ios_set_text("OnButtonClick! #" + ChangeablePart.UpdateCounter (ref counter));
}
[UnmanagedCallersOnly]
private static void OnApplyUpdateClick()
{
deltaHelper.Update (typeof(ChangeablePart).Assembly);
}
static MonoDelta.DeltaHelper deltaHelper;
public static async Task Main(string[] args)
{
unsafe {
// Register a managed callback (will be called by UIButton, see main.m)
delegate* unmanaged<void> unmanagedPtr = &OnButtonClick;
ios_register_button_click(unmanagedPtr);
delegate* unmanaged<void> unmanagedPtr2 = &OnApplyUpdateClick;
ios_register_applyupdate_click(unmanagedPtr2);
}
deltaHelper = MonoDelta.DeltaHelper.Make();
const string msg = "Hello World!\n.NET 5.0";
for (int i = 0; i < msg.Length; i++)
{
// a kind of an animation
ios_set_text(msg.Substring(0, i + 1));
await Task.Delay(100);
}
Console.WriteLine("Done!");
await Task.Delay(-1);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
public static class Program
{
// Defined in main.m
[DllImport("__Internal")]
private static extern void ios_set_text(string value);
[DllImport("__Internal")]
unsafe private static extern void ios_register_button_click(delegate* unmanaged<void> callback);
[DllImport("__Internal")]
unsafe private static extern void ios_register_applyupdate_click(delegate* unmanaged<void> callback);
private static int counter = 0;
// Called by native code, see main.m
[UnmanagedCallersOnly]
private static void OnButtonClick()
{
ios_set_text("OnButtonClick! #" + ChangeablePart.UpdateCounter (ref counter));
}
[UnmanagedCallersOnly]
private static void OnApplyUpdateClick()
{
deltaHelper.Update (typeof(ChangeablePart).Assembly);
}
static MonoDelta.DeltaHelper deltaHelper;
public static async Task Main(string[] args)
{
unsafe {
// Register a managed callback (will be called by UIButton, see main.m)
delegate* unmanaged<void> unmanagedPtr = &OnButtonClick;
ios_register_button_click(unmanagedPtr);
delegate* unmanaged<void> unmanagedPtr2 = &OnApplyUpdateClick;
ios_register_applyupdate_click(unmanagedPtr2);
}
deltaHelper = MonoDelta.DeltaHelper.Make();
const string msg = "Hello World!\n.NET 5.0";
for (int i = 0; i < msg.Length; i++)
{
// a kind of an animation
ios_set_text(msg.Substring(0, i + 1));
await Task.Delay(100);
}
Console.WriteLine("Done!");
await Task.Delay(-1);
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.CoreLib/src/Internal/AssemblyAttributes.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 exists to contain miscellaneous module-level attributes
** and other miscellaneous stuff.
**
**
**
===========================================================*/
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Resources;
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.System32)]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: NeutralResourcesLanguage("en-US")]
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
** This file exists to contain miscellaneous module-level attributes
** and other miscellaneous stuff.
**
**
**
===========================================================*/
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Resources;
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.System32)]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: NeutralResourcesLanguage("en-US")]
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/CoreMangLib/system/threading/interlocked/interlockedexchange5.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
// Tests that Exchange(Int64, Int64)
// actually switches values
public class InterlockedExchange5
{
private const int c_NUM_LOOPS = 100;
public static int Main()
{
InterlockedExchange5 test = new InterlockedExchange5();
TestLibrary.TestFramework.BeginTestCase("InterlockedExchange5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
Int64 location;
Int64 value;
Int64 prevLocation;
Int64 oldLocation;
TestLibrary.TestFramework.BeginScenario("PosTest1: Int64 Interlocked.Exchange(Int64&,Int64)");
try
{
for (int i=0; i<c_NUM_LOOPS; i++)
{
value = TestLibrary.Generator.GetInt64(-55);
location = TestLibrary.Generator.GetInt64(-55);
prevLocation = location;
oldLocation = Interlocked.Exchange(ref location, value);
if (!location.Equals(value))
{
TestLibrary.TestFramework.LogError("001", "Interlocked.Exchange() did not do the exchange correctly: Expected(" + value + ") Actual(" + location + ")");
retVal = false;
}
if (!oldLocation.Equals(prevLocation))
{
TestLibrary.TestFramework.LogError("002", "Interlocked.Exchange() did not return the expected value: Expected(" + prevLocation + ") Actual(" + oldLocation + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
// Tests that Exchange(Int64, Int64)
// actually switches values
public class InterlockedExchange5
{
private const int c_NUM_LOOPS = 100;
public static int Main()
{
InterlockedExchange5 test = new InterlockedExchange5();
TestLibrary.TestFramework.BeginTestCase("InterlockedExchange5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
Int64 location;
Int64 value;
Int64 prevLocation;
Int64 oldLocation;
TestLibrary.TestFramework.BeginScenario("PosTest1: Int64 Interlocked.Exchange(Int64&,Int64)");
try
{
for (int i=0; i<c_NUM_LOOPS; i++)
{
value = TestLibrary.Generator.GetInt64(-55);
location = TestLibrary.Generator.GetInt64(-55);
prevLocation = location;
oldLocation = Interlocked.Exchange(ref location, value);
if (!location.Equals(value))
{
TestLibrary.TestFramework.LogError("001", "Interlocked.Exchange() did not do the exchange correctly: Expected(" + value + ") Actual(" + location + ")");
retVal = false;
}
if (!oldLocation.Equals(prevLocation))
{
TestLibrary.TestFramework.LogError("002", "Interlocked.Exchange() did not return the expected value: Expected(" + prevLocation + ") Actual(" + oldLocation + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/Interop/IJW/FixupCallsHostWhenLoaded/FixupCallsHostWhenLoaded.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
namespace FixupCallsHostWhenLoaded
{
class FixupCallsHostWhenLoaded
{
static int Main(string[] args)
{
// Disable running on Windows 7 until IJW activation work is complete.
if(Environment.OSVersion.Platform != PlatformID.Win32NT || TestLibrary.Utilities.IsWindows7)
{
return 100;
}
try
{
IntPtr ijwHost = NativeLibrary.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ijwhost.dll"));
WasModuleVTableQueriedDelegate wasModuleVTableQueried = Marshal.GetDelegateForFunctionPointer<WasModuleVTableQueriedDelegate>(NativeLibrary.GetExport(ijwHost, "WasModuleVTableQueried"));
// Load IJW via reflection
Assembly.Load("IjwNativeDll");
IntPtr ijwModuleHandle = GetModuleHandle("IjwNativeDll.dll");
Assert.NotEqual(IntPtr.Zero, ijwModuleHandle);
Assert.True(wasModuleVTableQueried(ijwModuleHandle));
}
catch (Exception e)
{
Console.WriteLine(e);
return 101;
}
return 100;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate bool WasModuleVTableQueriedDelegate(IntPtr handle);
[DllImport("kernel32.dll")]
static extern IntPtr GetModuleHandle(string lpModuleName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
namespace FixupCallsHostWhenLoaded
{
class FixupCallsHostWhenLoaded
{
static int Main(string[] args)
{
// Disable running on Windows 7 until IJW activation work is complete.
if(Environment.OSVersion.Platform != PlatformID.Win32NT || TestLibrary.Utilities.IsWindows7)
{
return 100;
}
try
{
IntPtr ijwHost = NativeLibrary.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ijwhost.dll"));
WasModuleVTableQueriedDelegate wasModuleVTableQueried = Marshal.GetDelegateForFunctionPointer<WasModuleVTableQueriedDelegate>(NativeLibrary.GetExport(ijwHost, "WasModuleVTableQueried"));
// Load IJW via reflection
Assembly.Load("IjwNativeDll");
IntPtr ijwModuleHandle = GetModuleHandle("IjwNativeDll.dll");
Assert.NotEqual(IntPtr.Zero, ijwModuleHandle);
Assert.True(wasModuleVTableQueried(ijwModuleHandle));
}
catch (Exception e)
{
Console.WriteLine(e);
return 101;
}
return 100;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate bool WasModuleVTableQueriedDelegate(IntPtr handle);
[DllImport("kernel32.dll")]
static extern IntPtr GetModuleHandle(string lpModuleName);
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Speech/src/Synthesis/SpeakCompletedEventArgs.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.Speech.Synthesis
{
public class SpeakCompletedEventArgs : PromptEventArgs
{
#region Constructors
internal SpeakCompletedEventArgs(Prompt prompt) : base(prompt)
{
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Speech.Synthesis
{
public class SpeakCompletedEventArgs : PromptEventArgs
{
#region Constructors
internal SpeakCompletedEventArgs(Prompt prompt) : base(prompt)
{
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.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.Composition.Primitives;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
/// <summary>
/// A mutable collection of <see cref="ComposablePartCatalog"/>s.
/// </summary>
/// <remarks>
/// This type is thread safe.
/// </remarks>
public class CompositionService : ICompositionService, IDisposable
{
private readonly CompositionContainer? _compositionContainer;
private readonly INotifyComposablePartCatalogChanged? _notifyCatalog;
internal CompositionService(ComposablePartCatalog composablePartCatalog!!)
{
_notifyCatalog = composablePartCatalog as INotifyComposablePartCatalogChanged;
try
{
if (_notifyCatalog != null)
{
_notifyCatalog.Changing += OnCatalogChanging;
}
var compositionOptions = CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService;
var compositionContainer = new CompositionContainer(composablePartCatalog, compositionOptions);
_compositionContainer = compositionContainer;
}
catch
{
if (_notifyCatalog != null)
{
_notifyCatalog.Changing -= OnCatalogChanging;
}
throw;
}
}
public void SatisfyImportsOnce(ComposablePart part)
{
Requires.NotNull(part, nameof(part));
if (_compositionContainer == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
_compositionContainer.SatisfyImportsOnce(part);
}
public void Dispose()
{
if (_compositionContainer == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
// Delegates are cool there is no concern if you try to remove an item from them and they don't exist
if (_notifyCatalog != null)
{
_notifyCatalog.Changing -= OnCatalogChanging;
}
_compositionContainer.Dispose();
}
private void OnCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e)
{
throw new ChangeRejectedException(SR.NotSupportedCatalogChanges);
}
}
}
| // 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.Composition.Primitives;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
/// <summary>
/// A mutable collection of <see cref="ComposablePartCatalog"/>s.
/// </summary>
/// <remarks>
/// This type is thread safe.
/// </remarks>
public class CompositionService : ICompositionService, IDisposable
{
private readonly CompositionContainer? _compositionContainer;
private readonly INotifyComposablePartCatalogChanged? _notifyCatalog;
internal CompositionService(ComposablePartCatalog composablePartCatalog!!)
{
_notifyCatalog = composablePartCatalog as INotifyComposablePartCatalogChanged;
try
{
if (_notifyCatalog != null)
{
_notifyCatalog.Changing += OnCatalogChanging;
}
var compositionOptions = CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService;
var compositionContainer = new CompositionContainer(composablePartCatalog, compositionOptions);
_compositionContainer = compositionContainer;
}
catch
{
if (_notifyCatalog != null)
{
_notifyCatalog.Changing -= OnCatalogChanging;
}
throw;
}
}
public void SatisfyImportsOnce(ComposablePart part)
{
Requires.NotNull(part, nameof(part));
if (_compositionContainer == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
_compositionContainer.SatisfyImportsOnce(part);
}
public void Dispose()
{
if (_compositionContainer == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
// Delegates are cool there is no concern if you try to remove an item from them and they don't exist
if (_notifyCatalog != null)
{
_notifyCatalog.Changing -= OnCatalogChanging;
}
_compositionContainer.Dispose();
}
private void OnCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e)
{
throw new ChangeRejectedException(SR.NotSupportedCatalogChanges);
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=============================================================================
**
**
** Purpose: An array implementation of a generic stack.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
[DebuggerTypeProxy(typeof(StackDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Stack<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array; // Storage for stack elements. Do not rename (binary serialization)
private int _size; // Number of items in the stack. Do not rename (binary serialization)
private int _version; // Used to keep enumerator in sync w/ collection. Do not rename (binary serialization)
private const int DefaultCapacity = 4;
public Stack()
{
_array = Array.Empty<T>();
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
public Stack(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
public Stack(IEnumerable<T> collection!!)
{
_array = EnumerableHelpers.ToArray(collection, out _size);
}
public int Count
{
get { return _size; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot => this;
// Removes all Objects from the Stack.
public void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
}
_size = 0;
_version++;
}
public bool Contains(T item)
{
// Compare items using the default equality comparer
// PERF: Internally Array.LastIndexOf calls
// EqualityComparer<T>.Default.LastIndexOf, which
// is specialized for different types. This
// boosts performance since instead of making a
// virtual method call each iteration of the loop,
// via EqualityComparer<T>.Default.Equals, we
// only make one virtual call to EqualityComparer.LastIndexOf.
return _size != 0 && Array.LastIndexOf(_array, item, _size - 1) != -1;
}
// Copies the stack into an array.
public void CopyTo(T[] array!!, int arrayIndex)
{
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Debug.Assert(array != _array);
int srcIndex = 0;
int dstIndex = arrayIndex + _size;
while (srcIndex < _size)
{
array[--dstIndex] = _array[srcIndex++];
}
}
void ICollection.CopyTo(Array array!!, int arrayIndex)
{
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
try
{
Array.Copy(_array, 0, array, arrayIndex, _size);
Array.Reverse(array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Returns an IEnumerator for this Stack.
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public void TrimExcess()
{
int threshold = (int)(_array.Length * 0.9);
if (_size < threshold)
{
Array.Resize(ref _array, _size);
_version++;
}
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
public T Peek()
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
ThrowForEmptyStack();
}
return array[size];
}
public bool TryPeek([MaybeNullWhen(false)] out T result)
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
result = default!;
return false;
}
result = array[size];
return true;
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
public T Pop()
{
int size = _size - 1;
T[] array = _array;
// if (_size == 0) is equivalent to if (size == -1), and this case
// is covered with (uint)size, thus allowing bounds check elimination
// https://github.com/dotnet/coreclr/pull/9773
if ((uint)size >= (uint)array.Length)
{
ThrowForEmptyStack();
}
_version++;
_size = size;
T item = array[size];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
array[size] = default!; // Free memory quicker.
}
return item;
}
public bool TryPop([MaybeNullWhen(false)] out T result)
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
result = default!;
return false;
}
_version++;
_size = size;
result = array[size];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
array[size] = default!;
}
return true;
}
// Pushes an item to the top of the stack.
public void Push(T item)
{
int size = _size;
T[] array = _array;
if ((uint)size < (uint)array.Length)
{
array[size] = item;
_version++;
_size = size + 1;
}
else
{
PushWithResize(item);
}
}
// Non-inline from Stack.Push to improve its code quality as uncommon path
[MethodImpl(MethodImplOptions.NoInlining)]
private void PushWithResize(T item)
{
Debug.Assert(_size == _array.Length);
Grow(_size + 1);
_array[_size] = item;
_version++;
_size++;
}
/// <summary>
/// Ensures that the capacity of this Stack is at least the specified <paramref name="capacity"/>.
/// If the current capacity of the Stack is less than specified <paramref name="capacity"/>,
/// the capacity is increased by continuously twice current capacity until it is at least the specified <paramref name="capacity"/>.
/// </summary>
/// <param name="capacity">The minimum capacity to ensure.</param>
/// <returns>The new capacity of this stack.</returns>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_array.Length < capacity)
{
Grow(capacity);
_version++;
}
return _array.Length;
}
private void Grow(int capacity)
{
Debug.Assert(_array.Length < capacity);
int newcapacity = _array.Length == 0 ? DefaultCapacity : 2 * _array.Length;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast.
if ((uint)newcapacity > Array.MaxLength) newcapacity = Array.MaxLength;
// If computed capacity is still less than specified, set to the original argument.
// Capacities exceeding Array.MaxLength will be surfaced as OutOfMemoryException by Array.Resize.
if (newcapacity < capacity) newcapacity = capacity;
Array.Resize(ref _array, newcapacity);
}
// Copies the Stack to an array, in the same order Pop would return the items.
public T[] ToArray()
{
if (_size == 0)
return Array.Empty<T>();
T[] objArray = new T[_size];
int i = 0;
while (i < _size)
{
objArray[i] = _array[_size - i - 1];
i++;
}
return objArray;
}
private void ThrowForEmptyStack()
{
Debug.Assert(_size == 0);
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
}
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private readonly Stack<T> _stack;
private readonly int _version;
private int _index;
private T? _currentElement;
internal Enumerator(Stack<T> stack)
{
_stack = stack;
_version = stack._version;
_index = -2;
_currentElement = default;
}
public void Dispose()
{
_index = -1;
}
public bool MoveNext()
{
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
{ // First call to enumerator.
_index = _stack._size - 1;
retval = (_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
return retval;
}
if (_index == -1)
{ // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
else
_currentElement = default;
return retval;
}
public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement!;
}
}
private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -2 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}
object? System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -2;
_currentElement = default;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=============================================================================
**
**
** Purpose: An array implementation of a generic stack.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
[DebuggerTypeProxy(typeof(StackDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Stack<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array; // Storage for stack elements. Do not rename (binary serialization)
private int _size; // Number of items in the stack. Do not rename (binary serialization)
private int _version; // Used to keep enumerator in sync w/ collection. Do not rename (binary serialization)
private const int DefaultCapacity = 4;
public Stack()
{
_array = Array.Empty<T>();
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
public Stack(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
public Stack(IEnumerable<T> collection!!)
{
_array = EnumerableHelpers.ToArray(collection, out _size);
}
public int Count
{
get { return _size; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot => this;
// Removes all Objects from the Stack.
public void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
}
_size = 0;
_version++;
}
public bool Contains(T item)
{
// Compare items using the default equality comparer
// PERF: Internally Array.LastIndexOf calls
// EqualityComparer<T>.Default.LastIndexOf, which
// is specialized for different types. This
// boosts performance since instead of making a
// virtual method call each iteration of the loop,
// via EqualityComparer<T>.Default.Equals, we
// only make one virtual call to EqualityComparer.LastIndexOf.
return _size != 0 && Array.LastIndexOf(_array, item, _size - 1) != -1;
}
// Copies the stack into an array.
public void CopyTo(T[] array!!, int arrayIndex)
{
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Debug.Assert(array != _array);
int srcIndex = 0;
int dstIndex = arrayIndex + _size;
while (srcIndex < _size)
{
array[--dstIndex] = _array[srcIndex++];
}
}
void ICollection.CopyTo(Array array!!, int arrayIndex)
{
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
try
{
Array.Copy(_array, 0, array, arrayIndex, _size);
Array.Reverse(array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Returns an IEnumerator for this Stack.
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public void TrimExcess()
{
int threshold = (int)(_array.Length * 0.9);
if (_size < threshold)
{
Array.Resize(ref _array, _size);
_version++;
}
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
public T Peek()
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
ThrowForEmptyStack();
}
return array[size];
}
public bool TryPeek([MaybeNullWhen(false)] out T result)
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
result = default!;
return false;
}
result = array[size];
return true;
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
public T Pop()
{
int size = _size - 1;
T[] array = _array;
// if (_size == 0) is equivalent to if (size == -1), and this case
// is covered with (uint)size, thus allowing bounds check elimination
// https://github.com/dotnet/coreclr/pull/9773
if ((uint)size >= (uint)array.Length)
{
ThrowForEmptyStack();
}
_version++;
_size = size;
T item = array[size];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
array[size] = default!; // Free memory quicker.
}
return item;
}
public bool TryPop([MaybeNullWhen(false)] out T result)
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
result = default!;
return false;
}
_version++;
_size = size;
result = array[size];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
array[size] = default!;
}
return true;
}
// Pushes an item to the top of the stack.
public void Push(T item)
{
int size = _size;
T[] array = _array;
if ((uint)size < (uint)array.Length)
{
array[size] = item;
_version++;
_size = size + 1;
}
else
{
PushWithResize(item);
}
}
// Non-inline from Stack.Push to improve its code quality as uncommon path
[MethodImpl(MethodImplOptions.NoInlining)]
private void PushWithResize(T item)
{
Debug.Assert(_size == _array.Length);
Grow(_size + 1);
_array[_size] = item;
_version++;
_size++;
}
/// <summary>
/// Ensures that the capacity of this Stack is at least the specified <paramref name="capacity"/>.
/// If the current capacity of the Stack is less than specified <paramref name="capacity"/>,
/// the capacity is increased by continuously twice current capacity until it is at least the specified <paramref name="capacity"/>.
/// </summary>
/// <param name="capacity">The minimum capacity to ensure.</param>
/// <returns>The new capacity of this stack.</returns>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_array.Length < capacity)
{
Grow(capacity);
_version++;
}
return _array.Length;
}
private void Grow(int capacity)
{
Debug.Assert(_array.Length < capacity);
int newcapacity = _array.Length == 0 ? DefaultCapacity : 2 * _array.Length;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast.
if ((uint)newcapacity > Array.MaxLength) newcapacity = Array.MaxLength;
// If computed capacity is still less than specified, set to the original argument.
// Capacities exceeding Array.MaxLength will be surfaced as OutOfMemoryException by Array.Resize.
if (newcapacity < capacity) newcapacity = capacity;
Array.Resize(ref _array, newcapacity);
}
// Copies the Stack to an array, in the same order Pop would return the items.
public T[] ToArray()
{
if (_size == 0)
return Array.Empty<T>();
T[] objArray = new T[_size];
int i = 0;
while (i < _size)
{
objArray[i] = _array[_size - i - 1];
i++;
}
return objArray;
}
private void ThrowForEmptyStack()
{
Debug.Assert(_size == 0);
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
}
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private readonly Stack<T> _stack;
private readonly int _version;
private int _index;
private T? _currentElement;
internal Enumerator(Stack<T> stack)
{
_stack = stack;
_version = stack._version;
_index = -2;
_currentElement = default;
}
public void Dispose()
{
_index = -1;
}
public bool MoveNext()
{
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
{ // First call to enumerator.
_index = _stack._size - 1;
retval = (_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
return retval;
}
if (_index == -1)
{ // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
else
_currentElement = default;
return retval;
}
public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement!;
}
}
private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -2 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}
object? System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -2;
_currentElement = default;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/X86/Fma_Vector128/MultiplySubtract.Double.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplySubtractDouble()
{
var test = new SimpleTernaryOpTest__MultiplySubtractDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplySubtractDouble
{
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(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public Vector128<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractDouble testClass)
{
var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private static Vector128<Double> _clsVar3;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private Vector128<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplySubtractDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleTernaryOpTest__MultiplySubtractDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtract(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtract(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtract(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
fixed (Vector128<Double>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2)),
Sse2.LoadVector128((Double*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplySubtractDouble();
var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplySubtractDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
fixed (Vector128<Double>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2)),
Sse2.LoadVector128((Double*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[0] * secondOp[0]) - thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i] * secondOp[i]) - thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtract)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplySubtractDouble()
{
var test = new SimpleTernaryOpTest__MultiplySubtractDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplySubtractDouble
{
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(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public Vector128<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractDouble testClass)
{
var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private static Vector128<Double> _clsVar3;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private Vector128<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplySubtractDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleTernaryOpTest__MultiplySubtractDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtract(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtract(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtract(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
fixed (Vector128<Double>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2)),
Sse2.LoadVector128((Double*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplySubtractDouble();
var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplySubtractDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
fixed (Vector128<Double>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtract(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2)),
Sse2.LoadVector128((Double*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[0] * secondOp[0]) - thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i] * secondOp[i]) - thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtract)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Collections;
namespace System.Xml.Xsl.XsltOld
{
internal sealed class WriterOutput : IRecordOutput
{
private XmlWriter _writer;
private readonly Processor _processor;
internal WriterOutput(Processor processor, XmlWriter writer!!)
{
_writer = writer;
_processor = processor;
}
// RecordOutput interface method implementation
//
public Processor.OutputResult RecordDone(RecordBuilder record)
{
BuilderInfo mainNode = record.MainNode;
switch (mainNode.NodeType)
{
case XmlNodeType.Element:
_writer.WriteStartElement(mainNode.Prefix, mainNode.LocalName, mainNode.NamespaceURI);
WriteAttributes(record.AttributeList, record.AttributeCount);
if (mainNode.IsEmptyTag)
{
_writer.WriteEndElement();
}
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_writer.WriteString(mainNode.Value);
break;
case XmlNodeType.CDATA:
Debug.Fail("XSLT never gives us CDATA");
_writer.WriteCData(mainNode.Value);
break;
case XmlNodeType.EntityReference:
_writer.WriteEntityRef(mainNode.LocalName);
break;
case XmlNodeType.ProcessingInstruction:
_writer.WriteProcessingInstruction(mainNode.LocalName, mainNode.Value);
break;
case XmlNodeType.Comment:
_writer.WriteComment(mainNode.Value);
break;
case XmlNodeType.Document:
break;
case XmlNodeType.DocumentType:
_writer.WriteRaw(mainNode.Value);
break;
case XmlNodeType.EndElement:
_writer.WriteFullEndElement();
break;
case XmlNodeType.None:
case XmlNodeType.Attribute:
case XmlNodeType.Entity:
case XmlNodeType.Notation:
case XmlNodeType.DocumentFragment:
case XmlNodeType.EndEntity:
break;
default:
Debug.Fail($"Invalid NodeType on output: {mainNode.NodeType}");
break;
}
record.Reset();
return Processor.OutputResult.Continue;
}
public void TheEnd()
{
_writer.Flush();
_writer = null!;
}
private void WriteAttributes(ArrayList list, int count)
{
Debug.Assert(list.Count >= count);
for (int attrib = 0; attrib < count; attrib++)
{
Debug.Assert(list[attrib] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)list[attrib]!;
_writer.WriteAttributeString(attribute.Prefix, attribute.LocalName, attribute.NamespaceURI, attribute.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.Diagnostics;
using System.Collections;
namespace System.Xml.Xsl.XsltOld
{
internal sealed class WriterOutput : IRecordOutput
{
private XmlWriter _writer;
private readonly Processor _processor;
internal WriterOutput(Processor processor, XmlWriter writer!!)
{
_writer = writer;
_processor = processor;
}
// RecordOutput interface method implementation
//
public Processor.OutputResult RecordDone(RecordBuilder record)
{
BuilderInfo mainNode = record.MainNode;
switch (mainNode.NodeType)
{
case XmlNodeType.Element:
_writer.WriteStartElement(mainNode.Prefix, mainNode.LocalName, mainNode.NamespaceURI);
WriteAttributes(record.AttributeList, record.AttributeCount);
if (mainNode.IsEmptyTag)
{
_writer.WriteEndElement();
}
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_writer.WriteString(mainNode.Value);
break;
case XmlNodeType.CDATA:
Debug.Fail("XSLT never gives us CDATA");
_writer.WriteCData(mainNode.Value);
break;
case XmlNodeType.EntityReference:
_writer.WriteEntityRef(mainNode.LocalName);
break;
case XmlNodeType.ProcessingInstruction:
_writer.WriteProcessingInstruction(mainNode.LocalName, mainNode.Value);
break;
case XmlNodeType.Comment:
_writer.WriteComment(mainNode.Value);
break;
case XmlNodeType.Document:
break;
case XmlNodeType.DocumentType:
_writer.WriteRaw(mainNode.Value);
break;
case XmlNodeType.EndElement:
_writer.WriteFullEndElement();
break;
case XmlNodeType.None:
case XmlNodeType.Attribute:
case XmlNodeType.Entity:
case XmlNodeType.Notation:
case XmlNodeType.DocumentFragment:
case XmlNodeType.EndEntity:
break;
default:
Debug.Fail($"Invalid NodeType on output: {mainNode.NodeType}");
break;
}
record.Reset();
return Processor.OutputResult.Continue;
}
public void TheEnd()
{
_writer.Flush();
_writer = null!;
}
private void WriteAttributes(ArrayList list, int count)
{
Debug.Assert(list.Count >= count);
for (int attrib = 0; attrib < count; attrib++)
{
Debug.Assert(list[attrib] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)list[attrib]!;
_writer.WriteAttributeString(attribute.Prefix, attribute.LocalName, attribute.NamespaceURI, attribute.Value);
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.IO.Ports/tests/Support/KnownFailureAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Xunit.Sdk;
using Xunit.Abstractions;
namespace Legacy.Support
{
[TraitDiscoverer("Legacy.Support.KnownFailureDiscoverer", "System.IO.Ports.Tests")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
class KnownFailureAttribute : Attribute, ITraitAttribute
{
public KnownFailureAttribute() { }
}
public class KnownFailureDiscoverer : ITraitDiscoverer
{
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
yield return new KeyValuePair<string, string>("KnownFailure", "true");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Xunit.Sdk;
using Xunit.Abstractions;
namespace Legacy.Support
{
[TraitDiscoverer("Legacy.Support.KnownFailureDiscoverer", "System.IO.Ports.Tests")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
class KnownFailureAttribute : Attribute, ITraitAttribute
{
public KnownFailureAttribute() { }
}
public class KnownFailureDiscoverer : ITraitDiscoverer
{
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
yield return new KeyValuePair<string, string>("KnownFailure", "true");
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Runtime.Serialization.Formatters/tests/SerializationBinderTests.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.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
public class SerializationBinderTests
{
[Fact]
public void BindToName_NullDefaults()
{
var b = new TrackAllBindToTypes();
string assemblyName, typeName;
b.BindToName(typeof(string), out assemblyName, out typeName);
Assert.Null(assemblyName);
Assert.Null(typeName);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
public void BindToType_AllValuesTracked()
{
var s = new MemoryStream();
var f = new BinaryFormatter();
f.Serialize(s, DayOfWeek.Monday);
s.Position = 0;
var t = new TrackAllBindToTypes();
f.Binder = t;
f.Deserialize(s);
Assert.Contains(t.Binds, kvp => kvp.Value.Contains("System.DayOfWeek"));
}
private class TrackAllBindToTypes : SerializationBinder
{
public readonly List<KeyValuePair<string, string>> Binds = new List<KeyValuePair<string, string>>();
public override Type BindToType(string assemblyName, string typeName)
{
Binds.Add(new KeyValuePair<string, string>(assemblyName, typeName));
return Assembly.Load(new AssemblyName(assemblyName)).GetType(typeName);
}
}
}
}
| // 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.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
public class SerializationBinderTests
{
[Fact]
public void BindToName_NullDefaults()
{
var b = new TrackAllBindToTypes();
string assemblyName, typeName;
b.BindToName(typeof(string), out assemblyName, out typeName);
Assert.Null(assemblyName);
Assert.Null(typeName);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
public void BindToType_AllValuesTracked()
{
var s = new MemoryStream();
var f = new BinaryFormatter();
f.Serialize(s, DayOfWeek.Monday);
s.Position = 0;
var t = new TrackAllBindToTypes();
f.Binder = t;
f.Deserialize(s);
Assert.Contains(t.Binds, kvp => kvp.Value.Contains("System.DayOfWeek"));
}
private class TrackAllBindToTypes : SerializationBinder
{
public readonly List<KeyValuePair<string, string>> Binds = new List<KeyValuePair<string, string>>();
public override Type BindToType(string assemblyName, string typeName)
{
Binds.Add(new KeyValuePair<string, string>(assemblyName, typeName));
return Assembly.Load(new AssemblyName(assemblyName)).GetType(typeName);
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.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;
namespace System.Xml
{
internal partial interface IDtdParser
{
IDtdInfo ParseInternalDtd(IDtdParserAdapter adapter, bool saveInternalSubset);
IDtdInfo ParseFreeFloatingDtd(string baseUri, string docTypeName, string? publicId, string? systemId, string? internalSubset, IDtdParserAdapter adapter);
}
}
| // 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;
namespace System.Xml
{
internal partial interface IDtdParser
{
IDtdInfo ParseInternalDtd(IDtdParserAdapter adapter, bool saveInternalSubset);
IDtdInfo ParseFreeFloatingDtd(string baseUri, string docTypeName, string? publicId, string? systemId, string? internalSubset, IDtdParserAdapter adapter);
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/FusedMultiplySubtractBySelectedScalar.Vector128.Double.Vector128.Double.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 FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1()
{
var test = new SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_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 SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1
{
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(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public Vector128<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1 testClass)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(_fld1, _fld2, _fld3, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1 testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(pFld1)),
AdvSimd.LoadVector128((Double*)(pFld2)),
AdvSimd.LoadVector128((Double*)(pFld3)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly byte Imm = 1;
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private static Vector128<Double> _clsVar3;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private Vector128<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
_clsVar1,
_clsVar2,
_clsVar3,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
fixed (Vector128<Double>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(pClsVar1)),
AdvSimd.LoadVector128((Double*)(pClsVar2)),
AdvSimd.LoadVector128((Double*)(pClsVar3)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr);
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(op1, op2, op3, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(op1, op2, op3, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1();
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(test._fld1, test._fld2, test._fld3, 1);
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__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
fixed (Vector128<Double>* pFld3 = &test._fld3)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(pFld1)),
AdvSimd.LoadVector128((Double*)(pFld2)),
AdvSimd.LoadVector128((Double*)(pFld3)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(_fld1, _fld2, _fld3, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(pFld1)),
AdvSimd.LoadVector128((Double*)(pFld2)),
AdvSimd.LoadVector128((Double*)(pFld3)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(test._fld1, test._fld2, test._fld3, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(&test._fld1)),
AdvSimd.LoadVector128((Double*)(&test._fld2)),
AdvSimd.LoadVector128((Double*)(&test._fld3)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Helpers.FusedMultiplySubtract(firstOp[i], secondOp[i], thirdOp[Imm])) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {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 FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1()
{
var test = new SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_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 SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1
{
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(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public Vector128<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1 testClass)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(_fld1, _fld2, _fld3, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1 testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(pFld1)),
AdvSimd.LoadVector128((Double*)(pFld2)),
AdvSimd.LoadVector128((Double*)(pFld3)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly byte Imm = 1;
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private static Vector128<Double> _clsVar3;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private Vector128<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
_clsVar1,
_clsVar2,
_clsVar3,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
fixed (Vector128<Double>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(pClsVar1)),
AdvSimd.LoadVector128((Double*)(pClsVar2)),
AdvSimd.LoadVector128((Double*)(pClsVar3)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr);
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(op1, op2, op3, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(op1, op2, op3, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1();
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(test._fld1, test._fld2, test._fld3, 1);
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__FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
fixed (Vector128<Double>* pFld3 = &test._fld3)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(pFld1)),
AdvSimd.LoadVector128((Double*)(pFld2)),
AdvSimd.LoadVector128((Double*)(pFld3)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(_fld1, _fld2, _fld3, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(pFld1)),
AdvSimd.LoadVector128((Double*)(pFld2)),
AdvSimd.LoadVector128((Double*)(pFld3)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(test._fld1, test._fld2, test._fld3, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar(
AdvSimd.LoadVector128((Double*)(&test._fld1)),
AdvSimd.LoadVector128((Double*)(&test._fld2)),
AdvSimd.LoadVector128((Double*)(&test._fld3)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Helpers.FusedMultiplySubtract(firstOp[i], secondOp[i], thirdOp[Imm])) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.FusedMultiplySubtractBySelectedScalar)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/coreclr/tools/Common/TypeSystem/Serialization/FieldDesc.Serialization.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
{
// Additional members of FieldDesc related to serialization.
partial class FieldDesc
{
/// <summary>
/// Gets a value indicating whether this field is not serialized.
/// specially.
/// </summary>
public virtual bool IsNotSerialized
{
get
{
return false;
}
}
}
partial class FieldForInstantiatedType
{
public override bool IsNotSerialized
{
get
{
return _fieldDef.IsNotSerialized;
}
}
}
}
| // 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
{
// Additional members of FieldDesc related to serialization.
partial class FieldDesc
{
/// <summary>
/// Gets a value indicating whether this field is not serialized.
/// specially.
/// </summary>
public virtual bool IsNotSerialized
{
get
{
return false;
}
}
}
partial class FieldForInstantiatedType
{
public override bool IsNotSerialized
{
get
{
return _fieldDef.IsNotSerialized;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
using Internal.Reflection.Core;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Execution.PayForPlayExperience;
using Internal.Reflection.Extensions.NonPortable;
using System.Reflection.Runtime.General;
using Debug = System.Diagnostics.Debug;
namespace Internal.Reflection.Execution
{
//==========================================================================================================================
// This class provides various services down to System.Private.CoreLib. (Though we forward most or all of them directly up to Reflection.Core.)
//==========================================================================================================================
internal sealed class ReflectionExecutionDomainCallbacksImplementation : ReflectionExecutionDomainCallbacks
{
public ReflectionExecutionDomainCallbacksImplementation(ExecutionDomain executionDomain, ExecutionEnvironmentImplementation executionEnvironment)
{
_executionDomain = executionDomain;
_executionEnvironment = executionEnvironment;
}
public sealed override Type GetType(string typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, string defaultAssemblyName)
{
LowLevelListWithIList<string> defaultAssemblies = new LowLevelListWithIList<string>();
if (defaultAssemblyName != null)
defaultAssemblies.Add(defaultAssemblyName);
defaultAssemblies.Add(AssemblyBinder.DefaultAssemblyNameForGetType);
return _executionDomain.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, defaultAssemblies);
}
public sealed override bool IsReflectionBlocked(RuntimeTypeHandle typeHandle)
{
return _executionEnvironment.IsReflectionBlocked(typeHandle);
}
//=======================================================================================
// This group of methods jointly service the Type.GetTypeFromHandle() path. The caller
// is responsible for analyzing the RuntimeTypeHandle to figure out which flavor to call.
//=======================================================================================
public sealed override Type GetNamedTypeForHandle(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition)
{
return _executionDomain.GetNamedTypeForHandle(typeHandle, isGenericTypeDefinition);
}
public sealed override Type GetArrayTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetArrayTypeForHandle(typeHandle);
}
public sealed override Type GetMdArrayTypeForHandle(RuntimeTypeHandle typeHandle, int rank)
{
return _executionDomain.GetMdArrayTypeForHandle(typeHandle, rank);
}
public sealed override Type GetPointerTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetPointerTypeForHandle(typeHandle);
}
public sealed override Type GetByRefTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetByRefTypeForHandle(typeHandle);
}
public sealed override Type GetConstructedGenericTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetConstructedGenericTypeForHandle(typeHandle);
}
//=======================================================================================
// MissingMetadataException support.
//=======================================================================================
public sealed override Exception CreateMissingMetadataException(Type pertainant)
{
return _executionDomain.CreateMissingMetadataException(pertainant);
}
// This is called from the ToString() helper of a RuntimeType that does not have full metadata.
// This helper makes a "best effort" to give the caller something better than "EETypePtr nnnnnnnnn".
public sealed override string GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle)
{
return Type.GetTypeFromHandle(runtimeTypeHandle).ToDisplayStringIfAvailable(null);
}
public sealed override MethodBase GetMethodBaseFromStartAddressIfAvailable(IntPtr methodStartAddress)
{
RuntimeTypeHandle declaringTypeHandle = default(RuntimeTypeHandle);
QMethodDefinition methodHandle;
if (!ReflectionExecution.ExecutionEnvironment.TryGetMethodForStartAddress(methodStartAddress,
ref declaringTypeHandle, out methodHandle))
{
return null;
}
// We don't use the type argument handles as we want the uninstantiated method info
return ReflectionCoreExecution.ExecutionDomain.GetMethod(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles: null);
}
public sealed override Assembly GetAssemblyForHandle(RuntimeTypeHandle typeHandle)
{
return Type.GetTypeFromHandle(typeHandle).Assembly;
}
public sealed override IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle runtimeTypeHandle)
{
return _executionEnvironment.TryGetStaticClassConstructionContext(runtimeTypeHandle);
}
/// <summary>
/// Retrieves the default value for a parameter of a method.
/// </summary>
/// <param name="defaultParametersContext">The default parameters context used to invoke the method,
/// this should identify the method in question. This is passed to the RuntimeAugments.CallDynamicInvokeMethod.</param>
/// <param name="thType">The type of the parameter to retrieve.</param>
/// <param name="argIndex">The index of the parameter on the method to retrieve.</param>
/// <param name="defaultValue">The default value of the parameter if available.</param>
/// <returns>true if the default parameter value is available, otherwise false.</returns>
public sealed override bool TryGetDefaultParameterValue(object defaultParametersContext, RuntimeTypeHandle thType, int argIndex, out object defaultValue)
{
defaultValue = null;
MethodBase methodBase = defaultParametersContext as MethodBase;
if (methodBase is null)
{
if (defaultParametersContext is Delegate)
{
methodBase = GetDelegateInvokeMethod(defaultParametersContext.GetType());
}
if (methodBase is null)
{
return false;
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "Delegates always generate metadata for the Invoke method")]
static MethodBase GetDelegateInvokeMethod(Type delegateType)
{
MethodInfo result = delegateType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Debug.Assert(result != null);
return result;
}
}
ParameterInfo parameterInfo = methodBase.GetParametersNoCopy()[argIndex];
if (!parameterInfo.HasDefaultValue)
{
// If the parameter is optional, with no default value and we're asked for its default value,
// it means the caller specified Missing.Value as the value for the parameter. In this case the behavior
// is defined as passing in the Missing.Value, regardless of the parameter type.
// If Missing.Value is convertible to the parameter type, it will just work, otherwise we will fail
// due to type mismatch.
if (parameterInfo.IsOptional)
{
defaultValue = Missing.Value;
return true;
}
return false;
}
defaultValue = parameterInfo.DefaultValue;
return true;
}
public sealed override RuntimeTypeHandle GetTypeHandleIfAvailable(Type type)
{
return _executionDomain.GetTypeHandleIfAvailable(type);
}
public sealed override bool SupportsReflection(Type type)
{
return _executionDomain.SupportsReflection(type);
}
public sealed override MethodInfo GetDelegateMethod(Delegate del)
{
return DelegateMethodInfoRetriever.GetDelegateMethodInfo(del);
}
public sealed override Exception GetExceptionForHR(int hr)
{
return Marshal.GetExceptionForHR(hr);
}
private ExecutionDomain _executionDomain;
private ExecutionEnvironmentImplementation _executionEnvironment;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
using Internal.Reflection.Core;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Execution.PayForPlayExperience;
using Internal.Reflection.Extensions.NonPortable;
using System.Reflection.Runtime.General;
using Debug = System.Diagnostics.Debug;
namespace Internal.Reflection.Execution
{
//==========================================================================================================================
// This class provides various services down to System.Private.CoreLib. (Though we forward most or all of them directly up to Reflection.Core.)
//==========================================================================================================================
internal sealed class ReflectionExecutionDomainCallbacksImplementation : ReflectionExecutionDomainCallbacks
{
public ReflectionExecutionDomainCallbacksImplementation(ExecutionDomain executionDomain, ExecutionEnvironmentImplementation executionEnvironment)
{
_executionDomain = executionDomain;
_executionEnvironment = executionEnvironment;
}
public sealed override Type GetType(string typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, string defaultAssemblyName)
{
LowLevelListWithIList<string> defaultAssemblies = new LowLevelListWithIList<string>();
if (defaultAssemblyName != null)
defaultAssemblies.Add(defaultAssemblyName);
defaultAssemblies.Add(AssemblyBinder.DefaultAssemblyNameForGetType);
return _executionDomain.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, defaultAssemblies);
}
public sealed override bool IsReflectionBlocked(RuntimeTypeHandle typeHandle)
{
return _executionEnvironment.IsReflectionBlocked(typeHandle);
}
//=======================================================================================
// This group of methods jointly service the Type.GetTypeFromHandle() path. The caller
// is responsible for analyzing the RuntimeTypeHandle to figure out which flavor to call.
//=======================================================================================
public sealed override Type GetNamedTypeForHandle(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition)
{
return _executionDomain.GetNamedTypeForHandle(typeHandle, isGenericTypeDefinition);
}
public sealed override Type GetArrayTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetArrayTypeForHandle(typeHandle);
}
public sealed override Type GetMdArrayTypeForHandle(RuntimeTypeHandle typeHandle, int rank)
{
return _executionDomain.GetMdArrayTypeForHandle(typeHandle, rank);
}
public sealed override Type GetPointerTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetPointerTypeForHandle(typeHandle);
}
public sealed override Type GetByRefTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetByRefTypeForHandle(typeHandle);
}
public sealed override Type GetConstructedGenericTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetConstructedGenericTypeForHandle(typeHandle);
}
//=======================================================================================
// MissingMetadataException support.
//=======================================================================================
public sealed override Exception CreateMissingMetadataException(Type pertainant)
{
return _executionDomain.CreateMissingMetadataException(pertainant);
}
// This is called from the ToString() helper of a RuntimeType that does not have full metadata.
// This helper makes a "best effort" to give the caller something better than "EETypePtr nnnnnnnnn".
public sealed override string GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle)
{
return Type.GetTypeFromHandle(runtimeTypeHandle).ToDisplayStringIfAvailable(null);
}
public sealed override MethodBase GetMethodBaseFromStartAddressIfAvailable(IntPtr methodStartAddress)
{
RuntimeTypeHandle declaringTypeHandle = default(RuntimeTypeHandle);
QMethodDefinition methodHandle;
if (!ReflectionExecution.ExecutionEnvironment.TryGetMethodForStartAddress(methodStartAddress,
ref declaringTypeHandle, out methodHandle))
{
return null;
}
// We don't use the type argument handles as we want the uninstantiated method info
return ReflectionCoreExecution.ExecutionDomain.GetMethod(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles: null);
}
public sealed override Assembly GetAssemblyForHandle(RuntimeTypeHandle typeHandle)
{
return Type.GetTypeFromHandle(typeHandle).Assembly;
}
public sealed override IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle runtimeTypeHandle)
{
return _executionEnvironment.TryGetStaticClassConstructionContext(runtimeTypeHandle);
}
/// <summary>
/// Retrieves the default value for a parameter of a method.
/// </summary>
/// <param name="defaultParametersContext">The default parameters context used to invoke the method,
/// this should identify the method in question. This is passed to the RuntimeAugments.CallDynamicInvokeMethod.</param>
/// <param name="thType">The type of the parameter to retrieve.</param>
/// <param name="argIndex">The index of the parameter on the method to retrieve.</param>
/// <param name="defaultValue">The default value of the parameter if available.</param>
/// <returns>true if the default parameter value is available, otherwise false.</returns>
public sealed override bool TryGetDefaultParameterValue(object defaultParametersContext, RuntimeTypeHandle thType, int argIndex, out object defaultValue)
{
defaultValue = null;
MethodBase methodBase = defaultParametersContext as MethodBase;
if (methodBase is null)
{
if (defaultParametersContext is Delegate)
{
methodBase = GetDelegateInvokeMethod(defaultParametersContext.GetType());
}
if (methodBase is null)
{
return false;
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "Delegates always generate metadata for the Invoke method")]
static MethodBase GetDelegateInvokeMethod(Type delegateType)
{
MethodInfo result = delegateType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Debug.Assert(result != null);
return result;
}
}
ParameterInfo parameterInfo = methodBase.GetParametersNoCopy()[argIndex];
if (!parameterInfo.HasDefaultValue)
{
// If the parameter is optional, with no default value and we're asked for its default value,
// it means the caller specified Missing.Value as the value for the parameter. In this case the behavior
// is defined as passing in the Missing.Value, regardless of the parameter type.
// If Missing.Value is convertible to the parameter type, it will just work, otherwise we will fail
// due to type mismatch.
if (parameterInfo.IsOptional)
{
defaultValue = Missing.Value;
return true;
}
return false;
}
defaultValue = parameterInfo.DefaultValue;
return true;
}
public sealed override RuntimeTypeHandle GetTypeHandleIfAvailable(Type type)
{
return _executionDomain.GetTypeHandleIfAvailable(type);
}
public sealed override bool SupportsReflection(Type type)
{
return _executionDomain.SupportsReflection(type);
}
public sealed override MethodInfo GetDelegateMethod(Delegate del)
{
return DelegateMethodInfoRetriever.GetDelegateMethodInfo(del);
}
public sealed override Exception GetExceptionForHR(int hr)
{
return Marshal.GetExceptionForHR(hr);
}
private ExecutionDomain _executionDomain;
private ExecutionEnvironmentImplementation _executionEnvironment;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/Regression/JitBlue/GitHub_11343/GitHub_11343.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 GitHub_11343
{
const int Passed = 100;
const int Failed = 0;
[MethodImpl(MethodImplOptions.NoInlining)]
static void Test()
{
string s = null;
// Should throw NullReferenceException even if the result is not used
int unused = s.Length;
}
static int Main()
{
try
{
Test();
return Failed;
}
catch (NullReferenceException)
{
return Passed;
}
}
}
| // 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 GitHub_11343
{
const int Passed = 100;
const int Failed = 0;
[MethodImpl(MethodImplOptions.NoInlining)]
static void Test()
{
string s = null;
// Should throw NullReferenceException even if the result is not used
int unused = s.Length;
}
static int Main()
{
try
{
Test();
return Failed;
}
catch (NullReferenceException)
{
return Passed;
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Security.Permissions/src/System/Security/Policy/UnionCodeGroup.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.Policy
{
[Obsolete("This type is obsolete. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public sealed partial class UnionCodeGroup : CodeGroup
{
public UnionCodeGroup(IMembershipCondition membershipCondition, PolicyStatement policy) : base(default(IMembershipCondition), default(PolicyStatement)) { }
public override string MergeLogic { get { return null; } }
public override CodeGroup Copy() { return default(CodeGroup); }
public override PolicyStatement Resolve(Evidence evidence) { return default(PolicyStatement); }
public override CodeGroup ResolveMatchingCodeGroups(Evidence evidence) { return default(CodeGroup); }
}
}
| // 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.Policy
{
[Obsolete("This type is obsolete. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public sealed partial class UnionCodeGroup : CodeGroup
{
public UnionCodeGroup(IMembershipCondition membershipCondition, PolicyStatement policy) : base(default(IMembershipCondition), default(PolicyStatement)) { }
public override string MergeLogic { get { return null; } }
public override CodeGroup Copy() { return default(CodeGroup); }
public override PolicyStatement Resolve(Evidence evidence) { return default(PolicyStatement); }
public override CodeGroup ResolveMatchingCodeGroups(Evidence evidence) { return default(CodeGroup); }
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/Common/src/Interop/Windows/Kernel32/Interop.DeleteVolumeMountPoint.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System.IO;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Kernel32
{
/// <summary>
/// WARNING: This method does not implicitly handle long paths. Use DeleteVolumeMountPoint.
/// </summary>
[GeneratedDllImport(Libraries.Kernel32, EntryPoint = "DeleteVolumeMountPointW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool DeleteVolumeMountPointPrivate(string mountPoint);
internal static bool DeleteVolumeMountPoint(string mountPoint)
{
mountPoint = PathInternal.EnsureExtendedPrefixIfNeeded(mountPoint);
return DeleteVolumeMountPointPrivate(mountPoint);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System.IO;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Kernel32
{
/// <summary>
/// WARNING: This method does not implicitly handle long paths. Use DeleteVolumeMountPoint.
/// </summary>
[GeneratedDllImport(Libraries.Kernel32, EntryPoint = "DeleteVolumeMountPointW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool DeleteVolumeMountPointPrivate(string mountPoint);
internal static bool DeleteVolumeMountPoint(string mountPoint)
{
mountPoint = PathInternal.EnsureExtendedPrefixIfNeeded(mountPoint);
return DeleteVolumeMountPointPrivate(mountPoint);
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class Pkcs9DocumentName : Pkcs9AttributeObject
{
//
// Constructors.
//
public Pkcs9DocumentName()
: base(Oids.DocumentNameOid.CopyOid())
{
}
public Pkcs9DocumentName(string documentName)
: base(Oids.DocumentNameOid.CopyOid(), Encode(documentName))
{
_lazyDocumentName = documentName;
}
public Pkcs9DocumentName(byte[] encodedDocumentName)
: base(Oids.DocumentNameOid.CopyOid(), encodedDocumentName)
{
}
//
// Public methods.
//
public string DocumentName
{
get
{
return _lazyDocumentName ?? (_lazyDocumentName = Decode(RawData));
}
}
public override void CopyFrom(AsnEncodedData asnEncodedData)
{
base.CopyFrom(asnEncodedData);
_lazyDocumentName = null;
}
//
// Private methods.
//
[return: NotNullIfNotNull("rawData")]
private static string? Decode(byte[]? rawData)
{
if (rawData == null)
return null;
byte[] octets = PkcsHelpers.DecodeOctetString(rawData);
return octets.OctetStringToUnicode();
}
private static byte[] Encode(string documentName!!)
{
byte[] octets = documentName.UnicodeToOctetString();
return PkcsHelpers.EncodeOctetString(octets);
}
private volatile string? _lazyDocumentName;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class Pkcs9DocumentName : Pkcs9AttributeObject
{
//
// Constructors.
//
public Pkcs9DocumentName()
: base(Oids.DocumentNameOid.CopyOid())
{
}
public Pkcs9DocumentName(string documentName)
: base(Oids.DocumentNameOid.CopyOid(), Encode(documentName))
{
_lazyDocumentName = documentName;
}
public Pkcs9DocumentName(byte[] encodedDocumentName)
: base(Oids.DocumentNameOid.CopyOid(), encodedDocumentName)
{
}
//
// Public methods.
//
public string DocumentName
{
get
{
return _lazyDocumentName ?? (_lazyDocumentName = Decode(RawData));
}
}
public override void CopyFrom(AsnEncodedData asnEncodedData)
{
base.CopyFrom(asnEncodedData);
_lazyDocumentName = null;
}
//
// Private methods.
//
[return: NotNullIfNotNull("rawData")]
private static string? Decode(byte[]? rawData)
{
if (rawData == null)
return null;
byte[] octets = PkcsHelpers.DecodeOctetString(rawData);
return octets.OctetStringToUnicode();
}
private static byte[] Encode(string documentName!!)
{
byte[] octets = documentName.UnicodeToOctetString();
return PkcsHelpers.EncodeOctetString(octets);
}
private volatile string? _lazyDocumentName;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageFormat.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
namespace System.Drawing.Imaging
{
/// <summary>
/// Specifies the format of the image.
/// </summary>
[TypeConverter(typeof(ImageFormatConverter))]
public sealed class ImageFormat
{
// Format IDs
// private static ImageFormat undefined = new ImageFormat(new Guid("{b96b3ca9-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_memoryBMP = new ImageFormat(new Guid("{b96b3caa-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_bmp = new ImageFormat(new Guid("{b96b3cab-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_emf = new ImageFormat(new Guid("{b96b3cac-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_wmf = new ImageFormat(new Guid("{b96b3cad-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_jpeg = new ImageFormat(new Guid("{b96b3cae-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_png = new ImageFormat(new Guid("{b96b3caf-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_gif = new ImageFormat(new Guid("{b96b3cb0-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_tiff = new ImageFormat(new Guid("{b96b3cb1-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_exif = new ImageFormat(new Guid("{b96b3cb2-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_icon = new ImageFormat(new Guid("{b96b3cb5-0728-11d3-9d7b-0000f81ef32e}"));
private Guid _guid;
/// <summary>
/// Initializes a new instance of the <see cref='ImageFormat'/> class with the specified GUID.
/// </summary>
public ImageFormat(Guid guid)
{
_guid = guid;
}
/// <summary>
/// Specifies a global unique identifier (GUID) that represents this <see cref='ImageFormat'/>.
/// </summary>
public Guid Guid
{
get { return _guid; }
}
/// <summary>
/// Specifies a memory bitmap image format.
/// </summary>
public static ImageFormat MemoryBmp
{
get { return s_memoryBMP; }
}
/// <summary>
/// Specifies the bitmap image format.
/// </summary>
public static ImageFormat Bmp
{
get { return s_bmp; }
}
/// <summary>
/// Specifies the enhanced Windows metafile image format.
/// </summary>
public static ImageFormat Emf
{
get { return s_emf; }
}
/// <summary>
/// Specifies the Windows metafile image format.
/// </summary>
public static ImageFormat Wmf
{
get { return s_wmf; }
}
/// <summary>
/// Specifies the GIF image format.
/// </summary>
public static ImageFormat Gif
{
get { return s_gif; }
}
/// <summary>
/// Specifies the JPEG image format.
/// </summary>
public static ImageFormat Jpeg
{
get { return s_jpeg; }
}
/// <summary>
/// Specifies the W3C PNG image format.
/// </summary>
public static ImageFormat Png
{
get { return s_png; }
}
/// <summary>
/// Specifies the Tag Image File Format (TIFF) image format.
/// </summary>
public static ImageFormat Tiff
{
get { return s_tiff; }
}
/// <summary>
/// Specifies the Exchangeable Image Format (EXIF).
/// </summary>
public static ImageFormat Exif
{
get { return s_exif; }
}
/// <summary>
/// Specifies the Windows icon image format.
/// </summary>
public static ImageFormat Icon
{
get { return s_icon; }
}
/// <summary>
/// Returns a value indicating whether the specified object is an <see cref='ImageFormat'/> equivalent to this
/// <see cref='ImageFormat'/>.
/// </summary>
public override bool Equals([NotNullWhen(true)] object? o)
{
ImageFormat? format = o as ImageFormat;
if (format == null)
return false;
return _guid == format._guid;
}
/// <summary>
/// Returns a hash code.
/// </summary>
public override int GetHashCode()
{
return _guid.GetHashCode();
}
// Find any random encoder which supports this format
internal ImageCodecInfo? FindEncoder()
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID.Equals(_guid))
return codec;
}
return null;
}
/// <summary>
/// Converts this <see cref='System.Drawing.Imaging.ImageFormat'/> to a human-readable string.
/// </summary>
public override string ToString()
{
if (this.Guid == s_memoryBMP.Guid) return "MemoryBMP";
if (this.Guid == s_bmp.Guid) return "Bmp";
if (this.Guid == s_emf.Guid) return "Emf";
if (this.Guid == s_wmf.Guid) return "Wmf";
if (this.Guid == s_gif.Guid) return "Gif";
if (this.Guid == s_jpeg.Guid) return "Jpeg";
if (this.Guid == s_png.Guid) return "Png";
if (this.Guid == s_tiff.Guid) return "Tiff";
if (this.Guid == s_exif.Guid) return "Exif";
if (this.Guid == s_icon.Guid) return "Icon";
return $"[ImageFormat: {_guid}]";
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
namespace System.Drawing.Imaging
{
/// <summary>
/// Specifies the format of the image.
/// </summary>
[TypeConverter(typeof(ImageFormatConverter))]
public sealed class ImageFormat
{
// Format IDs
// private static ImageFormat undefined = new ImageFormat(new Guid("{b96b3ca9-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_memoryBMP = new ImageFormat(new Guid("{b96b3caa-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_bmp = new ImageFormat(new Guid("{b96b3cab-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_emf = new ImageFormat(new Guid("{b96b3cac-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_wmf = new ImageFormat(new Guid("{b96b3cad-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_jpeg = new ImageFormat(new Guid("{b96b3cae-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_png = new ImageFormat(new Guid("{b96b3caf-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_gif = new ImageFormat(new Guid("{b96b3cb0-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_tiff = new ImageFormat(new Guid("{b96b3cb1-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_exif = new ImageFormat(new Guid("{b96b3cb2-0728-11d3-9d7b-0000f81ef32e}"));
private static readonly ImageFormat s_icon = new ImageFormat(new Guid("{b96b3cb5-0728-11d3-9d7b-0000f81ef32e}"));
private Guid _guid;
/// <summary>
/// Initializes a new instance of the <see cref='ImageFormat'/> class with the specified GUID.
/// </summary>
public ImageFormat(Guid guid)
{
_guid = guid;
}
/// <summary>
/// Specifies a global unique identifier (GUID) that represents this <see cref='ImageFormat'/>.
/// </summary>
public Guid Guid
{
get { return _guid; }
}
/// <summary>
/// Specifies a memory bitmap image format.
/// </summary>
public static ImageFormat MemoryBmp
{
get { return s_memoryBMP; }
}
/// <summary>
/// Specifies the bitmap image format.
/// </summary>
public static ImageFormat Bmp
{
get { return s_bmp; }
}
/// <summary>
/// Specifies the enhanced Windows metafile image format.
/// </summary>
public static ImageFormat Emf
{
get { return s_emf; }
}
/// <summary>
/// Specifies the Windows metafile image format.
/// </summary>
public static ImageFormat Wmf
{
get { return s_wmf; }
}
/// <summary>
/// Specifies the GIF image format.
/// </summary>
public static ImageFormat Gif
{
get { return s_gif; }
}
/// <summary>
/// Specifies the JPEG image format.
/// </summary>
public static ImageFormat Jpeg
{
get { return s_jpeg; }
}
/// <summary>
/// Specifies the W3C PNG image format.
/// </summary>
public static ImageFormat Png
{
get { return s_png; }
}
/// <summary>
/// Specifies the Tag Image File Format (TIFF) image format.
/// </summary>
public static ImageFormat Tiff
{
get { return s_tiff; }
}
/// <summary>
/// Specifies the Exchangeable Image Format (EXIF).
/// </summary>
public static ImageFormat Exif
{
get { return s_exif; }
}
/// <summary>
/// Specifies the Windows icon image format.
/// </summary>
public static ImageFormat Icon
{
get { return s_icon; }
}
/// <summary>
/// Returns a value indicating whether the specified object is an <see cref='ImageFormat'/> equivalent to this
/// <see cref='ImageFormat'/>.
/// </summary>
public override bool Equals([NotNullWhen(true)] object? o)
{
ImageFormat? format = o as ImageFormat;
if (format == null)
return false;
return _guid == format._guid;
}
/// <summary>
/// Returns a hash code.
/// </summary>
public override int GetHashCode()
{
return _guid.GetHashCode();
}
// Find any random encoder which supports this format
internal ImageCodecInfo? FindEncoder()
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID.Equals(_guid))
return codec;
}
return null;
}
/// <summary>
/// Converts this <see cref='System.Drawing.Imaging.ImageFormat'/> to a human-readable string.
/// </summary>
public override string ToString()
{
if (this.Guid == s_memoryBMP.Guid) return "MemoryBMP";
if (this.Guid == s_bmp.Guid) return "Bmp";
if (this.Guid == s_emf.Guid) return "Emf";
if (this.Guid == s_wmf.Guid) return "Wmf";
if (this.Guid == s_gif.Guid) return "Gif";
if (this.Guid == s_jpeg.Guid) return "Jpeg";
if (this.Guid == s_png.Guid) return "Png";
if (this.Guid == s_tiff.Guid) return "Tiff";
if (this.Guid == s_exif.Guid) return "Exif";
if (this.Guid == s_icon.Guid) return "Icon";
return $"[ImageFormat: {_guid}]";
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/TCDefaultWriterSettingsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using OLEDB.Test.ModuleCore;
using XmlCoreTest.Common;
using Xunit;
namespace System.Xml.Tests
{
public class TCDefaultWriterSettings
{
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_1(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.Encoding, Encoding.UTF8, "Incorrect default value of Encoding");
XmlWriter w = utils.CreateWriter();
switch (utils.WriterType)
{
case WriterType.UTF8Writer:
case WriterType.UTF8WriterIndent:
case WriterType.CharCheckingWriter:
case WriterType.WrappedWriter:
CError.Compare(w.Settings.Encoding.WebName, "utf-8", "Incorrect default value of Encoding");
break;
case WriterType.UnicodeWriter:
case WriterType.UnicodeWriterIndent:
CError.Compare(w.Settings.Encoding.WebName, "utf-16", "Incorrect default value of Encoding");
break;
}
w.Dispose();
return;
}
[Fact]
public void default_2()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.OmitXmlDeclaration, false, "Incorrect default value of OmitXmlDeclaration");
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_3(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.NewLineHandling, NewLineHandling.Replace, "Incorrect default value of NewLineHandling");
XmlWriter w = utils.CreateWriter();
switch (utils.WriterType)
{
case WriterType.UTF8Writer:
case WriterType.UnicodeWriter:
CError.Compare(w.Settings.NewLineHandling, NewLineHandling.Replace, "Incorrect default value of NewLineHandling");
break;
}
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_4(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.NewLineChars, Environment.NewLine, "Incorrect default value of NewLineChars");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.NewLineChars, Environment.NewLine, "Incorrect default value of NewLineChars");
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_5(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.Indent, false, "Incorrect default value of wSettings.Indent");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.Indent, utils.IsIndent(), "Incorrect default value of w.Settings.Indent");
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_6(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.IndentChars, " ", "Incorrect default value of IndentChars");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.IndentChars, " ", "Incorrect default value of IndentChars");
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_7(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.NewLineOnAttributes, false, "Incorrect default value of NewLineOnAttributes");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.NewLineOnAttributes, false, "Incorrect default value of NewLineOnAttributes");
return;
}
[Fact]
public void default_8()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.CloseOutput, false, "Incorrect default value of CloseOutput");
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_10(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.CheckCharacters, true, "Incorrect default value of CheckCharacters");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.CheckCharacters, true, "Incorrect default value of CheckCharacters");
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_11(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.ConformanceLevel, ConformanceLevel.Document, "Incorrect default value of ConformanceLevel");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Incorrect default value of ConformanceLevel");
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_13(XmlWriterUtils utils)
{
XmlWriterSettings ws = new XmlWriterSettings();
CError.Equals(ws.WriteEndDocumentOnClose, true, "Incorrect default value of WriteEndDocumentOnClose");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.WriteEndDocumentOnClose, true, "Incorrect default value of WriteEndDocumentOnClose");
w.Dispose();
return;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using OLEDB.Test.ModuleCore;
using XmlCoreTest.Common;
using Xunit;
namespace System.Xml.Tests
{
public class TCDefaultWriterSettings
{
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_1(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.Encoding, Encoding.UTF8, "Incorrect default value of Encoding");
XmlWriter w = utils.CreateWriter();
switch (utils.WriterType)
{
case WriterType.UTF8Writer:
case WriterType.UTF8WriterIndent:
case WriterType.CharCheckingWriter:
case WriterType.WrappedWriter:
CError.Compare(w.Settings.Encoding.WebName, "utf-8", "Incorrect default value of Encoding");
break;
case WriterType.UnicodeWriter:
case WriterType.UnicodeWriterIndent:
CError.Compare(w.Settings.Encoding.WebName, "utf-16", "Incorrect default value of Encoding");
break;
}
w.Dispose();
return;
}
[Fact]
public void default_2()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.OmitXmlDeclaration, false, "Incorrect default value of OmitXmlDeclaration");
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_3(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.NewLineHandling, NewLineHandling.Replace, "Incorrect default value of NewLineHandling");
XmlWriter w = utils.CreateWriter();
switch (utils.WriterType)
{
case WriterType.UTF8Writer:
case WriterType.UnicodeWriter:
CError.Compare(w.Settings.NewLineHandling, NewLineHandling.Replace, "Incorrect default value of NewLineHandling");
break;
}
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_4(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.NewLineChars, Environment.NewLine, "Incorrect default value of NewLineChars");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.NewLineChars, Environment.NewLine, "Incorrect default value of NewLineChars");
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_5(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.Indent, false, "Incorrect default value of wSettings.Indent");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.Indent, utils.IsIndent(), "Incorrect default value of w.Settings.Indent");
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_6(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.IndentChars, " ", "Incorrect default value of IndentChars");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.IndentChars, " ", "Incorrect default value of IndentChars");
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_7(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.NewLineOnAttributes, false, "Incorrect default value of NewLineOnAttributes");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.NewLineOnAttributes, false, "Incorrect default value of NewLineOnAttributes");
return;
}
[Fact]
public void default_8()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.CloseOutput, false, "Incorrect default value of CloseOutput");
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_10(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.CheckCharacters, true, "Incorrect default value of CheckCharacters");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.CheckCharacters, true, "Incorrect default value of CheckCharacters");
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_11(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Equals(wSettings.ConformanceLevel, ConformanceLevel.Document, "Incorrect default value of ConformanceLevel");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Incorrect default value of ConformanceLevel");
w.Dispose();
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void default_13(XmlWriterUtils utils)
{
XmlWriterSettings ws = new XmlWriterSettings();
CError.Equals(ws.WriteEndDocumentOnClose, true, "Incorrect default value of WriteEndDocumentOnClose");
XmlWriter w = utils.CreateWriter();
CError.Equals(w.Settings.WriteEndDocumentOnClose, true, "Incorrect default value of WriteEndDocumentOnClose");
w.Dispose();
return;
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Collections.Concurrent/tests/ConcurrentDictionary/ConcurrentDictionary.NonGeneric.Tests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Tests;
using System.Collections.Generic;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentDictionary_NonGeneric_Tests : IDictionary_NonGeneric_Tests
{
#region IDictionary<TKey, TValue Helper Methods
protected override IDictionary NonGenericIDictionaryFactory()
{
return new ConcurrentDictionary<string, string>();
}
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected override object CreateTKey(int seed)
{
int stringLength = seed % 10 + 5;
Random rand = new Random(seed);
byte[] bytes = new byte[stringLength];
rand.NextBytes(bytes);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected override object CreateTValue(int seed) => CreateTKey(seed);
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>();
protected override bool Enumerator_Current_UndefinedOperation_Throws => false;
protected override bool IDictionary_NonGeneric_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection => false;
protected override bool ICollection_NonGeneric_SupportsSyncRoot => false;
protected override bool IDictionary_NonGeneric_Keys_Values_ParentDictionaryModifiedInvalidates => false;
protected override bool ResetImplemented => true;
protected override bool IDictionary_NonGeneric_Keys_Values_Enumeration_ResetImplemented => true;
protected override bool SupportsSerialization => false;
protected override Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(ArrayTypeMismatchException);
#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.Tests;
using System.Collections.Generic;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentDictionary_NonGeneric_Tests : IDictionary_NonGeneric_Tests
{
#region IDictionary<TKey, TValue Helper Methods
protected override IDictionary NonGenericIDictionaryFactory()
{
return new ConcurrentDictionary<string, string>();
}
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected override object CreateTKey(int seed)
{
int stringLength = seed % 10 + 5;
Random rand = new Random(seed);
byte[] bytes = new byte[stringLength];
rand.NextBytes(bytes);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected override object CreateTValue(int seed) => CreateTKey(seed);
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>();
protected override bool Enumerator_Current_UndefinedOperation_Throws => false;
protected override bool IDictionary_NonGeneric_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection => false;
protected override bool ICollection_NonGeneric_SupportsSyncRoot => false;
protected override bool IDictionary_NonGeneric_Keys_Values_ParentDictionaryModifiedInvalidates => false;
protected override bool ResetImplemented => true;
protected override bool IDictionary_NonGeneric_Keys_Values_Enumeration_ResetImplemented => true;
protected override bool SupportsSerialization => false;
protected override Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(ArrayTypeMismatchException);
#endregion
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Data.OleDb/src/System/Data/Common/NameValuePair.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
namespace System.Data.Common
{
internal sealed class NameValuePair
{
private readonly string _name;
private readonly string? _value;
private readonly int _length;
private NameValuePair? _next;
internal NameValuePair(string name, string? value, int length)
{
Debug.Assert(!string.IsNullOrEmpty(name), "empty keyname");
_name = name;
_value = value;
_length = length;
}
internal int Length
{
get
{
Debug.Assert(0 < _length, "NameValuePair zero Length usage");
return _length;
}
}
internal string Name => _name;
internal string? Value => _value;
internal NameValuePair? Next
{
get { return _next; }
set
{
if ((null != _next) || (null == value))
{
throw ADP.InternalError(ADP.InternalErrorCode.NameValuePairNext);
}
_next = 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.Diagnostics;
namespace System.Data.Common
{
internal sealed class NameValuePair
{
private readonly string _name;
private readonly string? _value;
private readonly int _length;
private NameValuePair? _next;
internal NameValuePair(string name, string? value, int length)
{
Debug.Assert(!string.IsNullOrEmpty(name), "empty keyname");
_name = name;
_value = value;
_length = length;
}
internal int Length
{
get
{
Debug.Assert(0 < _length, "NameValuePair zero Length usage");
return _length;
}
}
internal string Name => _name;
internal string? Value => _value;
internal NameValuePair? Next
{
get { return _next; }
set
{
if ((null != _next) || (null == value))
{
throw ADP.InternalError(ADP.InternalErrorCode.NameValuePairNext);
}
_next = value;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ContinuationTests.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.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class ContinuationTests
{
private static readonly (Func<string, string>, Func<string, int>, int)[] s_payloadTweaks = new (Func<string, string>, Func<string, int>, int)[]
{
(payload => payload, payload => -1, 0),
(payload => payload.Replace("null", "nullX"), payload => payload.IndexOf("nullX"), "null".Length),
(payload => payload.Replace("true", "trueX"), payload => payload.IndexOf("trueX"), "true".Length),
(payload => payload.Replace("false", "falseX"), payload => payload.IndexOf("falseX"), "false".Length),
(payload => payload.Replace("E+17", "E+-17"), payload => payload.IndexOf("E+-17"), "E+".Length)
};
private static IEnumerable<(ITestObject, INestedObject)> TestObjects
=> new (ITestObject, INestedObject)[]
{
(new TestClass<NestedClass>(), new NestedClass()),
(new TestClass<NestedValueType>(), new NestedValueType()),
(new TestValueType<NestedClass>(), new NestedClass()),
(new TestValueType<NestedValueType>(), new NestedValueType()),
(new TestClass<NestedClassWithParamCtor>(), new NestedClassWithParamCtor(null)),
(new DictionaryTestClass<NestedClass>(), new NestedClass()),
};
private static IEnumerable<bool> IgnoreNullValues
=> new[] { true, false };
private static IEnumerable<bool> WriteIndented
=> new[] { true, false };
public static IEnumerable<object[]> TestData(bool enumeratePayloadTweaks)
{
// The serialized json gets padded with leading ' ' chars. The length of the
// incrementing paddings, leads to continuations at every position of the payload.
// The complete strings (padding + payload) are then passed to the test method.
// <------min-padding------>[{--payload--}] min-padding = buffer - payload + 1
// <-----------2^n byte buffer----------->
// <-------------max-padding------------>[{--payload--}] max-padding = buffer - 1
foreach ((ITestObject TestObject, INestedObject Nested) in TestObjects.Take(enumeratePayloadTweaks ? 1 : TestObjects.Count()))
{
Type testObjectType = TestObject.GetType();
TestObject.Initialize(Nested);
foreach (bool writeIndented in WriteIndented)
{
string payload = JsonSerializer.Serialize(TestObject, testObjectType, new JsonSerializerOptions { WriteIndented = writeIndented });
foreach ((Func<string, string> Tweak, Func<string, int> Position, int Offset) tweak in enumeratePayloadTweaks ? s_payloadTweaks.Skip(1) : s_payloadTweaks.Take(1))
{
string tweaked = tweak.Tweak(payload);
// Wrap the payload inside an array to have something to read before/after.
tweaked = '[' + tweaked + ']';
Type arrayType = Type.GetType(testObjectType.FullName + "[]");
(int Line, int Col) failurePosition = GetExpectedFailure(tweaked, tweak.Position(tweaked), tweak.Offset);
// Determine the DefaultBufferSize that is required to contain the complete json.
int bufferSize = 16;
while (tweaked.Length > bufferSize)
{
bufferSize *= 2;
}
int minPaddingLength = bufferSize - tweaked.Length + 1;
int maxPaddingLength = bufferSize - 1;
foreach (int length in Enumerable.Range(minPaddingLength, maxPaddingLength - minPaddingLength + 1))
{
(int Line, int Col) paddedFailurePosition = failurePosition;
if (failurePosition != default && failurePosition.Line == 0)
paddedFailurePosition = (failurePosition.Line, failurePosition.Col + length);
foreach (bool ignoreNull in IgnoreNullValues)
{
yield return new object[]
{
new string(' ', length) + tweaked,
bufferSize,
arrayType,
ignoreNull,
paddedFailurePosition
};
}
}
}
}
}
static (int Line, int Col) GetExpectedFailure(string payload, int position, int offset)
{
if (position < 0)
return default;
position += offset;
ReadOnlySpan<byte> utf8 = Encoding.UTF8.GetBytes(payload);
utf8 = utf8.Slice(0, position);
int positionInLine = position;
int lastNewLine;
int newLineCount = 0;
while ((lastNewLine = utf8.LastIndexOf((byte)'\n')) >= 0)
{
if (newLineCount == 0)
positionInLine -= lastNewLine + 1;
newLineCount++;
utf8 = utf8.Slice(0, lastNewLine);
}
return (newLineCount, positionInLine);
}
}
[Theory]
[MemberData(nameof(TestData), /* enumeratePayloadTweaks: */ false)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)]
public static async Task ShouldWorkAtAnyPosition_Stream(
string json,
int bufferSize,
Type type,
bool ignoreNullValues,
(int Line, int Column) expectedFailure)
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
{
var readOptions = new JsonSerializerOptions
{
DefaultBufferSize = bufferSize,
IgnoreNullValues = ignoreNullValues,
};
var array = (ITestObject[])await JsonSerializer.DeserializeAsync(stream, type, readOptions);
Assert.NotNull(array);
Assert.Equal(1, array.Length);
array[0].Verify();
}
Assert.Equal(default, expectedFailure);
}
[Theory]
[MemberData(nameof(TestData), /* enumeratePayloadTweaks: */ true)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)]
public static async Task InvalidJsonShouldFailAtAnyPosition_Stream(
string json,
int bufferSize,
Type type,
bool ignoreNullValues,
(int Line, int Column) expectedFailure)
{
if (expectedFailure == default)
{
// The tweak didn't find something to tweak in the payload
return;
}
var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
{
var readOptions = new JsonSerializerOptions
{
DefaultBufferSize = bufferSize,
IgnoreNullValues = ignoreNullValues,
};
JsonException ex = await Assert.ThrowsAsync<JsonException>(async () => await JsonSerializer.DeserializeAsync(stream, type, readOptions));
Assert.Equal(expectedFailure.Line, ex.LineNumber);
Assert.Equal(expectedFailure.Column, ex.BytePositionInLine);
}
}
[Theory]
[MemberData(nameof(TestData), /* enumeratePayloadTweaks: */ false)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)]
[SkipOnCoreClr("https://github.com/dotnet/runtime/issues/45464", ~RuntimeConfiguration.Release)]
public static void ShouldWorkAtAnyPosition_Sequence(
string json,
int bufferSize,
Type type,
bool ignoreNullValues,
(int Line, int Column) expectedFailure)
{
var readOptions = new JsonSerializerOptions { IgnoreNullValues = ignoreNullValues, };
var chunk = new Chunk(json, bufferSize);
var sequence = new ReadOnlySequence<byte>(chunk, 0, chunk.Next, chunk.Next.Memory.Length);
var reader = new Utf8JsonReader(sequence);
var array = (ITestObject[])JsonSerializer.Deserialize(ref reader, type, readOptions);
Assert.NotNull(array);
Assert.Equal(1, array.Length);
array[0].Verify();
Assert.Equal(default, expectedFailure);
}
[Theory]
[MemberData(nameof(TestData), /* enumeratePayloadTweaks: */ true)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)]
public static void InvalidJsonShouldFailAtAnyPosition_Sequence(
string json,
int bufferSize,
Type type,
bool ignoreNullValues,
(int Line, int Column) expectedFailure)
{
if (expectedFailure == default)
{
// The tweak didn't find something to tweak in the payload
return;
}
var readOptions = new JsonSerializerOptions { IgnoreNullValues = ignoreNullValues, };
var chunk = new Chunk(json, bufferSize);
var sequence = new ReadOnlySequence<byte>(chunk, 0, chunk.Next, chunk.Next.Memory.Length);
JsonException ex = Assert.Throws<JsonException>(() =>
{
var reader = new Utf8JsonReader(sequence);
JsonSerializer.Deserialize(ref reader, type, readOptions);
});
Assert.Equal(expectedFailure.Line, ex.LineNumber);
Assert.Equal(expectedFailure.Column, ex.BytePositionInLine);
}
private class Chunk : ReadOnlySequenceSegment<byte>
{
public Chunk(string json, int firstSegmentLength)
{
Memory<byte> bytes = Encoding.UTF8.GetBytes(json);
Memory = bytes.Slice(0, firstSegmentLength);
RunningIndex = 0;
Next = new Chunk()
{
Memory = bytes.Slice(firstSegmentLength),
RunningIndex = firstSegmentLength,
Next = null,
};
}
private Chunk()
{ }
}
private interface ITestObject
{
void Initialize(INestedObject nested);
void Verify();
}
private interface INestedObject
{
void Initialize();
void Verify();
}
private class TestClass<TNested> : ITestObject where TNested : INestedObject
{
public string A { get; set; }
public string B { get; set; }
public int C { get; set; }
public int? D { get; set; }
public float E { get; set; }
public bool G { get; set; }
public int[] I { get; set; }
public TNested J { get; set; }
void ITestObject.Initialize(INestedObject nested)
{
A = "Hello";
B = null;
C = 42;
D = null;
E = 3.14e+17f;
G = true;
I = new int[] { 42, 17 };
nested.Initialize();
J = (TNested)nested;
}
void ITestObject.Verify()
{
Assert.Equal("Hello", A);
Assert.Null(B);
Assert.Equal(42, C);
Assert.Null(D);
Assert.Equal(3.14e17f, E);
Assert.True(G);
Assert.NotNull(I);
Assert.True(I.SequenceEqual(new[] { 42, 17 }));
Assert.NotNull(J);
J.Verify();
}
}
private class TestValueType<TNested> : ITestObject where TNested : INestedObject
{
public string A { get; set; }
public string B { get; set; }
public int C { get; set; }
public int? D { get; set; }
public float E { get; set; }
public bool G { get; set; }
public int[] I { get; set; }
public TNested J { get; set; }
void ITestObject.Initialize(INestedObject nested)
{
A = "Hello";
B = null;
C = 42;
D = null;
E = 3.14e+17f;
G = true;
I = new int[] { 42, 17 };
nested.Initialize();
J = (TNested)nested;
}
void ITestObject.Verify()
{
Assert.Equal("Hello", A);
Assert.Null(B);
Assert.Equal(42, C);
Assert.Null(D);
Assert.Equal(3.14e17f, E);
Assert.True(G);
Assert.NotNull(I);
Assert.True(I.SequenceEqual(new[] { 42, 17 }));
Assert.NotNull(J);
J.Verify();
}
}
private class NestedClass : INestedObject
{
public string A { get; set; }
public int B { get; set; }
void INestedObject.Initialize()
{
A = null;
B = 7;
}
void INestedObject.Verify()
{
Assert.Null(A);
Assert.Equal(7, B);
}
}
private struct NestedValueType : INestedObject
{
public string A { get; set; }
public int B { get; set; }
void INestedObject.Initialize()
{
A = null;
B = 7;
}
void INestedObject.Verify()
{
Assert.Null(A);
Assert.Equal(7, B);
}
}
private class NestedClassWithParamCtor : NestedClass
{
public NestedClassWithParamCtor(string a)
=> A = a;
}
private class DictionaryTestClass<TNested> : ITestObject where TNested : INestedObject
{
public Dictionary<string, TNested> A { get; set; }
void ITestObject.Initialize(INestedObject nested)
{
nested.Initialize();
A = new() { { "a", (TNested)nested }, { "b", (TNested)nested } };
}
void ITestObject.Verify()
{
Assert.NotNull(A);
Assert.Collection(A,
kv =>
{
Assert.Equal("a", kv.Key);
kv.Value.Verify();
},
kv =>
{
Assert.Equal("b", kv.Key);
kv.Value.Verify();
});
}
}
}
}
| // 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.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class ContinuationTests
{
private static readonly (Func<string, string>, Func<string, int>, int)[] s_payloadTweaks = new (Func<string, string>, Func<string, int>, int)[]
{
(payload => payload, payload => -1, 0),
(payload => payload.Replace("null", "nullX"), payload => payload.IndexOf("nullX"), "null".Length),
(payload => payload.Replace("true", "trueX"), payload => payload.IndexOf("trueX"), "true".Length),
(payload => payload.Replace("false", "falseX"), payload => payload.IndexOf("falseX"), "false".Length),
(payload => payload.Replace("E+17", "E+-17"), payload => payload.IndexOf("E+-17"), "E+".Length)
};
private static IEnumerable<(ITestObject, INestedObject)> TestObjects
=> new (ITestObject, INestedObject)[]
{
(new TestClass<NestedClass>(), new NestedClass()),
(new TestClass<NestedValueType>(), new NestedValueType()),
(new TestValueType<NestedClass>(), new NestedClass()),
(new TestValueType<NestedValueType>(), new NestedValueType()),
(new TestClass<NestedClassWithParamCtor>(), new NestedClassWithParamCtor(null)),
(new DictionaryTestClass<NestedClass>(), new NestedClass()),
};
private static IEnumerable<bool> IgnoreNullValues
=> new[] { true, false };
private static IEnumerable<bool> WriteIndented
=> new[] { true, false };
public static IEnumerable<object[]> TestData(bool enumeratePayloadTweaks)
{
// The serialized json gets padded with leading ' ' chars. The length of the
// incrementing paddings, leads to continuations at every position of the payload.
// The complete strings (padding + payload) are then passed to the test method.
// <------min-padding------>[{--payload--}] min-padding = buffer - payload + 1
// <-----------2^n byte buffer----------->
// <-------------max-padding------------>[{--payload--}] max-padding = buffer - 1
foreach ((ITestObject TestObject, INestedObject Nested) in TestObjects.Take(enumeratePayloadTweaks ? 1 : TestObjects.Count()))
{
Type testObjectType = TestObject.GetType();
TestObject.Initialize(Nested);
foreach (bool writeIndented in WriteIndented)
{
string payload = JsonSerializer.Serialize(TestObject, testObjectType, new JsonSerializerOptions { WriteIndented = writeIndented });
foreach ((Func<string, string> Tweak, Func<string, int> Position, int Offset) tweak in enumeratePayloadTweaks ? s_payloadTweaks.Skip(1) : s_payloadTweaks.Take(1))
{
string tweaked = tweak.Tweak(payload);
// Wrap the payload inside an array to have something to read before/after.
tweaked = '[' + tweaked + ']';
Type arrayType = Type.GetType(testObjectType.FullName + "[]");
(int Line, int Col) failurePosition = GetExpectedFailure(tweaked, tweak.Position(tweaked), tweak.Offset);
// Determine the DefaultBufferSize that is required to contain the complete json.
int bufferSize = 16;
while (tweaked.Length > bufferSize)
{
bufferSize *= 2;
}
int minPaddingLength = bufferSize - tweaked.Length + 1;
int maxPaddingLength = bufferSize - 1;
foreach (int length in Enumerable.Range(minPaddingLength, maxPaddingLength - minPaddingLength + 1))
{
(int Line, int Col) paddedFailurePosition = failurePosition;
if (failurePosition != default && failurePosition.Line == 0)
paddedFailurePosition = (failurePosition.Line, failurePosition.Col + length);
foreach (bool ignoreNull in IgnoreNullValues)
{
yield return new object[]
{
new string(' ', length) + tweaked,
bufferSize,
arrayType,
ignoreNull,
paddedFailurePosition
};
}
}
}
}
}
static (int Line, int Col) GetExpectedFailure(string payload, int position, int offset)
{
if (position < 0)
return default;
position += offset;
ReadOnlySpan<byte> utf8 = Encoding.UTF8.GetBytes(payload);
utf8 = utf8.Slice(0, position);
int positionInLine = position;
int lastNewLine;
int newLineCount = 0;
while ((lastNewLine = utf8.LastIndexOf((byte)'\n')) >= 0)
{
if (newLineCount == 0)
positionInLine -= lastNewLine + 1;
newLineCount++;
utf8 = utf8.Slice(0, lastNewLine);
}
return (newLineCount, positionInLine);
}
}
[Theory]
[MemberData(nameof(TestData), /* enumeratePayloadTweaks: */ false)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)]
public static async Task ShouldWorkAtAnyPosition_Stream(
string json,
int bufferSize,
Type type,
bool ignoreNullValues,
(int Line, int Column) expectedFailure)
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
{
var readOptions = new JsonSerializerOptions
{
DefaultBufferSize = bufferSize,
IgnoreNullValues = ignoreNullValues,
};
var array = (ITestObject[])await JsonSerializer.DeserializeAsync(stream, type, readOptions);
Assert.NotNull(array);
Assert.Equal(1, array.Length);
array[0].Verify();
}
Assert.Equal(default, expectedFailure);
}
[Theory]
[MemberData(nameof(TestData), /* enumeratePayloadTweaks: */ true)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)]
public static async Task InvalidJsonShouldFailAtAnyPosition_Stream(
string json,
int bufferSize,
Type type,
bool ignoreNullValues,
(int Line, int Column) expectedFailure)
{
if (expectedFailure == default)
{
// The tweak didn't find something to tweak in the payload
return;
}
var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
{
var readOptions = new JsonSerializerOptions
{
DefaultBufferSize = bufferSize,
IgnoreNullValues = ignoreNullValues,
};
JsonException ex = await Assert.ThrowsAsync<JsonException>(async () => await JsonSerializer.DeserializeAsync(stream, type, readOptions));
Assert.Equal(expectedFailure.Line, ex.LineNumber);
Assert.Equal(expectedFailure.Column, ex.BytePositionInLine);
}
}
[Theory]
[MemberData(nameof(TestData), /* enumeratePayloadTweaks: */ false)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)]
[SkipOnCoreClr("https://github.com/dotnet/runtime/issues/45464", ~RuntimeConfiguration.Release)]
public static void ShouldWorkAtAnyPosition_Sequence(
string json,
int bufferSize,
Type type,
bool ignoreNullValues,
(int Line, int Column) expectedFailure)
{
var readOptions = new JsonSerializerOptions { IgnoreNullValues = ignoreNullValues, };
var chunk = new Chunk(json, bufferSize);
var sequence = new ReadOnlySequence<byte>(chunk, 0, chunk.Next, chunk.Next.Memory.Length);
var reader = new Utf8JsonReader(sequence);
var array = (ITestObject[])JsonSerializer.Deserialize(ref reader, type, readOptions);
Assert.NotNull(array);
Assert.Equal(1, array.Length);
array[0].Verify();
Assert.Equal(default, expectedFailure);
}
[Theory]
[MemberData(nameof(TestData), /* enumeratePayloadTweaks: */ true)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)]
public static void InvalidJsonShouldFailAtAnyPosition_Sequence(
string json,
int bufferSize,
Type type,
bool ignoreNullValues,
(int Line, int Column) expectedFailure)
{
if (expectedFailure == default)
{
// The tweak didn't find something to tweak in the payload
return;
}
var readOptions = new JsonSerializerOptions { IgnoreNullValues = ignoreNullValues, };
var chunk = new Chunk(json, bufferSize);
var sequence = new ReadOnlySequence<byte>(chunk, 0, chunk.Next, chunk.Next.Memory.Length);
JsonException ex = Assert.Throws<JsonException>(() =>
{
var reader = new Utf8JsonReader(sequence);
JsonSerializer.Deserialize(ref reader, type, readOptions);
});
Assert.Equal(expectedFailure.Line, ex.LineNumber);
Assert.Equal(expectedFailure.Column, ex.BytePositionInLine);
}
private class Chunk : ReadOnlySequenceSegment<byte>
{
public Chunk(string json, int firstSegmentLength)
{
Memory<byte> bytes = Encoding.UTF8.GetBytes(json);
Memory = bytes.Slice(0, firstSegmentLength);
RunningIndex = 0;
Next = new Chunk()
{
Memory = bytes.Slice(firstSegmentLength),
RunningIndex = firstSegmentLength,
Next = null,
};
}
private Chunk()
{ }
}
private interface ITestObject
{
void Initialize(INestedObject nested);
void Verify();
}
private interface INestedObject
{
void Initialize();
void Verify();
}
private class TestClass<TNested> : ITestObject where TNested : INestedObject
{
public string A { get; set; }
public string B { get; set; }
public int C { get; set; }
public int? D { get; set; }
public float E { get; set; }
public bool G { get; set; }
public int[] I { get; set; }
public TNested J { get; set; }
void ITestObject.Initialize(INestedObject nested)
{
A = "Hello";
B = null;
C = 42;
D = null;
E = 3.14e+17f;
G = true;
I = new int[] { 42, 17 };
nested.Initialize();
J = (TNested)nested;
}
void ITestObject.Verify()
{
Assert.Equal("Hello", A);
Assert.Null(B);
Assert.Equal(42, C);
Assert.Null(D);
Assert.Equal(3.14e17f, E);
Assert.True(G);
Assert.NotNull(I);
Assert.True(I.SequenceEqual(new[] { 42, 17 }));
Assert.NotNull(J);
J.Verify();
}
}
private class TestValueType<TNested> : ITestObject where TNested : INestedObject
{
public string A { get; set; }
public string B { get; set; }
public int C { get; set; }
public int? D { get; set; }
public float E { get; set; }
public bool G { get; set; }
public int[] I { get; set; }
public TNested J { get; set; }
void ITestObject.Initialize(INestedObject nested)
{
A = "Hello";
B = null;
C = 42;
D = null;
E = 3.14e+17f;
G = true;
I = new int[] { 42, 17 };
nested.Initialize();
J = (TNested)nested;
}
void ITestObject.Verify()
{
Assert.Equal("Hello", A);
Assert.Null(B);
Assert.Equal(42, C);
Assert.Null(D);
Assert.Equal(3.14e17f, E);
Assert.True(G);
Assert.NotNull(I);
Assert.True(I.SequenceEqual(new[] { 42, 17 }));
Assert.NotNull(J);
J.Verify();
}
}
private class NestedClass : INestedObject
{
public string A { get; set; }
public int B { get; set; }
void INestedObject.Initialize()
{
A = null;
B = 7;
}
void INestedObject.Verify()
{
Assert.Null(A);
Assert.Equal(7, B);
}
}
private struct NestedValueType : INestedObject
{
public string A { get; set; }
public int B { get; set; }
void INestedObject.Initialize()
{
A = null;
B = 7;
}
void INestedObject.Verify()
{
Assert.Null(A);
Assert.Equal(7, B);
}
}
private class NestedClassWithParamCtor : NestedClass
{
public NestedClassWithParamCtor(string a)
=> A = a;
}
private class DictionaryTestClass<TNested> : ITestObject where TNested : INestedObject
{
public Dictionary<string, TNested> A { get; set; }
void ITestObject.Initialize(INestedObject nested)
{
nested.Initialize();
A = new() { { "a", (TNested)nested }, { "b", (TNested)nested } };
}
void ITestObject.Verify()
{
Assert.NotNull(A);
Assert.Collection(A,
kv =>
{
Assert.Equal("a", kv.Key);
kv.Value.Verify();
},
kv =>
{
Assert.Equal("b", kv.Key);
kv.Value.Verify();
});
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/Common/src/Extensions/TypeNameHelper/TypeNameHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Extensions.Internal
{
internal static class TypeNameHelper
{
private const char DefaultNestedTypeDelimiter = '+';
private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string>
{
{ typeof(void), "void" },
{ typeof(bool), "bool" },
{ typeof(byte), "byte" },
{ typeof(char), "char" },
{ typeof(decimal), "decimal" },
{ typeof(double), "double" },
{ typeof(float), "float" },
{ typeof(int), "int" },
{ typeof(long), "long" },
{ typeof(object), "object" },
{ typeof(sbyte), "sbyte" },
{ typeof(short), "short" },
{ typeof(string), "string" },
{ typeof(uint), "uint" },
{ typeof(ulong), "ulong" },
{ typeof(ushort), "ushort" }
};
[return: NotNullIfNotNull("item")]
public static string? GetTypeDisplayName(object? item, bool fullName = true)
{
return item == null ? null : GetTypeDisplayName(item.GetType(), fullName);
}
/// <summary>
/// Pretty print a type name.
/// </summary>
/// <param name="type">The <see cref="Type"/>.</param>
/// <param name="fullName"><c>true</c> to print a fully qualified name.</param>
/// <param name="includeGenericParameterNames"><c>true</c> to include generic parameter names.</param>
/// <param name="includeGenericParameters"><c>true</c> to include generic parameters.</param>
/// <param name="nestedTypeDelimiter">Character to use as a delimiter in nested type names</param>
/// <returns>The pretty printed type name.</returns>
public static string GetTypeDisplayName(Type type, bool fullName = true, bool includeGenericParameterNames = false, bool includeGenericParameters = true, char nestedTypeDelimiter = DefaultNestedTypeDelimiter)
{
var builder = new StringBuilder();
ProcessType(builder, type, new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter));
return builder.ToString();
}
private static void ProcessType(StringBuilder builder, Type type, in DisplayNameOptions options)
{
if (type.IsGenericType)
{
Type[] genericArguments = type.GetGenericArguments();
ProcessGenericType(builder, type, genericArguments, genericArguments.Length, options);
}
else if (type.IsArray)
{
ProcessArrayType(builder, type, options);
}
else if (_builtInTypeNames.TryGetValue(type, out string? builtInName))
{
builder.Append(builtInName);
}
else if (type.IsGenericParameter)
{
if (options.IncludeGenericParameterNames)
{
builder.Append(type.Name);
}
}
else
{
string name = options.FullName ? type.FullName! : type.Name;
builder.Append(name);
if (options.NestedTypeDelimiter != DefaultNestedTypeDelimiter)
{
builder.Replace(DefaultNestedTypeDelimiter, options.NestedTypeDelimiter, builder.Length - name.Length, name.Length);
}
}
}
private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options)
{
Type innerType = type;
while (innerType.IsArray)
{
innerType = innerType.GetElementType()!;
}
ProcessType(builder, innerType, options);
while (type.IsArray)
{
builder.Append('[');
builder.Append(',', type.GetArrayRank() - 1);
builder.Append(']');
type = type.GetElementType()!;
}
}
private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, in DisplayNameOptions options)
{
int offset = 0;
if (type.IsNested)
{
offset = type.DeclaringType!.GetGenericArguments().Length;
}
if (options.FullName)
{
if (type.IsNested)
{
ProcessGenericType(builder, type.DeclaringType!, genericArguments, offset, options);
builder.Append(options.NestedTypeDelimiter);
}
else if (!string.IsNullOrEmpty(type.Namespace))
{
builder.Append(type.Namespace);
builder.Append('.');
}
}
int genericPartIndex = type.Name.IndexOf('`');
if (genericPartIndex <= 0)
{
builder.Append(type.Name);
return;
}
builder.Append(type.Name, 0, genericPartIndex);
if (options.IncludeGenericParameters)
{
builder.Append('<');
for (int i = offset; i < length; i++)
{
ProcessType(builder, genericArguments[i], options);
if (i + 1 == length)
{
continue;
}
builder.Append(',');
if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter)
{
builder.Append(' ');
}
}
builder.Append('>');
}
}
private readonly struct DisplayNameOptions
{
public DisplayNameOptions(bool fullName, bool includeGenericParameterNames, bool includeGenericParameters, char nestedTypeDelimiter)
{
FullName = fullName;
IncludeGenericParameters = includeGenericParameters;
IncludeGenericParameterNames = includeGenericParameterNames;
NestedTypeDelimiter = nestedTypeDelimiter;
}
public bool FullName { get; }
public bool IncludeGenericParameters { get; }
public bool IncludeGenericParameterNames { get; }
public char NestedTypeDelimiter { get; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Extensions.Internal
{
internal static class TypeNameHelper
{
private const char DefaultNestedTypeDelimiter = '+';
private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string>
{
{ typeof(void), "void" },
{ typeof(bool), "bool" },
{ typeof(byte), "byte" },
{ typeof(char), "char" },
{ typeof(decimal), "decimal" },
{ typeof(double), "double" },
{ typeof(float), "float" },
{ typeof(int), "int" },
{ typeof(long), "long" },
{ typeof(object), "object" },
{ typeof(sbyte), "sbyte" },
{ typeof(short), "short" },
{ typeof(string), "string" },
{ typeof(uint), "uint" },
{ typeof(ulong), "ulong" },
{ typeof(ushort), "ushort" }
};
[return: NotNullIfNotNull("item")]
public static string? GetTypeDisplayName(object? item, bool fullName = true)
{
return item == null ? null : GetTypeDisplayName(item.GetType(), fullName);
}
/// <summary>
/// Pretty print a type name.
/// </summary>
/// <param name="type">The <see cref="Type"/>.</param>
/// <param name="fullName"><c>true</c> to print a fully qualified name.</param>
/// <param name="includeGenericParameterNames"><c>true</c> to include generic parameter names.</param>
/// <param name="includeGenericParameters"><c>true</c> to include generic parameters.</param>
/// <param name="nestedTypeDelimiter">Character to use as a delimiter in nested type names</param>
/// <returns>The pretty printed type name.</returns>
public static string GetTypeDisplayName(Type type, bool fullName = true, bool includeGenericParameterNames = false, bool includeGenericParameters = true, char nestedTypeDelimiter = DefaultNestedTypeDelimiter)
{
var builder = new StringBuilder();
ProcessType(builder, type, new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter));
return builder.ToString();
}
private static void ProcessType(StringBuilder builder, Type type, in DisplayNameOptions options)
{
if (type.IsGenericType)
{
Type[] genericArguments = type.GetGenericArguments();
ProcessGenericType(builder, type, genericArguments, genericArguments.Length, options);
}
else if (type.IsArray)
{
ProcessArrayType(builder, type, options);
}
else if (_builtInTypeNames.TryGetValue(type, out string? builtInName))
{
builder.Append(builtInName);
}
else if (type.IsGenericParameter)
{
if (options.IncludeGenericParameterNames)
{
builder.Append(type.Name);
}
}
else
{
string name = options.FullName ? type.FullName! : type.Name;
builder.Append(name);
if (options.NestedTypeDelimiter != DefaultNestedTypeDelimiter)
{
builder.Replace(DefaultNestedTypeDelimiter, options.NestedTypeDelimiter, builder.Length - name.Length, name.Length);
}
}
}
private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options)
{
Type innerType = type;
while (innerType.IsArray)
{
innerType = innerType.GetElementType()!;
}
ProcessType(builder, innerType, options);
while (type.IsArray)
{
builder.Append('[');
builder.Append(',', type.GetArrayRank() - 1);
builder.Append(']');
type = type.GetElementType()!;
}
}
private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, in DisplayNameOptions options)
{
int offset = 0;
if (type.IsNested)
{
offset = type.DeclaringType!.GetGenericArguments().Length;
}
if (options.FullName)
{
if (type.IsNested)
{
ProcessGenericType(builder, type.DeclaringType!, genericArguments, offset, options);
builder.Append(options.NestedTypeDelimiter);
}
else if (!string.IsNullOrEmpty(type.Namespace))
{
builder.Append(type.Namespace);
builder.Append('.');
}
}
int genericPartIndex = type.Name.IndexOf('`');
if (genericPartIndex <= 0)
{
builder.Append(type.Name);
return;
}
builder.Append(type.Name, 0, genericPartIndex);
if (options.IncludeGenericParameters)
{
builder.Append('<');
for (int i = offset; i < length; i++)
{
ProcessType(builder, genericArguments[i], options);
if (i + 1 == length)
{
continue;
}
builder.Append(',');
if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter)
{
builder.Append(' ');
}
}
builder.Append('>');
}
}
private readonly struct DisplayNameOptions
{
public DisplayNameOptions(bool fullName, bool includeGenericParameterNames, bool includeGenericParameters, char nestedTypeDelimiter)
{
FullName = fullName;
IncludeGenericParameters = includeGenericParameters;
IncludeGenericParameterNames = includeGenericParameterNames;
NestedTypeDelimiter = nestedTypeDelimiter;
}
public bool FullName { get; }
public bool IncludeGenericParameters { get; }
public bool IncludeGenericParameterNames { get; }
public char NestedTypeDelimiter { get; }
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Xml/tests/Readers/ReaderSettings/ReaderSettings.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 System.Text;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
[TestModule(Name = "ReaderSettings Test", Desc = "ReaderSettings Test")]
public partial class CReaderTestModule : CGenericTestModule
{
public override int Init(object objParam)
{
int ret = base.Init(objParam);
// Create global usage test files
string strFile = string.Empty;
// Create reader factory
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC);
ReaderFactory = new ReaderSettingsFactory();
return ret;
}
public override int Terminate(object objParam)
{
// Remove global usage test files
return base.Terminate(objParam);
}
}
internal class ReaderSettingsFactory : ReaderFactory
{
public override XmlReader Create(MyDict<string, object> options)
{
XmlReaderSettings settings = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
if (settings == null)
settings = new XmlReaderSettings();
Stream stream = (Stream)options[ReaderFactory.HT_STREAM];
string filename = (string)options[ReaderFactory.HT_FILENAME];
object readerType = options[ReaderFactory.HT_READERTYPE];
string fragment = (string)options[ReaderFactory.HT_FRAGMENT];
if (stream != null)
{
XmlReader reader = ReaderHelper.Create(stream, settings, filename);
return reader;
}
if (fragment != null)
{
StringReader tr = new StringReader(fragment);
XmlReader reader = ReaderHelper.Create(tr, settings, "someUri");
return reader;
}
if (filename != null)
{
XmlReader reader = ReaderHelper.Create(filename, settings);
return reader;
}
throw new CTestFailedException("No Reader Created");
}
}
//[TestCase("ReaderSettings Generic Tests.CoreReader", Param = "CoreReader")]
//[TestCase("ReaderSettings Generic Tests.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("ReaderSettings Generic Tests.WrappedReader", Param = "WrappedReader")]
//[TestCase("ReaderSettings Generic Tests.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("ReaderSettings Generic Tests.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("ReaderSettings Generic Tests.XsdValidatingReader", Param = "XsdValidatingReader")]
public partial class TCReaderSettings : TCXMLReaderBaseGeneral
{
public int v1()
{
string readerType = (string)this.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader("<root>abc</root>"), false))
{
CError.WriteLine(r.GetType().ToString());
CError.Compare((r.Settings != null), "Settings is null");
}
return TEST_PASS;
}
}
//[TestCase("CloseInput.CoreReader", Param = "CoreReader")]
//[TestCase("CloseInput.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("CloseInput.WrappedReader", Param = "WrappedReader")]
//[TestCase("CloseInput.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("CloseInput.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("CloseInput.XsdValidatingReader", Param = "XsdValidatingReader")]
//[TestCase("CloseInput.XmlTextReader", Param = "XmlTextReader")]
//[TestCase("CloseInput.XPathNavigatorReader", Param = "XPathNavigatorReader")]
//[TestCase("CloseInput.XsltReader", Param = "XsltReader")]
//[TestCase("CloseInput.XmlNodeReader", Param = "XmlNodeReader")]
//[TestCase("CloseInput.XmlBinaryReader", Param = "XmlBinaryReader")]
public partial class TCCloseInput : TCXMLReaderBaseGeneral
{
[Variation("Default Values", Priority = 0)]
public int v1()
{
XmlReaderSettings settings = new XmlReaderSettings();
return (settings.CloseInput == true) ? TEST_FAIL : TEST_PASS;
}
}
//[TestCase("ReaderSettings Generic Tests.CoreReader", Param = "CoreReader")]
//[TestCase("ReaderSettings Generic Tests.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("ReaderSettings Generic Tests.WrappedReader", Param = "WrappedReader")]
//[TestCase("ReaderSettings Generic Tests.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("ReaderSettings Generic Tests.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("ReaderSettings Generic Tests.XsdValidatingReader", Param = "XsdValidatingReader")]
public partial class TCRSGeneric : TCXMLReaderBaseGeneral
{
[Variation("ReaderSettings not null", Priority = 0)]
public int v1()
{
string readerType = (string)this.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader("<root>abc</root>"), false))
{
CError.WriteLine(r.GetType().ToString());
CError.Compare((r.Settings != null), "Settings is null");
}
return TEST_PASS;
}
[Variation("Wrapping scenario")]
public int WrappingScenario()
{
if (AsyncUtil.IsAsyncEnabled)
return TEST_SKIPPED;
string readerType = (string)this.Param;
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.CheckCharacters = true;
ReaderSettings.IgnoreProcessingInstructions = true;
ReaderSettings.IgnoreComments = true;
ReaderSettings.IgnoreWhitespace = true;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader("<root/>"), false, null, ReaderSettings))
{
using (XmlReader r2 = ReaderHelper.Create(r, ReaderSettings)) { }
}
return TEST_PASS;
}
[Variation("Reset", Priority = 0)]
public int v3()
{
string readerType = (string)this.Param;
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader("<a/>"), false, null, rs))
{
bool cc = r.Settings.CheckCharacters;
bool closeinput = r.Settings.CloseInput;
DtdProcessing dtd = r.Settings.DtdProcessing;
bool ignorecomm = r.Settings.IgnoreComments;
bool ignorepi = r.Settings.IgnoreProcessingInstructions;
bool ignorewhtsp = r.Settings.IgnoreWhitespace;
int lineNumberOffset = r.Settings.LineNumberOffset;
int linePositionOffset = r.Settings.LinePositionOffset;
long maxcharsindoc = r.Settings.MaxCharactersInDocument;
XmlNameTable nameTable = r.Settings.NameTable;
ConformanceLevel cl = r.Settings.ConformanceLevel;
Type t = r.Settings.GetType();
rs.Reset();
CError.Compare(cc, rs.CheckCharacters, "cc");
CError.Compare(closeinput, rs.CloseInput, "closeinput");
CError.Compare(dtd, rs.DtdProcessing, "dtd");
CError.Compare(ignorecomm, rs.IgnoreComments, "ignorecomm");
CError.Compare(ignorepi, rs.IgnoreProcessingInstructions, "ignorepi");
CError.Compare(ignorewhtsp, rs.IgnoreWhitespace, "ignorewhtsp");
CError.Compare(lineNumberOffset, rs.LineNumberOffset, "lineNumberOffset");
CError.Compare(linePositionOffset, rs.LinePositionOffset, "linePositionOffset");
CError.Compare(maxcharsindoc, rs.MaxCharactersInDocument, "maxcharsindoc");
CError.Compare(nameTable, rs.NameTable, "nameTable");
CError.Compare(cl, rs.ConformanceLevel, "cl");
CError.Compare(t, rs.GetType(), "t");
return TEST_PASS;
}
}
[Variation("Clone", Priority = 0)]
public int v4()
{
XmlReaderSettings rs = new XmlReaderSettings();
XmlReaderSettings crs = rs.Clone();
CError.Compare(rs.CheckCharacters, crs.CheckCharacters, "CheckCharacters");
CError.Compare(rs.CloseInput, crs.CloseInput, "CloseInput");
CError.Compare(rs.DtdProcessing, crs.DtdProcessing, "ProhibitDtd");
CError.Compare(rs.IgnoreComments, crs.IgnoreComments, "IgnoreComments");
CError.Compare(rs.IgnoreProcessingInstructions, crs.IgnoreProcessingInstructions, "IgnorePI");
CError.Compare(rs.IgnoreWhitespace, crs.IgnoreWhitespace, "IgnoreWhitespace");
CError.Compare(rs.LineNumberOffset, crs.LineNumberOffset, "LineNumberOffset");
CError.Compare(rs.LinePositionOffset, crs.LinePositionOffset, "LinePositionOffset");
CError.Compare(rs.MaxCharactersInDocument, crs.MaxCharactersInDocument, "maxcharsindoc");
CError.Compare(rs.NameTable, crs.NameTable, "NameTable");
CError.Compare(rs.ConformanceLevel, crs.ConformanceLevel, "ConformanceLevel");
CError.Compare(rs.GetType(), crs.GetType(), "GetType");
return TEST_PASS;
}
[Variation("NameTable", Priority = 0)]
public int v5()
{
XmlNameTable nt = null;
XmlReaderSettings rs = new XmlReaderSettings();
rs.NameTable = nt;
return TEST_PASS;
}
}
//[TestCase("TCDtdProcessingCoreReader.CoreReader", Param = "CoreReader")]
//[TestCase("TCDtdProcessingCoreReader.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("TCDtdProcessingCoreReader.WrappedReader", Param = "WrappedReader")]
//[TestCase("TCDtdProcessingCoreReader.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("TCDtdProcessingCoreReader.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("TCDtdProcessingCoreReader.XsdValidatingReader", Param = "XsdValidatingReader")]
public partial class TCDtdProcessingCoreReader : TCXMLReaderBaseGeneral
{
//[Variation("Read xml without DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Read xml without DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Read xml without DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v0()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1a()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.Create(r, s))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Ignore, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1b()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.Create(r, s))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1d()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
u.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.Create(r, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1e()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
u.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.Create(r, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, xml with DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, xml with DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, xml with DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v2a()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE root [<!ELEMENT root ANY>]><root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Prohibit;
using (XmlReader wr = ReaderHelper.Create(r, s))
{
try
{
while (wr.Read()) ;
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error0");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error00");
return TEST_PASS;
}
catch (XmlException)
{
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
return TEST_PASS;
}
}
}
}
//[Variation("Wrap with Ignore, xml with DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, xml with DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, xml with DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v2b()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE root [<!ELEMENT root ANY>]><root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader wr = ReaderHelper.Create(r, s))
{
try
{
while (wr.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error3");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Ignore, "error4");
}
}
return TEST_PASS;
}
[Variation("Testing default values.")]
public int V3()
{
string readerType = (string)this.Param;
string strXml = "<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "DtdProcessing");
}
return TEST_PASS;
}
//[Variation("Parse a file with inline DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with inline DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with inline DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V4()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT a ANY>\n]> \n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
}
return TEST_PASS;
}
//[Variation("Parse a xml with inline inv.DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a xml with inline inv.DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a xml with inline inv.DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V4c()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = @"<?xml version='1.0' encoding='utf-8'?><!DOCTYPE r [<!ATTLIST a b CDATA #FIXED - >]><r></r>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
}
return TEST_PASS;
}
//[Variation("Read xml with invalid content.Parse", Param = DtdProcessing.Parse)]
//[Variation("Read xml with invalid content.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Read xml with invalid content.Ignore", Param = DtdProcessing.Ignore)]
public int V4i()
{
string readerType = (string)this.Param;
string strXml = "<root>&#;</root>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Ignore", Param = DtdProcessing.Ignore)]
public int V7a()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY >]><doc><![CDATA[< <<]]></doc>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Prohibit;
rs.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error1");
}
CError.Compare(strWriter.ToString(), "<doc><![CDATA[< <<]]></doc>", "error");
}
return TEST_PASS;
}
//[Variation("Parse a file with external DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with external DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with external DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V8()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT SYSTEM 'some.dtd'>\n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
}
return TEST_PASS;
}
//[Variation("Parse a file with invalid inline DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with invalid inline DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with invalid inline DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V9()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT a MANY>\n]> \n<ROOT/>"; //Wrong keyword MANY
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with predefined entities with no DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with predefined entities with no DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with predefined entities with no DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<root>
<a>
<b>
<c>
</c></b></a></root>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
while (r.Read()) ;
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with entity and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with entity and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with entity and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11a()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book \"some\">]><doc>&book;</doc>";
string exp = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book \"some\">]><doc>some</doc>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
CError.Compare(strWriter.ToString(), exp, "error");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with entity in attribute and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with entity in attribute and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with entity in attribute and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11b()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a 'some'>]><ROOT att=\"&a;\"/>";
string exp = "<!DOCTYPE ROOT [<!ENTITY a 'some'>]><ROOT att=\"some\" />";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
CError.Compare(strWriter.ToString(), exp, "error");
}
return TEST_PASS;
}
//[Variation("Parse a invalid xml with entity in attribute and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a invalid xml with entity in attribute and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a invalid xml with entity in attribute and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11c()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att=\"&a;\"/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
}
}
return TEST_FAIL;
}
//[Variation("Set value to Reader.Settings.DtdProcessing.Parse", Param = DtdProcessing.Parse)]
//[Variation("Set value to Reader.Settings.DtdProcessing.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Set value to Reader.Settings.DtdProcessing.Prohibit", Param = DtdProcessing.Prohibit)]
public int v12()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?><test> a </test>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
r.Settings.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
return TEST_FAIL;
}
[Variation("DtdProcessing - ArgumentOutOfRangeException")]
public int V14()
{
XmlReaderSettings xrs = new XmlReaderSettings();
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error");
}
catch (ArgumentOutOfRangeException)
{
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error2");
}
catch (ArgumentOutOfRangeException)
{
CError.Equals(xrs.DtdProcessing, DtdProcessing.Prohibit, "DtdProcessing");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Parse", Param = DtdProcessing.Parse)]
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Ignore", Param = DtdProcessing.Ignore)]
public int V15()
{
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error");
}
catch (ArgumentOutOfRangeException)
{
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error2");
}
catch (ArgumentOutOfRangeException)
{
CError.Equals(xrs.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "DtdProcessing");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("Parse a valid xml DTD and check NodeType.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml DTD and check NodeType.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml DTD and check NodeType.Ignore", Param = DtdProcessing.Ignore)]
public int V16()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a 'some'>]><ROOT att=\"&a;\"/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
while (r.Read())
{
CError.Compare(r.NodeType, XmlNodeType.DocumentType, "error1");
return TEST_PASS;
}
}
catch (XmlException)
{
CError.Compare(r.NodeType, XmlNodeType.None, XmlNodeType.Element, "error3");
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error4");
return TEST_PASS;
}
}
return TEST_FAIL;
}
public static string strXml = "<!DOCTYPE doc SYSTEM 'test::rootDtd'><doc></doc>";
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Ignore", Param = DtdProcessing.Ignore)]
public int V18()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE root SYSTEM 'a.dtd' PUBLIC 'some' []><root/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
while (r.Read())
{
CError.Compare(r.NodeType, XmlNodeType.DocumentType, "error1");
}
}
catch (XmlException)
{
CError.Compare(r.NodeType, XmlNodeType.None, XmlNodeType.Element, "error3");
CError.Compare(r.Settings.DtdProcessing, u.DtdProcessing, "error4");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("1.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 1 })]
//[Variation("1.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 1 })]
//[Variation("1.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 1 })]
//[Variation("2.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 2 })]
//[Variation("2.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 2 })]
//[Variation("2.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 2 })]
//[Variation("3.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 3 })]
//[Variation("3.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 3 })]
//[Variation("3.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 3 })]
//[Variation("4.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 4 })]
//[Variation("4.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 4 })]
//[Variation("4.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 4 })]
//[Variation("5.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 5})]
//[Variation("5.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 5 })]
//[Variation("5.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 5 })]
//[Variation("6.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 6 })]
//[Variation("6.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 6 })]
//[Variation("6.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 6 })]
//[Variation("7.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 7 })]
//[Variation("7.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 7 })]
//[Variation("7.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 7 })]
//[Variation("8.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 8 })]
//[Variation("8.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 8 })]
//[Variation("8.PParsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 8 })]
//[Variation("9.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 9 })]
//[Variation("9.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 9 })]
//[Variation("9.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 9 })]
//[Variation("10.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 10 })]
//[Variation("10.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 10 })]
//[Variation("10.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 10 })]
//[Variation("11.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 11 })]
//[Variation("11.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 11 })]
//[Variation("11.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 11 })]
//[Variation("12.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 12 })]
//[Variation("12.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 12 })]
//[Variation("12.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 12 })]
public int V19()
{
string xml = "";
switch ((int)CurVariation.Params[1])
{
case 1: xml = "<!DOCTYPE <"; break;
case 2: xml = "<!DOCTYPE root SYSTEM"; break;
case 3: xml = "<!DOCTYPE []<root/>"; break;
case 4: xml = "<!DOCTYPE root PUBLIC >]>"; break;
case 5: xml = "<!DOCTYPE "; break;
case 6: xml = "<!DOCTYPE >"; break;
case 7: xml = "<!DOCTYPE ["; break;
case 8: xml = " <?xml version=\"1.0\" ?>"; break;
case 9: xml = "<?xml version='1.0' ?><!DOCTYPE doc [ <!ELEMENT doc ANY >"; break;
case 10: xml = "< ?xml version=\"1.0\" ?>"; break;
case 11: xml = "<? xml version=\"1.0\" ?>"; break;
case 12: xml = "<?xml version = \" 1.0 \" ?>"; break;
}
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Params[0];
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(xml), false, null, u))
{
try
{
while (r.Read()) ;
}
catch (XmlException)
{
CError.Compare(r.Settings.DtdProcessing, u.DtdProcessing, "error4");
return TEST_PASS;
}
}
return TEST_FAIL;
}
}
//[TestCase("TCDtdProcessingNonCoreReader.XmlTextReader", Param = "XmlTextReader")]
//[TestCase("TCDtdProcessingNonCoreReader.XmlValidatingReader", Param = "XmlValidatingReader")]
//[TestCase("TCDtdProcessingNonCoreReader.XmlNodeReader", Param = "XmlNodeReader")]
//[TestCase("TCDtdProcessingNonCoreReader.XsltReader", Param = "XsltReader")]
public partial class TCDtdProcessingNonCoreReader : TCXMLReaderBaseGeneral
{
//[Variation("Read xml without DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Read xml without DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Read xml without DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v0()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1a()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, s))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Ignore, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1b()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, s))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1d()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
u.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1e()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
u.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, xml with DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, xml with DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, xml with DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v2a()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT ROOT ANY>\n]> \n<ROOT>abc 123</ROOT>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Prohibit;
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, s))
{
try
{
while (wr.Read()) ;
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error0");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error00");
return TEST_PASS;
}
catch (XmlException)
{
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
}
//[Variation("Wrap with Ignore, xml with DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, xml with DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, xml with DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v2b()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT ROOT ANY>\n]> \n<ROOT>abc 123</ROOT>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, s))
{
try
{
while (wr.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error3");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Ignore, "error4");
}
}
return TEST_PASS;
}
[Variation("Testing default values")]
public int V3()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT a ANY>\n]> \n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "DtdProcessing");
}
return TEST_PASS;
}
//[Variation("Read xml with invalid content.Parse", Param = DtdProcessing.Parse)]
//[Variation("Read xml with invalid content.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Read xml with invalid content.Ignore", Param = DtdProcessing.Ignore)]
public int V4i()
{
string readerType = (string)this.Param;
string strXml = "<root>&#;</root>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlReader r = null;
try
{
r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs);
while (r.Read()) ;
CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
return TEST_FAIL;
}
//[Variation("Changing DtdProcessing to Parse, Prohibit.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Parse, Prohibit.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Parse, Prohibit.Ignore", Param = DtdProcessing.Ignore)]
public int V5()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT ROOT ANY>\n]> \n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Prohibit;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
if (r.Settings != null) CError.Compare(false, "error2");
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
}
return TEST_PASS;
}
//[Variation("Changing DtdProcessing to Prohibit,Parse.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Prohibit,Parse.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Prohibit,Parse.Ignore", Param = DtdProcessing.Ignore)]
public int V6()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book ''> <!ATTLIST doc JSmith CDATA #FIXED '' date CDATA #IMPLIED>]><doc JSmith=\"\" date=\"\"> &book; </doc>";
string exp = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book ''> <!ATTLIST doc JSmith CDATA #FIXED '' date CDATA #IMPLIED>]><doc JSmith=\"\" date=\"\"> </doc>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
}
CError.Compare(strWriter.ToString(), (readerType == "XmlTextReader") ? strXml : exp, "error");
}
return TEST_PASS;
}
//[Variation("Changing DtdProcessing to Parse, Ignore.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Parse, Ignore.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Parse, Ignore.Ignore", Param = DtdProcessing.Ignore)]
public int V7()
{
string readerType = (string)this.Param;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book ''> <!ATTLIST doc JSmith CDATA #FIXED '' date CDATA #IMPLIED>]><doc JSmith='' date=''> &book; </doc> ";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
if (r.Settings != null) CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error1");
return TEST_PASS;
}
}
}
}
return TEST_PASS;
}
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Ignore", Param = DtdProcessing.Ignore)]
public int V7a()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY >]><doc><![CDATA[< <<]]></doc>";
string exp =
(readerType == "XmlNodeReader" || readerType == "XmlValidatingReader" || readerType == "XmlTextReader") ?
"<!DOCTYPE doc [ <!ELEMENT doc ANY >]><doc><![CDATA[< <<]]></doc>" : "<doc><![CDATA[< <<]]></doc>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Prohibit;
rs.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error1");
}
CError.Compare(strWriter.ToString(), exp, "error");
}
return TEST_PASS;
}
//[Variation("Parse a file with external DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with external DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with external DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V8()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT SYSTEM 'some.dtd'>\n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlReader r = null;
try
{
using (r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
while (r.Read()) ;
}
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
catch (FileNotFoundException e)
{
CError.WriteLine(e);
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
return TEST_PASS;
}
//[Variation("Parse a file with invalid inline DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with invalid inline DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with invalid inline DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V9()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT a MANY>\n]> \n<ROOT/>"; //Wrong keyword MANY
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlReader r = null;
try
{
r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs);
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
return TEST_PASS;
}
//[Variation("Parse a valid xml with predefined entities with no DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with predefined entities with no DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with predefined entities with no DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<root>
<a>
<b>
<c>
</c></b></a></root>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
while (r.Read()) ;
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with entity and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with entity and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with entity and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11a()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book \"some\">]><doc>&book;</doc>";
string exp = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book \"some\">]><doc>some</doc>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
CError.Compare(strWriter.ToString(), (readerType != "XmlTextReader") ? exp : strXml, "error");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with entity in attribute and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with entity in attribute and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with entity in attribute and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11b()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader" || readerType == "XmlNodeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ELEMENT ROOT ANY><!ATTRIBUTE att ANY><!ENTITY a 'some'>]><ROOT att=\"&a;\" />";
string exp = "<!DOCTYPE ROOT [<!ELEMENT ROOT ANY><!ATTRIBUTE att ANY><!ENTITY a 'some'>]><ROOT att=\"some\" />";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
CError.Compare(strWriter.ToString(), (readerType != "XmlTextReader") ? exp : strXml, "error");
}
return TEST_PASS;
}
//[Variation("Parse a invalid xml with entity in attribute and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a invalid xml with entity in attribute and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a invalid xml with entity in attribute and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11c()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att=\"&a;\"/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
XmlReader r = null;
using (StringWriter strWriter = new StringWriter())
{
try
{
using (r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
if (readerType != "XmlTextReader") CError.Compare(false, "error");
}
}
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
return (readerType != "XmlTextReader") ? TEST_FAIL : TEST_PASS;
}
//[Variation("Set value to Reader.Settings.DtdProcessing.Parse", Param = DtdProcessing.Parse)]
//[Variation("Set value to Reader.Settings.DtdProcessing.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Set value to Reader.Settings.DtdProcessing.Prohibit", Param = DtdProcessing.Prohibit)]
public int v12()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?><test> a </test>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
if (r.Settings != null) r.Settings.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
if (r.Settings != null) CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
return TEST_PASS;
}
[Variation("DtdProcessing - ArgumentOutOfRangeException")]
public int V14()
{
XmlReaderSettings xrs = new XmlReaderSettings();
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error");
}
catch (ArgumentOutOfRangeException)
{
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error2");
}
catch (ArgumentOutOfRangeException)
{
CError.Equals(xrs.DtdProcessing, DtdProcessing.Prohibit, "DtdProcessing");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Parse", Param = DtdProcessing.Parse)]
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Ignore", Param = DtdProcessing.Ignore)]
public int V15()
{
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error");
}
catch (ArgumentOutOfRangeException)
{
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error2");
}
catch (ArgumentOutOfRangeException)
{
CError.Equals(xrs.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "DtdProcessing");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("Parse a valid xml DTD and check NodeType.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml DTD and check NodeType.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml DTD and check NodeType.Ignore", Param = DtdProcessing.Ignore)]
public int V16()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a 'some'>]><ROOT att=\"&a;\"/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
while (r.Read())
{
CError.Compare(r.NodeType, XmlNodeType.DocumentType, XmlNodeType.Element, "error1");
return TEST_PASS;
}
}
catch (XmlException)
{
CError.Compare(r.NodeType, XmlNodeType.None, XmlNodeType.Element, "error3");
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error4");
return TEST_PASS;
}
}
return TEST_FAIL;
}
public static string strXml = "<!DOCTYPE doc SYSTEM 'test::rootDtd'><doc></doc>";
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Ignore", Param = DtdProcessing.Ignore)]
public int V18()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader" || readerType == "XmlNodeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE root SYSTEM 'a.dtd' PUBLIC 'some' []><root/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlReader r = null;
try
{
r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u);
while (r.Read())
{
CError.Compare(r.NodeType, XmlNodeType.DocumentType, "error1");
}
}
catch (XmlException)
{
if (r != null) CError.Compare(r.NodeType, XmlNodeType.None, XmlNodeType.Element, "error3");
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, u.DtdProcessing, "error4");
return TEST_PASS;
}
return TEST_FAIL;
}
//[Variation("1.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 1 })]
//[Variation("1.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 1 })]
//[Variation("1.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 1 })]
//[Variation("2.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 2 })]
//[Variation("2.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 2 })]
//[Variation("2.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 2 })]
//[Variation("3.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 3 })]
//[Variation("3.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 3 })]
//[Variation("3.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 3 })]
//[Variation("4.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 4 })]
//[Variation("4.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 4 })]
//[Variation("4.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 4 })]
//[Variation("5.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 5 })]
//[Variation("5.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 5 })]
//[Variation("5.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 5 })]
//[Variation("6.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 6 })]
//[Variation("6.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 6 })]
//[Variation("6.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 6 })]
//[Variation("7.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 7 })]
//[Variation("7.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 7 })]
//[Variation("7.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 7 })]
//[Variation("8.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 8 })]
//[Variation("8.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 8 })]
//[Variation("8.PParsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 8 })]
//[Variation("9.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 9 })]
//[Variation("9.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 9 })]
//[Variation("9.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 9 })]
//[Variation("10.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 10 })]
//[Variation("10.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 10 })]
//[Variation("10.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 10 })]
//[Variation("11.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 11 })]
//[Variation("11.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 11 })]
//[Variation("11.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 11 })]
//[Variation("12.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 12 })]
//[Variation("12.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 12 })]
//[Variation("12.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 12 })]
public int V19()
{
string xml = "";
switch ((int)CurVariation.Params[1])
{
case 1: xml = "<!DOCTYPE <"; break;
case 2: xml = "<!DOCTYPE root SYSTEM"; break;
case 3: xml = "<!DOCTYPE []<root/>"; break;
case 4: xml = "<!DOCTYPE root PUBLIC >]>"; break;
case 5: xml = "<!DOCTYPE "; break;
case 6: xml = "<!DOCTYPE >"; break;
case 7: xml = "<!DOCTYPE ["; break;
case 8: xml = " <?xml version=\"1.0\" ?>"; break;
case 9: xml = "<?xml version='1.0' ?><!DOCTYPE doc [ <!ELEMENT doc ANY >"; break;
case 10: xml = "< ?xml version=\"1.0\" ?>"; break;
case 11: xml = "<? xml version=\"1.0\" ?>"; break;
case 12: xml = "<?xml version = \" 1.0 \" ?>"; break;
}
string readerType = (string)this.Param;
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Params[0];
XmlReader r = null;
try
{
r = ReaderHelper.CreateReader(readerType, new StringReader(xml), false, null, u);
while (r.Read()) ;
}
catch (XmlException)
{
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, u.DtdProcessing, "error4");
return TEST_PASS;
}
return TEST_FAIL;
}
}
//[TestCase("Read xml as one byte stream.CoreReader", Param = "CoreReader")]
//[TestCase("Read xml as one byte stream.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("Read xml as one byte stream.WrappedReader", Param = "WrappedReader")]
//[TestCase("Read xml as one byte stream.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("Read xml as one byte stream.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("Read xml as one byte stream.XsdValidatingReader", Param = "XsdValidatingReader")]
//[TestCase("Read xml as one byte stream.XsltReader", Param = "XsltReader")]
//[TestCase("Read xml as one byte stream.XmlValidatingReader", Param = "XmlValidatingReader")]
//[TestCase("Read xml as one byte stream.XmlNodeReader", Param = "XmlNodeReader")]
//[TestCase("Read xml as one byte stream.XPathNavigatorReader", Param = "XPathNavigatorReader")]
//[TestCase("Read xml as one byte stream.XmlTextReader", Param = "XmlTextReader")]
//[TestCase("Read xml as one byte stream.XmlBinaryReader", Param = "XmlBinaryReader")]
public partial class TCOneByteStream : TCXMLReaderBaseGeneral
{
[Variation("445370: Parsing this 'some]' as fragment fails with 'Unexpected EOF' error")]
public int v0()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
if (readerType == "SubtreeReader" || readerType == "XmlNodeReader") return TEST_SKIPPED;
OneByteStream sim = new OneByteStream(new byte[] { 0xFE, 0xFF, 0, (byte)'s', 0, (byte)'o',
0, (byte)'s', 0, (byte)'o', 0, (byte)'s', 0, (byte)'o', 0, (byte)'s', 0, (byte)'o',
0, (byte)']'});
XmlReaderSettings rs = new XmlReaderSettings();
rs.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader r = ReaderHelper.CreateReader(readerType, sim, null, false, null, rs, true))
{
while (r.Read()) { CError.WriteLine(r.Value); }
}
return TEST_PASS;
}
[Variation("445370a: Parsing this 'some]' as fragment fails with 'Unexpected EOF' error")]
public int v0a()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
if (readerType == "SubtreeReader" || readerType == "XmlNodeReader") return TEST_SKIPPED;
XmlReaderSettings rs = new XmlReaderSettings();
rs.ConformanceLevel = ConformanceLevel.Fragment;
string[] s = { "sosososo]", "sosososo]]", "sososos]o", "]", "[", "][", "[]", " ]]", "[[", "sosososo[", "sosososo[[", "Last char a square bracket. ]", ". ]" };
for (int i = 0; i < s.Length; i++)
{
CError.WriteLine(s[i]);
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(s[i]), false, null, rs, true))
{
r.Read();
CError.WriteLine(r.Value);
}
}
return TEST_PASS;
}
[Variation("Read as one byte stream xml with surrogate char")]
public int v1()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
string str = "<abc abc='\uD812\uDD12'>\uD812\uDD12</abc>";
byte[] bytes = Encoding.Unicode.GetBytes(str);
XmlReaderSettings rs = new XmlReaderSettings();
OneByteStream sim = new OneByteStream(bytes);
using (XmlReader r = ReaderHelper.CreateReader(readerType, sim, null, false, null, rs, false))
{
while (r.Read()) { CError.WriteLine(r.Value); }
return TEST_PASS;
}
}
[Variation("Read as TextReader xml with surrogate char")]
public int v1a()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
string str = "<abc abc='\uD812\uDD12'>\uD812\uDD12</abc>";
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(str), false, null, rs, false))
{
while (r.Read()) { CError.WriteLine(r.Value); }
return TEST_PASS;
}
}
[Variation("XmlWriter.WriteNode: read as one byte stream xml with surrogate char")]
public int v2()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
string str = "<abc abc='\uD812\uDD12'>\uD812\uDD12</abc>";
string exp = "<?xml version=\"1.0\" encoding=\"utf-16\"?><abc abc=\"\U00014912\">\U00014912</abc>";
exp = (readerType == "XmlBinaryReader") ? "<?xml version=\"1.0\" encoding=\"utf-8\"?><abc abc=\"\U00014912\">\U00014912</abc>" : exp;
byte[] bytes = Encoding.Unicode.GetBytes(str);
XmlReaderSettings rs = new XmlReaderSettings();
OneByteStream sim = new OneByteStream(bytes);
using (XmlReader r = ReaderHelper.CreateReader(readerType, sim, null, false, null, rs, false))
{
using (StringWriter sw = new StringWriter())
{
using (XmlWriter w = WriterHelper.Create(sw))
{
w.WriteNode(r, false);
}
CError.Compare(sw.ToString(), exp, "writer output");
}
}
return TEST_PASS;
}
}
internal class OneByteStream : System.IO.Stream
{
private byte[] _input;
private int _pos;
public OneByteStream(byte[] input)
{
_input = input;
_pos = 0;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override void Flush()
{
throw new Exception("The method or operation is not implemented.");
}
public override long Length
{
get { return _input.Length; }
}
public override long Position
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public override int Read(byte[] buffer, int offset, int count)
{
int tocopy = count;
if (tocopy > _input.Length - _pos)
{
tocopy = _input.Length - _pos;
}
if (tocopy > 4)
{
tocopy = 4;
}
int i;
for (i = 0; i < tocopy; i++)
{
buffer[offset + i] = _input[_pos + i];
}
_pos += i;
return i;
}
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new Exception("The method or operation is not implemented.");
}
public override void SetLength(long value)
{
throw new Exception("The method or operation is not implemented.");
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new Exception("The method or operation is not implemented.");
}
}
}
| // 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 System.Text;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
[TestModule(Name = "ReaderSettings Test", Desc = "ReaderSettings Test")]
public partial class CReaderTestModule : CGenericTestModule
{
public override int Init(object objParam)
{
int ret = base.Init(objParam);
// Create global usage test files
string strFile = string.Empty;
// Create reader factory
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC);
ReaderFactory = new ReaderSettingsFactory();
return ret;
}
public override int Terminate(object objParam)
{
// Remove global usage test files
return base.Terminate(objParam);
}
}
internal class ReaderSettingsFactory : ReaderFactory
{
public override XmlReader Create(MyDict<string, object> options)
{
XmlReaderSettings settings = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
if (settings == null)
settings = new XmlReaderSettings();
Stream stream = (Stream)options[ReaderFactory.HT_STREAM];
string filename = (string)options[ReaderFactory.HT_FILENAME];
object readerType = options[ReaderFactory.HT_READERTYPE];
string fragment = (string)options[ReaderFactory.HT_FRAGMENT];
if (stream != null)
{
XmlReader reader = ReaderHelper.Create(stream, settings, filename);
return reader;
}
if (fragment != null)
{
StringReader tr = new StringReader(fragment);
XmlReader reader = ReaderHelper.Create(tr, settings, "someUri");
return reader;
}
if (filename != null)
{
XmlReader reader = ReaderHelper.Create(filename, settings);
return reader;
}
throw new CTestFailedException("No Reader Created");
}
}
//[TestCase("ReaderSettings Generic Tests.CoreReader", Param = "CoreReader")]
//[TestCase("ReaderSettings Generic Tests.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("ReaderSettings Generic Tests.WrappedReader", Param = "WrappedReader")]
//[TestCase("ReaderSettings Generic Tests.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("ReaderSettings Generic Tests.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("ReaderSettings Generic Tests.XsdValidatingReader", Param = "XsdValidatingReader")]
public partial class TCReaderSettings : TCXMLReaderBaseGeneral
{
public int v1()
{
string readerType = (string)this.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader("<root>abc</root>"), false))
{
CError.WriteLine(r.GetType().ToString());
CError.Compare((r.Settings != null), "Settings is null");
}
return TEST_PASS;
}
}
//[TestCase("CloseInput.CoreReader", Param = "CoreReader")]
//[TestCase("CloseInput.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("CloseInput.WrappedReader", Param = "WrappedReader")]
//[TestCase("CloseInput.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("CloseInput.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("CloseInput.XsdValidatingReader", Param = "XsdValidatingReader")]
//[TestCase("CloseInput.XmlTextReader", Param = "XmlTextReader")]
//[TestCase("CloseInput.XPathNavigatorReader", Param = "XPathNavigatorReader")]
//[TestCase("CloseInput.XsltReader", Param = "XsltReader")]
//[TestCase("CloseInput.XmlNodeReader", Param = "XmlNodeReader")]
//[TestCase("CloseInput.XmlBinaryReader", Param = "XmlBinaryReader")]
public partial class TCCloseInput : TCXMLReaderBaseGeneral
{
[Variation("Default Values", Priority = 0)]
public int v1()
{
XmlReaderSettings settings = new XmlReaderSettings();
return (settings.CloseInput == true) ? TEST_FAIL : TEST_PASS;
}
}
//[TestCase("ReaderSettings Generic Tests.CoreReader", Param = "CoreReader")]
//[TestCase("ReaderSettings Generic Tests.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("ReaderSettings Generic Tests.WrappedReader", Param = "WrappedReader")]
//[TestCase("ReaderSettings Generic Tests.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("ReaderSettings Generic Tests.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("ReaderSettings Generic Tests.XsdValidatingReader", Param = "XsdValidatingReader")]
public partial class TCRSGeneric : TCXMLReaderBaseGeneral
{
[Variation("ReaderSettings not null", Priority = 0)]
public int v1()
{
string readerType = (string)this.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader("<root>abc</root>"), false))
{
CError.WriteLine(r.GetType().ToString());
CError.Compare((r.Settings != null), "Settings is null");
}
return TEST_PASS;
}
[Variation("Wrapping scenario")]
public int WrappingScenario()
{
if (AsyncUtil.IsAsyncEnabled)
return TEST_SKIPPED;
string readerType = (string)this.Param;
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.CheckCharacters = true;
ReaderSettings.IgnoreProcessingInstructions = true;
ReaderSettings.IgnoreComments = true;
ReaderSettings.IgnoreWhitespace = true;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader("<root/>"), false, null, ReaderSettings))
{
using (XmlReader r2 = ReaderHelper.Create(r, ReaderSettings)) { }
}
return TEST_PASS;
}
[Variation("Reset", Priority = 0)]
public int v3()
{
string readerType = (string)this.Param;
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader("<a/>"), false, null, rs))
{
bool cc = r.Settings.CheckCharacters;
bool closeinput = r.Settings.CloseInput;
DtdProcessing dtd = r.Settings.DtdProcessing;
bool ignorecomm = r.Settings.IgnoreComments;
bool ignorepi = r.Settings.IgnoreProcessingInstructions;
bool ignorewhtsp = r.Settings.IgnoreWhitespace;
int lineNumberOffset = r.Settings.LineNumberOffset;
int linePositionOffset = r.Settings.LinePositionOffset;
long maxcharsindoc = r.Settings.MaxCharactersInDocument;
XmlNameTable nameTable = r.Settings.NameTable;
ConformanceLevel cl = r.Settings.ConformanceLevel;
Type t = r.Settings.GetType();
rs.Reset();
CError.Compare(cc, rs.CheckCharacters, "cc");
CError.Compare(closeinput, rs.CloseInput, "closeinput");
CError.Compare(dtd, rs.DtdProcessing, "dtd");
CError.Compare(ignorecomm, rs.IgnoreComments, "ignorecomm");
CError.Compare(ignorepi, rs.IgnoreProcessingInstructions, "ignorepi");
CError.Compare(ignorewhtsp, rs.IgnoreWhitespace, "ignorewhtsp");
CError.Compare(lineNumberOffset, rs.LineNumberOffset, "lineNumberOffset");
CError.Compare(linePositionOffset, rs.LinePositionOffset, "linePositionOffset");
CError.Compare(maxcharsindoc, rs.MaxCharactersInDocument, "maxcharsindoc");
CError.Compare(nameTable, rs.NameTable, "nameTable");
CError.Compare(cl, rs.ConformanceLevel, "cl");
CError.Compare(t, rs.GetType(), "t");
return TEST_PASS;
}
}
[Variation("Clone", Priority = 0)]
public int v4()
{
XmlReaderSettings rs = new XmlReaderSettings();
XmlReaderSettings crs = rs.Clone();
CError.Compare(rs.CheckCharacters, crs.CheckCharacters, "CheckCharacters");
CError.Compare(rs.CloseInput, crs.CloseInput, "CloseInput");
CError.Compare(rs.DtdProcessing, crs.DtdProcessing, "ProhibitDtd");
CError.Compare(rs.IgnoreComments, crs.IgnoreComments, "IgnoreComments");
CError.Compare(rs.IgnoreProcessingInstructions, crs.IgnoreProcessingInstructions, "IgnorePI");
CError.Compare(rs.IgnoreWhitespace, crs.IgnoreWhitespace, "IgnoreWhitespace");
CError.Compare(rs.LineNumberOffset, crs.LineNumberOffset, "LineNumberOffset");
CError.Compare(rs.LinePositionOffset, crs.LinePositionOffset, "LinePositionOffset");
CError.Compare(rs.MaxCharactersInDocument, crs.MaxCharactersInDocument, "maxcharsindoc");
CError.Compare(rs.NameTable, crs.NameTable, "NameTable");
CError.Compare(rs.ConformanceLevel, crs.ConformanceLevel, "ConformanceLevel");
CError.Compare(rs.GetType(), crs.GetType(), "GetType");
return TEST_PASS;
}
[Variation("NameTable", Priority = 0)]
public int v5()
{
XmlNameTable nt = null;
XmlReaderSettings rs = new XmlReaderSettings();
rs.NameTable = nt;
return TEST_PASS;
}
}
//[TestCase("TCDtdProcessingCoreReader.CoreReader", Param = "CoreReader")]
//[TestCase("TCDtdProcessingCoreReader.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("TCDtdProcessingCoreReader.WrappedReader", Param = "WrappedReader")]
//[TestCase("TCDtdProcessingCoreReader.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("TCDtdProcessingCoreReader.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("TCDtdProcessingCoreReader.XsdValidatingReader", Param = "XsdValidatingReader")]
public partial class TCDtdProcessingCoreReader : TCXMLReaderBaseGeneral
{
//[Variation("Read xml without DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Read xml without DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Read xml without DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v0()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1a()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.Create(r, s))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Ignore, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1b()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.Create(r, s))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1d()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
u.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.Create(r, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1e()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
u.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.Create(r, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, xml with DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, xml with DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, xml with DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v2a()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE root [<!ELEMENT root ANY>]><root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Prohibit;
using (XmlReader wr = ReaderHelper.Create(r, s))
{
try
{
while (wr.Read()) ;
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error0");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error00");
return TEST_PASS;
}
catch (XmlException)
{
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
return TEST_PASS;
}
}
}
}
//[Variation("Wrap with Ignore, xml with DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, xml with DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, xml with DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v2b()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE root [<!ELEMENT root ANY>]><root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader wr = ReaderHelper.Create(r, s))
{
try
{
while (wr.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error1");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error3");
CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Ignore, "error4");
}
}
return TEST_PASS;
}
[Variation("Testing default values.")]
public int V3()
{
string readerType = (string)this.Param;
string strXml = "<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "DtdProcessing");
}
return TEST_PASS;
}
//[Variation("Parse a file with inline DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with inline DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with inline DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V4()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT a ANY>\n]> \n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
}
return TEST_PASS;
}
//[Variation("Parse a xml with inline inv.DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a xml with inline inv.DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a xml with inline inv.DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V4c()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = @"<?xml version='1.0' encoding='utf-8'?><!DOCTYPE r [<!ATTLIST a b CDATA #FIXED - >]><r></r>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
}
return TEST_PASS;
}
//[Variation("Read xml with invalid content.Parse", Param = DtdProcessing.Parse)]
//[Variation("Read xml with invalid content.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Read xml with invalid content.Ignore", Param = DtdProcessing.Ignore)]
public int V4i()
{
string readerType = (string)this.Param;
string strXml = "<root>&#;</root>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Ignore", Param = DtdProcessing.Ignore)]
public int V7a()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY >]><doc><![CDATA[< <<]]></doc>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Prohibit;
rs.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error1");
}
CError.Compare(strWriter.ToString(), "<doc><![CDATA[< <<]]></doc>", "error");
}
return TEST_PASS;
}
//[Variation("Parse a file with external DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with external DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with external DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V8()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT SYSTEM 'some.dtd'>\n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
}
return TEST_PASS;
}
//[Variation("Parse a file with invalid inline DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with invalid inline DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with invalid inline DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V9()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT a MANY>\n]> \n<ROOT/>"; //Wrong keyword MANY
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with predefined entities with no DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with predefined entities with no DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with predefined entities with no DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<root>
<a>
<b>
<c>
</c></b></a></root>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
while (r.Read()) ;
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with entity and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with entity and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with entity and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11a()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book \"some\">]><doc>&book;</doc>";
string exp = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book \"some\">]><doc>some</doc>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
CError.Compare(strWriter.ToString(), exp, "error");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with entity in attribute and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with entity in attribute and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with entity in attribute and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11b()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a 'some'>]><ROOT att=\"&a;\"/>";
string exp = "<!DOCTYPE ROOT [<!ENTITY a 'some'>]><ROOT att=\"some\" />";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
CError.Compare(strWriter.ToString(), exp, "error");
}
return TEST_PASS;
}
//[Variation("Parse a invalid xml with entity in attribute and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a invalid xml with entity in attribute and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a invalid xml with entity in attribute and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11c()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att=\"&a;\"/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
}
}
return TEST_FAIL;
}
//[Variation("Set value to Reader.Settings.DtdProcessing.Parse", Param = DtdProcessing.Parse)]
//[Variation("Set value to Reader.Settings.DtdProcessing.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Set value to Reader.Settings.DtdProcessing.Prohibit", Param = DtdProcessing.Prohibit)]
public int v12()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?><test> a </test>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
r.Settings.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
return TEST_FAIL;
}
[Variation("DtdProcessing - ArgumentOutOfRangeException")]
public int V14()
{
XmlReaderSettings xrs = new XmlReaderSettings();
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error");
}
catch (ArgumentOutOfRangeException)
{
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error2");
}
catch (ArgumentOutOfRangeException)
{
CError.Equals(xrs.DtdProcessing, DtdProcessing.Prohibit, "DtdProcessing");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Parse", Param = DtdProcessing.Parse)]
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Ignore", Param = DtdProcessing.Ignore)]
public int V15()
{
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error");
}
catch (ArgumentOutOfRangeException)
{
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error2");
}
catch (ArgumentOutOfRangeException)
{
CError.Equals(xrs.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "DtdProcessing");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("Parse a valid xml DTD and check NodeType.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml DTD and check NodeType.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml DTD and check NodeType.Ignore", Param = DtdProcessing.Ignore)]
public int V16()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a 'some'>]><ROOT att=\"&a;\"/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
while (r.Read())
{
CError.Compare(r.NodeType, XmlNodeType.DocumentType, "error1");
return TEST_PASS;
}
}
catch (XmlException)
{
CError.Compare(r.NodeType, XmlNodeType.None, XmlNodeType.Element, "error3");
CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error4");
return TEST_PASS;
}
}
return TEST_FAIL;
}
public static string strXml = "<!DOCTYPE doc SYSTEM 'test::rootDtd'><doc></doc>";
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Ignore", Param = DtdProcessing.Ignore)]
public int V18()
{
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE root SYSTEM 'a.dtd' PUBLIC 'some' []><root/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
while (r.Read())
{
CError.Compare(r.NodeType, XmlNodeType.DocumentType, "error1");
}
}
catch (XmlException)
{
CError.Compare(r.NodeType, XmlNodeType.None, XmlNodeType.Element, "error3");
CError.Compare(r.Settings.DtdProcessing, u.DtdProcessing, "error4");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("1.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 1 })]
//[Variation("1.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 1 })]
//[Variation("1.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 1 })]
//[Variation("2.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 2 })]
//[Variation("2.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 2 })]
//[Variation("2.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 2 })]
//[Variation("3.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 3 })]
//[Variation("3.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 3 })]
//[Variation("3.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 3 })]
//[Variation("4.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 4 })]
//[Variation("4.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 4 })]
//[Variation("4.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 4 })]
//[Variation("5.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 5})]
//[Variation("5.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 5 })]
//[Variation("5.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 5 })]
//[Variation("6.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 6 })]
//[Variation("6.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 6 })]
//[Variation("6.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 6 })]
//[Variation("7.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 7 })]
//[Variation("7.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 7 })]
//[Variation("7.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 7 })]
//[Variation("8.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 8 })]
//[Variation("8.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 8 })]
//[Variation("8.PParsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 8 })]
//[Variation("9.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 9 })]
//[Variation("9.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 9 })]
//[Variation("9.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 9 })]
//[Variation("10.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 10 })]
//[Variation("10.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 10 })]
//[Variation("10.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 10 })]
//[Variation("11.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 11 })]
//[Variation("11.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 11 })]
//[Variation("11.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 11 })]
//[Variation("12.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 12 })]
//[Variation("12.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 12 })]
//[Variation("12.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 12 })]
public int V19()
{
string xml = "";
switch ((int)CurVariation.Params[1])
{
case 1: xml = "<!DOCTYPE <"; break;
case 2: xml = "<!DOCTYPE root SYSTEM"; break;
case 3: xml = "<!DOCTYPE []<root/>"; break;
case 4: xml = "<!DOCTYPE root PUBLIC >]>"; break;
case 5: xml = "<!DOCTYPE "; break;
case 6: xml = "<!DOCTYPE >"; break;
case 7: xml = "<!DOCTYPE ["; break;
case 8: xml = " <?xml version=\"1.0\" ?>"; break;
case 9: xml = "<?xml version='1.0' ?><!DOCTYPE doc [ <!ELEMENT doc ANY >"; break;
case 10: xml = "< ?xml version=\"1.0\" ?>"; break;
case 11: xml = "<? xml version=\"1.0\" ?>"; break;
case 12: xml = "<?xml version = \" 1.0 \" ?>"; break;
}
string readerType = (string)this.Param;
if (readerType == "SubtreeReader") return TEST_SKIPPED;
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Params[0];
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(xml), false, null, u))
{
try
{
while (r.Read()) ;
}
catch (XmlException)
{
CError.Compare(r.Settings.DtdProcessing, u.DtdProcessing, "error4");
return TEST_PASS;
}
}
return TEST_FAIL;
}
}
//[TestCase("TCDtdProcessingNonCoreReader.XmlTextReader", Param = "XmlTextReader")]
//[TestCase("TCDtdProcessingNonCoreReader.XmlValidatingReader", Param = "XmlValidatingReader")]
//[TestCase("TCDtdProcessingNonCoreReader.XmlNodeReader", Param = "XmlNodeReader")]
//[TestCase("TCDtdProcessingNonCoreReader.XsltReader", Param = "XsltReader")]
public partial class TCDtdProcessingNonCoreReader : TCXMLReaderBaseGeneral
{
//[Variation("Read xml without DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Read xml without DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Read xml without DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v0()
{
string readerType = (string)this.Param;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1a()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, s))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Ignore, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1b()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, s))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, change RS, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1d()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
u.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, change RS, xml w/o DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v1e()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<root><a xmlns:b=\"abc\"><b:c /></a></root>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
u.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(wr, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error2");
}
CError.Compare(strWriter.ToString(), strXml, "error");
}
}
return TEST_PASS;
}
//[Variation("Wrap with Prohibit, xml with DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Prohibit, xml with DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Prohibit, xml with DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v2a()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT ROOT ANY>\n]> \n<ROOT>abc 123</ROOT>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Prohibit;
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, s))
{
try
{
while (wr.Read()) ;
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error0");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error00");
return TEST_PASS;
}
catch (XmlException)
{
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
}
//[Variation("Wrap with Ignore, xml with DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Wrap with Ignore, xml with DTD.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Wrap with Ignore, xml with DTD.Prohibit", Param = DtdProcessing.Prohibit)]
public int v2b()
{
string readerType = (string)this.Param;
if (readerType == "XmlNodeReader" || readerType == "XmlValidatingReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT ROOT ANY>\n]> \n<ROOT>abc 123</ROOT>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader wr = ReaderHelper.CreateReader(readerType, r, false, null, s))
{
try
{
while (wr.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error1");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error3");
if (wr.Settings != null) CError.Compare(wr.Settings.DtdProcessing, DtdProcessing.Ignore, "error4");
}
}
return TEST_PASS;
}
[Variation("Testing default values")]
public int V3()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT a ANY>\n]> \n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "DtdProcessing");
}
return TEST_PASS;
}
//[Variation("Read xml with invalid content.Parse", Param = DtdProcessing.Parse)]
//[Variation("Read xml with invalid content.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Read xml with invalid content.Ignore", Param = DtdProcessing.Ignore)]
public int V4i()
{
string readerType = (string)this.Param;
string strXml = "<root>&#;</root>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlReader r = null;
try
{
r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs);
while (r.Read()) ;
CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
return TEST_FAIL;
}
//[Variation("Changing DtdProcessing to Parse, Prohibit.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Parse, Prohibit.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Parse, Prohibit.Ignore", Param = DtdProcessing.Ignore)]
public int V5()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT ROOT ANY>\n]> \n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Prohibit;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
try
{
while (r.Read()) ;
if (r.Settings != null) CError.Compare(false, "error2");
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
}
return TEST_PASS;
}
//[Variation("Changing DtdProcessing to Prohibit,Parse.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Prohibit,Parse.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Prohibit,Parse.Ignore", Param = DtdProcessing.Ignore)]
public int V6()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book ''> <!ATTLIST doc JSmith CDATA #FIXED '' date CDATA #IMPLIED>]><doc JSmith=\"\" date=\"\"> &book; </doc>";
string exp = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book ''> <!ATTLIST doc JSmith CDATA #FIXED '' date CDATA #IMPLIED>]><doc JSmith=\"\" date=\"\"> </doc>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Prohibit;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
}
CError.Compare(strWriter.ToString(), (readerType == "XmlTextReader") ? strXml : exp, "error");
}
return TEST_PASS;
}
//[Variation("Changing DtdProcessing to Parse, Ignore.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Parse, Ignore.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Parse, Ignore.Ignore", Param = DtdProcessing.Ignore)]
public int V7()
{
string readerType = (string)this.Param;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book ''> <!ATTLIST doc JSmith CDATA #FIXED '' date CDATA #IMPLIED>]><doc JSmith='' date=''> &book; </doc> ";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
if (r.Settings != null) CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error1");
return TEST_PASS;
}
}
}
}
return TEST_PASS;
}
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Parse", Param = DtdProcessing.Parse)]
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Changing DtdProcessing to Prohibit,Ignore.Ignore", Param = DtdProcessing.Ignore)]
public int V7a()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY >]><doc><![CDATA[< <<]]></doc>";
string exp =
(readerType == "XmlNodeReader" || readerType == "XmlValidatingReader" || readerType == "XmlTextReader") ?
"<!DOCTYPE doc [ <!ELEMENT doc ANY >]><doc><![CDATA[< <<]]></doc>" : "<doc><![CDATA[< <<]]></doc>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
rs.DtdProcessing = DtdProcessing.Prohibit;
rs.DtdProcessing = DtdProcessing.Ignore;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error1");
}
CError.Compare(strWriter.ToString(), exp, "error");
}
return TEST_PASS;
}
//[Variation("Parse a file with external DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with external DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with external DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V8()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT SYSTEM 'some.dtd'>\n<ROOT/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlReader r = null;
try
{
using (r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
while (r.Read()) ;
}
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
catch (FileNotFoundException e)
{
CError.WriteLine(e);
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
return TEST_PASS;
}
//[Variation("Parse a file with invalid inline DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a file with invalid inline DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a file with invalid inline DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V9()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<!DOCTYPE ROOT[\n <!ELEMENT a MANY>\n]> \n<ROOT/>"; //Wrong keyword MANY
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlReader r = null;
try
{
r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs);
while (r.Read()) ;
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, "error");
return TEST_PASS;
}
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, "error2");
return TEST_PASS;
}
//[Variation("Parse a valid xml with predefined entities with no DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with predefined entities with no DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with predefined entities with no DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?>\n<root>
<a>
<b>
<c>
</c></b></a></root>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, rs))
{
while (r.Read()) ;
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with entity and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with entity and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with entity and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11a()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book \"some\">]><doc>&book;</doc>";
string exp = "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book \"some\">]><doc>some</doc>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
CError.Compare(strWriter.ToString(), (readerType != "XmlTextReader") ? exp : strXml, "error");
}
return TEST_PASS;
}
//[Variation("Parse a valid xml with entity in attribute and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml with entity in attribute and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml with entity in attribute and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11b()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader" || readerType == "XmlNodeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ELEMENT ROOT ANY><!ATTRIBUTE att ANY><!ENTITY a 'some'>]><ROOT att=\"&a;\" />";
string exp = "<!DOCTYPE ROOT [<!ELEMENT ROOT ANY><!ATTRIBUTE att ANY><!ENTITY a 'some'>]><ROOT att=\"some\" />";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
using (StringWriter strWriter = new StringWriter())
{
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
try
{
w.WriteNode(r, false);
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Ignore, DtdProcessing.Prohibit, "error2");
return TEST_PASS;
}
}
}
CError.Compare(strWriter.ToString(), (readerType != "XmlTextReader") ? exp : strXml, "error");
}
return TEST_PASS;
}
//[Variation("Parse a invalid xml with entity in attribute and DTD.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a invalid xml with entity in attribute and DTD.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a invalid xml with entity in attribute and DTD.Ignore", Param = DtdProcessing.Ignore)]
public int V11c()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att=\"&a;\"/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
XmlReader r = null;
using (StringWriter strWriter = new StringWriter())
{
try
{
using (r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
using (XmlWriter w = WriterHelper.Create(strWriter, ws))
{
w.WriteNode(r, false);
if (readerType != "XmlTextReader") CError.Compare(false, "error");
}
}
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
return (readerType != "XmlTextReader") ? TEST_FAIL : TEST_PASS;
}
//[Variation("Set value to Reader.Settings.DtdProcessing.Parse", Param = DtdProcessing.Parse)]
//[Variation("Set value to Reader.Settings.DtdProcessing.Ignore", Param = DtdProcessing.Ignore)]
//[Variation("Set value to Reader.Settings.DtdProcessing.Prohibit", Param = DtdProcessing.Prohibit)]
public int v12()
{
string readerType = (string)this.Param;
string strXml = "<?xml version='1.0'?><test> a </test>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
if (r.Settings != null) r.Settings.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
if (r.Settings != null) CError.Compare(false, "error");
}
catch (XmlException e)
{
CError.WriteLine(e);
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "error2");
return TEST_PASS;
}
}
return TEST_PASS;
}
[Variation("DtdProcessing - ArgumentOutOfRangeException")]
public int V14()
{
XmlReaderSettings xrs = new XmlReaderSettings();
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error");
}
catch (ArgumentOutOfRangeException)
{
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error2");
}
catch (ArgumentOutOfRangeException)
{
CError.Equals(xrs.DtdProcessing, DtdProcessing.Prohibit, "DtdProcessing");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Parse", Param = DtdProcessing.Parse)]
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("DtdProcessing - ArgumentOutOfRangeException.Ignore", Param = DtdProcessing.Ignore)]
public int V15()
{
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error");
}
catch (ArgumentOutOfRangeException)
{
try
{
xrs.DtdProcessing = (DtdProcessing)777;
CError.Compare(false, "error2");
}
catch (ArgumentOutOfRangeException)
{
CError.Equals(xrs.DtdProcessing, (DtdProcessing)this.CurVariation.Param, "DtdProcessing");
return TEST_PASS;
}
}
return TEST_FAIL;
}
//[Variation("Parse a valid xml DTD and check NodeType.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a valid xml DTD and check NodeType.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a valid xml DTD and check NodeType.Ignore", Param = DtdProcessing.Ignore)]
public int V16()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE ROOT [<!ENTITY a 'some'>]><ROOT att=\"&a;\"/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u))
{
try
{
while (r.Read())
{
CError.Compare(r.NodeType, XmlNodeType.DocumentType, XmlNodeType.Element, "error1");
return TEST_PASS;
}
}
catch (XmlException)
{
CError.Compare(r.NodeType, XmlNodeType.None, XmlNodeType.Element, "error3");
if (r.Settings != null) CError.Compare(r.Settings.DtdProcessing, DtdProcessing.Prohibit, DtdProcessing.Ignore, "error4");
return TEST_PASS;
}
}
return TEST_FAIL;
}
public static string strXml = "<!DOCTYPE doc SYSTEM 'test::rootDtd'><doc></doc>";
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Parse", Param = DtdProcessing.Parse)]
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Prohibit", Param = DtdProcessing.Prohibit)]
//[Variation("Parse a invalid xml DTD SYSTEM PUBLIC.Ignore", Param = DtdProcessing.Ignore)]
public int V18()
{
string readerType = (string)this.Param;
if (readerType == "XsltReader" || readerType == "XmlNodeReader") return TEST_SKIPPED;
string strXml = "<!DOCTYPE root SYSTEM 'a.dtd' PUBLIC 'some' []><root/>";
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Param;
XmlReader r = null;
try
{
r = ReaderHelper.CreateReader(readerType, new StringReader(strXml), false, null, u);
while (r.Read())
{
CError.Compare(r.NodeType, XmlNodeType.DocumentType, "error1");
}
}
catch (XmlException)
{
if (r != null) CError.Compare(r.NodeType, XmlNodeType.None, XmlNodeType.Element, "error3");
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, u.DtdProcessing, "error4");
return TEST_PASS;
}
return TEST_FAIL;
}
//[Variation("1.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 1 })]
//[Variation("1.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 1 })]
//[Variation("1.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 1 })]
//[Variation("2.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 2 })]
//[Variation("2.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 2 })]
//[Variation("2.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 2 })]
//[Variation("3.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 3 })]
//[Variation("3.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 3 })]
//[Variation("3.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 3 })]
//[Variation("4.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 4 })]
//[Variation("4.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 4 })]
//[Variation("4.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 4 })]
//[Variation("5.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 5 })]
//[Variation("5.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 5 })]
//[Variation("5.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 5 })]
//[Variation("6.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 6 })]
//[Variation("6.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 6 })]
//[Variation("6.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 6 })]
//[Variation("7.Parsing invalid DOCTYPE.Parse", Params = new object[] { DtdProcessing.Parse, 7 })]
//[Variation("7.Parsing invalid DOCTYPE.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 7 })]
//[Variation("7.Parsing invalid DOCTYPE.Ignore", Params = new object[] { DtdProcessing.Ignore, 7 })]
//[Variation("8.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 8 })]
//[Variation("8.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 8 })]
//[Variation("8.PParsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 8 })]
//[Variation("9.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 9 })]
//[Variation("9.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 9 })]
//[Variation("9.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 9 })]
//[Variation("10.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 10 })]
//[Variation("10.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 10 })]
//[Variation("10.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 10 })]
//[Variation("11.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 11 })]
//[Variation("11.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 11 })]
//[Variation("11.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 11 })]
//[Variation("12.Parsing invalid xml version.Parse", Params = new object[] { DtdProcessing.Parse, 12 })]
//[Variation("12.Parsing invalid xml version.Prohibit", Params = new object[] { DtdProcessing.Prohibit, 12 })]
//[Variation("12.Parsing invalid xml version.Ignore", Params = new object[] { DtdProcessing.Ignore, 12 })]
public int V19()
{
string xml = "";
switch ((int)CurVariation.Params[1])
{
case 1: xml = "<!DOCTYPE <"; break;
case 2: xml = "<!DOCTYPE root SYSTEM"; break;
case 3: xml = "<!DOCTYPE []<root/>"; break;
case 4: xml = "<!DOCTYPE root PUBLIC >]>"; break;
case 5: xml = "<!DOCTYPE "; break;
case 6: xml = "<!DOCTYPE >"; break;
case 7: xml = "<!DOCTYPE ["; break;
case 8: xml = " <?xml version=\"1.0\" ?>"; break;
case 9: xml = "<?xml version='1.0' ?><!DOCTYPE doc [ <!ELEMENT doc ANY >"; break;
case 10: xml = "< ?xml version=\"1.0\" ?>"; break;
case 11: xml = "<? xml version=\"1.0\" ?>"; break;
case 12: xml = "<?xml version = \" 1.0 \" ?>"; break;
}
string readerType = (string)this.Param;
XmlReaderSettings u = new XmlReaderSettings();
u.DtdProcessing = (DtdProcessing)this.CurVariation.Params[0];
XmlReader r = null;
try
{
r = ReaderHelper.CreateReader(readerType, new StringReader(xml), false, null, u);
while (r.Read()) ;
}
catch (XmlException)
{
if (r != null && r.Settings != null) CError.Compare(r.Settings.DtdProcessing, u.DtdProcessing, "error4");
return TEST_PASS;
}
return TEST_FAIL;
}
}
//[TestCase("Read xml as one byte stream.CoreReader", Param = "CoreReader")]
//[TestCase("Read xml as one byte stream.CharCheckingReader", Param = "CharCheckingReader")]
//[TestCase("Read xml as one byte stream.WrappedReader", Param = "WrappedReader")]
//[TestCase("Read xml as one byte stream.SubtreeReader", Param = "SubtreeReader")]
//[TestCase("Read xml as one byte stream.CoreValidatingReader", Param = "CoreValidatingReader")]
//[TestCase("Read xml as one byte stream.XsdValidatingReader", Param = "XsdValidatingReader")]
//[TestCase("Read xml as one byte stream.XsltReader", Param = "XsltReader")]
//[TestCase("Read xml as one byte stream.XmlValidatingReader", Param = "XmlValidatingReader")]
//[TestCase("Read xml as one byte stream.XmlNodeReader", Param = "XmlNodeReader")]
//[TestCase("Read xml as one byte stream.XPathNavigatorReader", Param = "XPathNavigatorReader")]
//[TestCase("Read xml as one byte stream.XmlTextReader", Param = "XmlTextReader")]
//[TestCase("Read xml as one byte stream.XmlBinaryReader", Param = "XmlBinaryReader")]
public partial class TCOneByteStream : TCXMLReaderBaseGeneral
{
[Variation("445370: Parsing this 'some]' as fragment fails with 'Unexpected EOF' error")]
public int v0()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
if (readerType == "SubtreeReader" || readerType == "XmlNodeReader") return TEST_SKIPPED;
OneByteStream sim = new OneByteStream(new byte[] { 0xFE, 0xFF, 0, (byte)'s', 0, (byte)'o',
0, (byte)'s', 0, (byte)'o', 0, (byte)'s', 0, (byte)'o', 0, (byte)'s', 0, (byte)'o',
0, (byte)']'});
XmlReaderSettings rs = new XmlReaderSettings();
rs.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader r = ReaderHelper.CreateReader(readerType, sim, null, false, null, rs, true))
{
while (r.Read()) { CError.WriteLine(r.Value); }
}
return TEST_PASS;
}
[Variation("445370a: Parsing this 'some]' as fragment fails with 'Unexpected EOF' error")]
public int v0a()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
if (readerType == "SubtreeReader" || readerType == "XmlNodeReader") return TEST_SKIPPED;
XmlReaderSettings rs = new XmlReaderSettings();
rs.ConformanceLevel = ConformanceLevel.Fragment;
string[] s = { "sosososo]", "sosososo]]", "sososos]o", "]", "[", "][", "[]", " ]]", "[[", "sosososo[", "sosososo[[", "Last char a square bracket. ]", ". ]" };
for (int i = 0; i < s.Length; i++)
{
CError.WriteLine(s[i]);
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(s[i]), false, null, rs, true))
{
r.Read();
CError.WriteLine(r.Value);
}
}
return TEST_PASS;
}
[Variation("Read as one byte stream xml with surrogate char")]
public int v1()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
string str = "<abc abc='\uD812\uDD12'>\uD812\uDD12</abc>";
byte[] bytes = Encoding.Unicode.GetBytes(str);
XmlReaderSettings rs = new XmlReaderSettings();
OneByteStream sim = new OneByteStream(bytes);
using (XmlReader r = ReaderHelper.CreateReader(readerType, sim, null, false, null, rs, false))
{
while (r.Read()) { CError.WriteLine(r.Value); }
return TEST_PASS;
}
}
[Variation("Read as TextReader xml with surrogate char")]
public int v1a()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
string str = "<abc abc='\uD812\uDD12'>\uD812\uDD12</abc>";
XmlReaderSettings rs = new XmlReaderSettings();
using (XmlReader r = ReaderHelper.CreateReader(readerType, new StringReader(str), false, null, rs, false))
{
while (r.Read()) { CError.WriteLine(r.Value); }
return TEST_PASS;
}
}
[Variation("XmlWriter.WriteNode: read as one byte stream xml with surrogate char")]
public int v2()
{
string readerType = (string)this.Param;
if (AsyncUtil.IsAsyncEnabled)
{
if (readerType == "XmlBinaryReader")
{
return TEST_SKIPPED;
}
}
string str = "<abc abc='\uD812\uDD12'>\uD812\uDD12</abc>";
string exp = "<?xml version=\"1.0\" encoding=\"utf-16\"?><abc abc=\"\U00014912\">\U00014912</abc>";
exp = (readerType == "XmlBinaryReader") ? "<?xml version=\"1.0\" encoding=\"utf-8\"?><abc abc=\"\U00014912\">\U00014912</abc>" : exp;
byte[] bytes = Encoding.Unicode.GetBytes(str);
XmlReaderSettings rs = new XmlReaderSettings();
OneByteStream sim = new OneByteStream(bytes);
using (XmlReader r = ReaderHelper.CreateReader(readerType, sim, null, false, null, rs, false))
{
using (StringWriter sw = new StringWriter())
{
using (XmlWriter w = WriterHelper.Create(sw))
{
w.WriteNode(r, false);
}
CError.Compare(sw.ToString(), exp, "writer output");
}
}
return TEST_PASS;
}
}
internal class OneByteStream : System.IO.Stream
{
private byte[] _input;
private int _pos;
public OneByteStream(byte[] input)
{
_input = input;
_pos = 0;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override void Flush()
{
throw new Exception("The method or operation is not implemented.");
}
public override long Length
{
get { return _input.Length; }
}
public override long Position
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public override int Read(byte[] buffer, int offset, int count)
{
int tocopy = count;
if (tocopy > _input.Length - _pos)
{
tocopy = _input.Length - _pos;
}
if (tocopy > 4)
{
tocopy = 4;
}
int i;
for (i = 0; i < tocopy; i++)
{
buffer[offset + i] = _input[_pos + i];
}
_pos += i;
return i;
}
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new Exception("The method or operation is not implemented.");
}
public override void SetLength(long value)
{
throw new Exception("The method or operation is not implemented.");
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new Exception("The method or operation is not implemented.");
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/Common/src/Interop/Windows/User32/Interop.WaitForInputIdle.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 User32
{
[GeneratedDllImport(Libraries.User32)]
public static partial int WaitForInputIdle(SafeProcessHandle handle, int milliseconds);
}
}
| // 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 User32
{
[GeneratedDllImport(Libraries.User32)]
public static partial int WaitForInputIdle(SafeProcessHandle handle, int milliseconds);
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/Loader/classloader/generics/Constraints/Regressions/ddb62403/bug62403.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
class TestClass
{
public static void N<U,V>() where U : V { }
public static void M<U,V>() where U : V
{
N<U,U>();
}
public static int Main()
{
try {
M<object,object>();
Console.WriteLine("PASS");
return 100;
} catch (Exception e)
{
Console.WriteLine("CATCH UNEXPECTED EXCEPTION: " + e.ToString());
Console.WriteLine("FAIL");
return 99;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
class TestClass
{
public static void N<U,V>() where U : V { }
public static void M<U,V>() where U : V
{
N<U,U>();
}
public static int Main()
{
try {
M<object,object>();
Console.WriteLine("PASS");
return 100;
} catch (Exception e)
{
Console.WriteLine("CATCH UNEXPECTED EXCEPTION: " + e.ToString());
Console.WriteLine("FAIL");
return 99;
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/jit64/gc/misc/struct1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
struct S
{
public String str;
}
class Test_struct1
{
public static void c(S s1)
{
GC.Collect();
Console.WriteLine(s1.str);
GC.Collect();
}
public static int Main()
{
S sM;
sM.str = "test";
c(sM);
return 100;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
struct S
{
public String str;
}
class Test_struct1
{
public static void c(S s1)
{
GC.Collect();
Console.WriteLine(s1.str);
GC.Collect();
}
public static int Main()
{
S sM;
sM.str = "test";
c(sM);
return 100;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/Methodical/explicit/coverage/body_short.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
internal class TestApp
{
private static short test_0_0(short num, AA init, AA zero)
{
return init.q;
}
private static short test_0_1(short num, AA init, AA zero)
{
zero.q = num;
return zero.q;
}
private static short test_0_2(short num, AA init, AA zero)
{
return (short)(init.q + zero.q);
}
private static short test_0_3(short num, AA init, AA zero)
{
return (short)checked(init.q - zero.q);
}
private static short test_0_4(short num, AA init, AA zero)
{
zero.q += num; return zero.q;
}
private static short test_0_5(short num, AA init, AA zero)
{
zero.q += init.q; return zero.q;
}
private static short test_0_6(short num, AA init, AA zero)
{
if (init.q == num)
return 100;
else
return zero.q;
}
private static short test_0_7(short num, AA init, AA zero)
{
return (short)(init.q < num + 1 ? 100 : -1);
}
private static short test_0_8(short num, AA init, AA zero)
{
return (short)((init.q > zero.q ? 1 : 0) + 99);
}
private static short test_0_9(short num, AA init, AA zero)
{
return (short)((init.q ^ zero.q) | num);
}
private static short test_0_10(short num, AA init, AA zero)
{
zero.q |= init.q;
return (short)(zero.q & num);
}
private static short test_0_11(short num, AA init, AA zero)
{
return (short)(init.q >> zero.q);
}
private static short test_0_12(short num, AA init, AA zero)
{
return AA.a_init[init.q].q;
}
private static short test_0_13(short num, AA init, AA zero)
{
return AA.aa_init[num - 100, (init.q | 1) - 2, 1 + zero.q].q;
}
private static short test_0_14(short num, AA init, AA zero)
{
object bb = init.q;
return (short)bb;
}
private static short test_0_15(short num, AA init, AA zero)
{
double dbl = init.q;
return (short)dbl;
}
private static short test_0_16(short num, AA init, AA zero)
{
return AA.call_target(init.q);
}
private static short test_0_17(short num, AA init, AA zero)
{
return AA.call_target_ref(ref init.q);
}
private static short test_1_0(short num, ref AA r_init, ref AA r_zero)
{
return r_init.q;
}
private static short test_1_1(short num, ref AA r_init, ref AA r_zero)
{
r_zero.q = num;
return r_zero.q;
}
private static short test_1_2(short num, ref AA r_init, ref AA r_zero)
{
return (short)(r_init.q + r_zero.q);
}
private static short test_1_3(short num, ref AA r_init, ref AA r_zero)
{
return (short)checked(r_init.q - r_zero.q);
}
private static short test_1_4(short num, ref AA r_init, ref AA r_zero)
{
r_zero.q += num; return r_zero.q;
}
private static short test_1_5(short num, ref AA r_init, ref AA r_zero)
{
r_zero.q += r_init.q; return r_zero.q;
}
private static short test_1_6(short num, ref AA r_init, ref AA r_zero)
{
if (r_init.q == num)
return 100;
else
return r_zero.q;
}
private static short test_1_7(short num, ref AA r_init, ref AA r_zero)
{
return (short)(r_init.q < num + 1 ? 100 : -1);
}
private static short test_1_8(short num, ref AA r_init, ref AA r_zero)
{
return (short)((r_init.q > r_zero.q ? 1 : 0) + 99);
}
private static short test_1_9(short num, ref AA r_init, ref AA r_zero)
{
return (short)((r_init.q ^ r_zero.q) | num);
}
private static short test_1_10(short num, ref AA r_init, ref AA r_zero)
{
r_zero.q |= r_init.q;
return (short)(r_zero.q & num);
}
private static short test_1_11(short num, ref AA r_init, ref AA r_zero)
{
return (short)(r_init.q >> r_zero.q);
}
private static short test_1_12(short num, ref AA r_init, ref AA r_zero)
{
return AA.a_init[r_init.q].q;
}
private static short test_1_13(short num, ref AA r_init, ref AA r_zero)
{
return AA.aa_init[num - 100, (r_init.q | 1) - 2, 1 + r_zero.q].q;
}
private static short test_1_14(short num, ref AA r_init, ref AA r_zero)
{
object bb = r_init.q;
return (short)bb;
}
private static short test_1_15(short num, ref AA r_init, ref AA r_zero)
{
double dbl = r_init.q;
return (short)dbl;
}
private static short test_1_16(short num, ref AA r_init, ref AA r_zero)
{
return AA.call_target(r_init.q);
}
private static short test_1_17(short num, ref AA r_init, ref AA r_zero)
{
return AA.call_target_ref(ref r_init.q);
}
private static short test_2_0(short num)
{
return AA.a_init[num].q;
}
private static short test_2_1(short num)
{
AA.a_zero[num].q = num;
return AA.a_zero[num].q;
}
private static short test_2_2(short num)
{
return (short)(AA.a_init[num].q + AA.a_zero[num].q);
}
private static short test_2_3(short num)
{
return (short)checked(AA.a_init[num].q - AA.a_zero[num].q);
}
private static short test_2_4(short num)
{
AA.a_zero[num].q += num; return AA.a_zero[num].q;
}
private static short test_2_5(short num)
{
AA.a_zero[num].q += AA.a_init[num].q; return AA.a_zero[num].q;
}
private static short test_2_6(short num)
{
if (AA.a_init[num].q == num)
return 100;
else
return AA.a_zero[num].q;
}
private static short test_2_7(short num)
{
return (short)(AA.a_init[num].q < num + 1 ? 100 : -1);
}
private static short test_2_8(short num)
{
return (short)((AA.a_init[num].q > AA.a_zero[num].q ? 1 : 0) + 99);
}
private static short test_2_9(short num)
{
return (short)((AA.a_init[num].q ^ AA.a_zero[num].q) | num);
}
private static short test_2_10(short num)
{
AA.a_zero[num].q |= AA.a_init[num].q;
return (short)(AA.a_zero[num].q & num);
}
private static short test_2_11(short num)
{
return (short)(AA.a_init[num].q >> AA.a_zero[num].q);
}
private static short test_2_12(short num)
{
return AA.a_init[AA.a_init[num].q].q;
}
private static short test_2_13(short num)
{
return AA.aa_init[num - 100, (AA.a_init[num].q | 1) - 2, 1 + AA.a_zero[num].q].q;
}
private static short test_2_14(short num)
{
object bb = AA.a_init[num].q;
return (short)bb;
}
private static short test_2_15(short num)
{
double dbl = AA.a_init[num].q;
return (short)dbl;
}
private static short test_2_16(short num)
{
return AA.call_target(AA.a_init[num].q);
}
private static short test_2_17(short num)
{
return AA.call_target_ref(ref AA.a_init[num].q);
}
private static short test_3_0(short num)
{
return AA.aa_init[0, num - 1, num / 100].q;
}
private static short test_3_1(short num)
{
AA.aa_zero[0, num - 1, num / 100].q = num;
return AA.aa_zero[0, num - 1, num / 100].q;
}
private static short test_3_2(short num)
{
return (short)(AA.aa_init[0, num - 1, num / 100].q + AA.aa_zero[0, num - 1, num / 100].q);
}
private static short test_3_3(short num)
{
return (short)checked(AA.aa_init[0, num - 1, num / 100].q - AA.aa_zero[0, num - 1, num / 100].q);
}
private static short test_3_4(short num)
{
AA.aa_zero[0, num - 1, num / 100].q += num; return AA.aa_zero[0, num - 1, num / 100].q;
}
private static short test_3_5(short num)
{
AA.aa_zero[0, num - 1, num / 100].q += AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q;
}
private static short test_3_6(short num)
{
if (AA.aa_init[0, num - 1, num / 100].q == num)
return 100;
else
return AA.aa_zero[0, num - 1, num / 100].q;
}
private static short test_3_7(short num)
{
return (short)(AA.aa_init[0, num - 1, num / 100].q < num + 1 ? 100 : -1);
}
private static short test_3_8(short num)
{
return (short)((AA.aa_init[0, num - 1, num / 100].q > AA.aa_zero[0, num - 1, num / 100].q ? 1 : 0) + 99);
}
private static short test_3_9(short num)
{
return (short)((AA.aa_init[0, num - 1, num / 100].q ^ AA.aa_zero[0, num - 1, num / 100].q) | num);
}
private static short test_3_10(short num)
{
AA.aa_zero[0, num - 1, num / 100].q |= AA.aa_init[0, num - 1, num / 100].q;
return (short)(AA.aa_zero[0, num - 1, num / 100].q & num);
}
private static short test_3_11(short num)
{
return (short)(AA.aa_init[0, num - 1, num / 100].q >> AA.aa_zero[0, num - 1, num / 100].q);
}
private static short test_3_12(short num)
{
return AA.a_init[AA.aa_init[0, num - 1, num / 100].q].q;
}
private static short test_3_13(short num)
{
return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q].q;
}
private static short test_3_14(short num)
{
object bb = AA.aa_init[0, num - 1, num / 100].q;
return (short)bb;
}
private static short test_3_15(short num)
{
double dbl = AA.aa_init[0, num - 1, num / 100].q;
return (short)dbl;
}
private static short test_3_16(short num)
{
return AA.call_target(AA.aa_init[0, num - 1, num / 100].q);
}
private static short test_3_17(short num)
{
return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q);
}
private static short test_4_0(short num)
{
return BB.f_init.q;
}
private static short test_4_1(short num)
{
BB.f_zero.q = num;
return BB.f_zero.q;
}
private static short test_4_2(short num)
{
return (short)(BB.f_init.q + BB.f_zero.q);
}
private static short test_4_3(short num)
{
return (short)checked(BB.f_init.q - BB.f_zero.q);
}
private static short test_4_4(short num)
{
BB.f_zero.q += num; return BB.f_zero.q;
}
private static short test_4_5(short num)
{
BB.f_zero.q += BB.f_init.q; return BB.f_zero.q;
}
private static short test_4_6(short num)
{
if (BB.f_init.q == num)
return 100;
else
return BB.f_zero.q;
}
private static short test_4_7(short num)
{
return (short)(BB.f_init.q < num + 1 ? 100 : -1);
}
private static short test_4_8(short num)
{
return (short)((BB.f_init.q > BB.f_zero.q ? 1 : 0) + 99);
}
private static short test_4_9(short num)
{
return (short)((BB.f_init.q ^ BB.f_zero.q) | num);
}
private static short test_4_10(short num)
{
BB.f_zero.q |= BB.f_init.q;
return (short)(BB.f_zero.q & num);
}
private static short test_4_11(short num)
{
return (short)(BB.f_init.q >> BB.f_zero.q);
}
private static short test_4_12(short num)
{
return AA.a_init[BB.f_init.q].q;
}
private static short test_4_13(short num)
{
return AA.aa_init[num - 100, (BB.f_init.q | 1) - 2, 1 + BB.f_zero.q].q;
}
private static short test_4_14(short num)
{
object bb = BB.f_init.q;
return (short)bb;
}
private static short test_4_15(short num)
{
double dbl = BB.f_init.q;
return (short)dbl;
}
private static short test_4_16(short num)
{
return AA.call_target(BB.f_init.q);
}
private static short test_4_17(short num)
{
return AA.call_target_ref(ref BB.f_init.q);
}
private static short test_5_0(short num)
{
return ((AA)AA.b_init).q;
}
private static short test_6_0(short num, TypedReference tr_init)
{
return __refvalue(tr_init, AA).q;
}
private static unsafe short test_7_0(short num, void* ptr_init, void* ptr_zero)
{
return (*((AA*)ptr_init)).q;
}
private static unsafe short test_7_1(short num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q = num;
return (*((AA*)ptr_zero)).q;
}
private static unsafe short test_7_2(short num, void* ptr_init, void* ptr_zero)
{
return (short)((*((AA*)ptr_init)).q + (*((AA*)ptr_zero)).q);
}
private static unsafe short test_7_3(short num, void* ptr_init, void* ptr_zero)
{
return (short)checked((*((AA*)ptr_init)).q - (*((AA*)ptr_zero)).q);
}
private static unsafe short test_7_4(short num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q += num; return (*((AA*)ptr_zero)).q;
}
private static unsafe short test_7_5(short num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q += (*((AA*)ptr_init)).q; return (*((AA*)ptr_zero)).q;
}
private static unsafe short test_7_6(short num, void* ptr_init, void* ptr_zero)
{
if ((*((AA*)ptr_init)).q == num)
return 100;
else
return (*((AA*)ptr_zero)).q;
}
private static unsafe short test_7_7(short num, void* ptr_init, void* ptr_zero)
{
return (short)((*((AA*)ptr_init)).q < num + 1 ? 100 : -1);
}
private static unsafe short test_7_8(short num, void* ptr_init, void* ptr_zero)
{
return (short)(((*((AA*)ptr_init)).q > (*((AA*)ptr_zero)).q ? 1 : 0) + 99);
}
private static unsafe short test_7_9(short num, void* ptr_init, void* ptr_zero)
{
return (short)(((*((AA*)ptr_init)).q ^ (*((AA*)ptr_zero)).q) | num);
}
private static unsafe short test_7_10(short num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q |= (*((AA*)ptr_init)).q;
return (short)((*((AA*)ptr_zero)).q & num);
}
private static unsafe short test_7_11(short num, void* ptr_init, void* ptr_zero)
{
return (short)((*((AA*)ptr_init)).q >> (*((AA*)ptr_zero)).q);
}
private static unsafe short test_7_12(short num, void* ptr_init, void* ptr_zero)
{
return AA.a_init[(*((AA*)ptr_init)).q].q;
}
private static unsafe short test_7_13(short num, void* ptr_init, void* ptr_zero)
{
return AA.aa_init[num - 100, ((*((AA*)ptr_init)).q | 1) - 2, 1 + (*((AA*)ptr_zero)).q].q;
}
private static unsafe short test_7_14(short num, void* ptr_init, void* ptr_zero)
{
object bb = (*((AA*)ptr_init)).q;
return (short)bb;
}
private static unsafe short test_7_15(short num, void* ptr_init, void* ptr_zero)
{
double dbl = (*((AA*)ptr_init)).q;
return (short)dbl;
}
private static unsafe short test_7_16(short num, void* ptr_init, void* ptr_zero)
{
return AA.call_target((*((AA*)ptr_init)).q);
}
private static unsafe short test_7_17(short num, void* ptr_init, void* ptr_zero)
{
return AA.call_target_ref(ref (*((AA*)ptr_init)).q);
}
internal static unsafe int RunAllTests()
{
AA.reset();
if (test_0_0(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_0() failed.");
return 101;
}
AA.verify_all(); AA.reset();
if (test_0_1(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_1() failed.");
return 102;
}
AA.verify_all(); AA.reset();
if (test_0_2(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_2() failed.");
return 103;
}
AA.verify_all(); AA.reset();
if (test_0_3(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_3() failed.");
return 104;
}
AA.verify_all(); AA.reset();
if (test_0_4(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_4() failed.");
return 105;
}
AA.verify_all(); AA.reset();
if (test_0_5(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_5() failed.");
return 106;
}
AA.verify_all(); AA.reset();
if (test_0_6(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_6() failed.");
return 107;
}
AA.verify_all(); AA.reset();
if (test_0_7(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_7() failed.");
return 108;
}
AA.verify_all(); AA.reset();
if (test_0_8(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_8() failed.");
return 109;
}
AA.verify_all(); AA.reset();
if (test_0_9(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_9() failed.");
return 110;
}
AA.verify_all(); AA.reset();
if (test_0_10(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_10() failed.");
return 111;
}
AA.verify_all(); AA.reset();
if (test_0_11(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_11() failed.");
return 112;
}
AA.verify_all(); AA.reset();
if (test_0_12(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_12() failed.");
return 113;
}
AA.verify_all(); AA.reset();
if (test_0_13(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_13() failed.");
return 114;
}
AA.verify_all(); AA.reset();
if (test_0_14(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_14() failed.");
return 115;
}
AA.verify_all(); AA.reset();
if (test_0_15(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_15() failed.");
return 116;
}
AA.verify_all(); AA.reset();
if (test_0_16(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_16() failed.");
return 117;
}
AA.verify_all(); AA.reset();
if (test_0_17(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_17() failed.");
return 118;
}
AA.verify_all(); AA.reset();
if (test_1_0(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_0() failed.");
return 119;
}
AA.verify_all(); AA.reset();
if (test_1_1(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_1() failed.");
return 120;
}
AA.verify_all(); AA.reset();
if (test_1_2(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_2() failed.");
return 121;
}
AA.verify_all(); AA.reset();
if (test_1_3(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_3() failed.");
return 122;
}
AA.verify_all(); AA.reset();
if (test_1_4(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_4() failed.");
return 123;
}
AA.verify_all(); AA.reset();
if (test_1_5(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_5() failed.");
return 124;
}
AA.verify_all(); AA.reset();
if (test_1_6(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_6() failed.");
return 125;
}
AA.verify_all(); AA.reset();
if (test_1_7(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_7() failed.");
return 126;
}
AA.verify_all(); AA.reset();
if (test_1_8(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_8() failed.");
return 127;
}
AA.verify_all(); AA.reset();
if (test_1_9(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_9() failed.");
return 128;
}
AA.verify_all(); AA.reset();
if (test_1_10(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_10() failed.");
return 129;
}
AA.verify_all(); AA.reset();
if (test_1_11(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_11() failed.");
return 130;
}
AA.verify_all(); AA.reset();
if (test_1_12(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_12() failed.");
return 131;
}
AA.verify_all(); AA.reset();
if (test_1_13(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_13() failed.");
return 132;
}
AA.verify_all(); AA.reset();
if (test_1_14(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_14() failed.");
return 133;
}
AA.verify_all(); AA.reset();
if (test_1_15(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_15() failed.");
return 134;
}
AA.verify_all(); AA.reset();
if (test_1_16(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_16() failed.");
return 135;
}
AA.verify_all(); AA.reset();
if (test_1_17(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_17() failed.");
return 136;
}
AA.verify_all(); AA.reset();
if (test_2_0(100) != 100)
{
Console.WriteLine("test_2_0() failed.");
return 137;
}
AA.verify_all(); AA.reset();
if (test_2_1(100) != 100)
{
Console.WriteLine("test_2_1() failed.");
return 138;
}
AA.verify_all(); AA.reset();
if (test_2_2(100) != 100)
{
Console.WriteLine("test_2_2() failed.");
return 139;
}
AA.verify_all(); AA.reset();
if (test_2_3(100) != 100)
{
Console.WriteLine("test_2_3() failed.");
return 140;
}
AA.verify_all(); AA.reset();
if (test_2_4(100) != 100)
{
Console.WriteLine("test_2_4() failed.");
return 141;
}
AA.verify_all(); AA.reset();
if (test_2_5(100) != 100)
{
Console.WriteLine("test_2_5() failed.");
return 142;
}
AA.verify_all(); AA.reset();
if (test_2_6(100) != 100)
{
Console.WriteLine("test_2_6() failed.");
return 143;
}
AA.verify_all(); AA.reset();
if (test_2_7(100) != 100)
{
Console.WriteLine("test_2_7() failed.");
return 144;
}
AA.verify_all(); AA.reset();
if (test_2_8(100) != 100)
{
Console.WriteLine("test_2_8() failed.");
return 145;
}
AA.verify_all(); AA.reset();
if (test_2_9(100) != 100)
{
Console.WriteLine("test_2_9() failed.");
return 146;
}
AA.verify_all(); AA.reset();
if (test_2_10(100) != 100)
{
Console.WriteLine("test_2_10() failed.");
return 147;
}
AA.verify_all(); AA.reset();
if (test_2_11(100) != 100)
{
Console.WriteLine("test_2_11() failed.");
return 148;
}
AA.verify_all(); AA.reset();
if (test_2_12(100) != 100)
{
Console.WriteLine("test_2_12() failed.");
return 149;
}
AA.verify_all(); AA.reset();
if (test_2_13(100) != 100)
{
Console.WriteLine("test_2_13() failed.");
return 150;
}
AA.verify_all(); AA.reset();
if (test_2_14(100) != 100)
{
Console.WriteLine("test_2_14() failed.");
return 151;
}
AA.verify_all(); AA.reset();
if (test_2_15(100) != 100)
{
Console.WriteLine("test_2_15() failed.");
return 152;
}
AA.verify_all(); AA.reset();
if (test_2_16(100) != 100)
{
Console.WriteLine("test_2_16() failed.");
return 153;
}
AA.verify_all(); AA.reset();
if (test_2_17(100) != 100)
{
Console.WriteLine("test_2_17() failed.");
return 154;
}
AA.verify_all(); AA.reset();
if (test_3_0(100) != 100)
{
Console.WriteLine("test_3_0() failed.");
return 155;
}
AA.verify_all(); AA.reset();
if (test_3_1(100) != 100)
{
Console.WriteLine("test_3_1() failed.");
return 156;
}
AA.verify_all(); AA.reset();
if (test_3_2(100) != 100)
{
Console.WriteLine("test_3_2() failed.");
return 157;
}
AA.verify_all(); AA.reset();
if (test_3_3(100) != 100)
{
Console.WriteLine("test_3_3() failed.");
return 158;
}
AA.verify_all(); AA.reset();
if (test_3_4(100) != 100)
{
Console.WriteLine("test_3_4() failed.");
return 159;
}
AA.verify_all(); AA.reset();
if (test_3_5(100) != 100)
{
Console.WriteLine("test_3_5() failed.");
return 160;
}
AA.verify_all(); AA.reset();
if (test_3_6(100) != 100)
{
Console.WriteLine("test_3_6() failed.");
return 161;
}
AA.verify_all(); AA.reset();
if (test_3_7(100) != 100)
{
Console.WriteLine("test_3_7() failed.");
return 162;
}
AA.verify_all(); AA.reset();
if (test_3_8(100) != 100)
{
Console.WriteLine("test_3_8() failed.");
return 163;
}
AA.verify_all(); AA.reset();
if (test_3_9(100) != 100)
{
Console.WriteLine("test_3_9() failed.");
return 164;
}
AA.verify_all(); AA.reset();
if (test_3_10(100) != 100)
{
Console.WriteLine("test_3_10() failed.");
return 165;
}
AA.verify_all(); AA.reset();
if (test_3_11(100) != 100)
{
Console.WriteLine("test_3_11() failed.");
return 166;
}
AA.verify_all(); AA.reset();
if (test_3_12(100) != 100)
{
Console.WriteLine("test_3_12() failed.");
return 167;
}
AA.verify_all(); AA.reset();
if (test_3_13(100) != 100)
{
Console.WriteLine("test_3_13() failed.");
return 168;
}
AA.verify_all(); AA.reset();
if (test_3_14(100) != 100)
{
Console.WriteLine("test_3_14() failed.");
return 169;
}
AA.verify_all(); AA.reset();
if (test_3_15(100) != 100)
{
Console.WriteLine("test_3_15() failed.");
return 170;
}
AA.verify_all(); AA.reset();
if (test_3_16(100) != 100)
{
Console.WriteLine("test_3_16() failed.");
return 171;
}
AA.verify_all(); AA.reset();
if (test_3_17(100) != 100)
{
Console.WriteLine("test_3_17() failed.");
return 172;
}
AA.verify_all(); AA.reset();
if (test_4_0(100) != 100)
{
Console.WriteLine("test_4_0() failed.");
return 173;
}
AA.verify_all(); AA.reset();
if (test_4_1(100) != 100)
{
Console.WriteLine("test_4_1() failed.");
return 174;
}
AA.verify_all(); AA.reset();
if (test_4_2(100) != 100)
{
Console.WriteLine("test_4_2() failed.");
return 175;
}
AA.verify_all(); AA.reset();
if (test_4_3(100) != 100)
{
Console.WriteLine("test_4_3() failed.");
return 176;
}
AA.verify_all(); AA.reset();
if (test_4_4(100) != 100)
{
Console.WriteLine("test_4_4() failed.");
return 177;
}
AA.verify_all(); AA.reset();
if (test_4_5(100) != 100)
{
Console.WriteLine("test_4_5() failed.");
return 178;
}
AA.verify_all(); AA.reset();
if (test_4_6(100) != 100)
{
Console.WriteLine("test_4_6() failed.");
return 179;
}
AA.verify_all(); AA.reset();
if (test_4_7(100) != 100)
{
Console.WriteLine("test_4_7() failed.");
return 180;
}
AA.verify_all(); AA.reset();
if (test_4_8(100) != 100)
{
Console.WriteLine("test_4_8() failed.");
return 181;
}
AA.verify_all(); AA.reset();
if (test_4_9(100) != 100)
{
Console.WriteLine("test_4_9() failed.");
return 182;
}
AA.verify_all(); AA.reset();
if (test_4_10(100) != 100)
{
Console.WriteLine("test_4_10() failed.");
return 183;
}
AA.verify_all(); AA.reset();
if (test_4_11(100) != 100)
{
Console.WriteLine("test_4_11() failed.");
return 184;
}
AA.verify_all(); AA.reset();
if (test_4_12(100) != 100)
{
Console.WriteLine("test_4_12() failed.");
return 185;
}
AA.verify_all(); AA.reset();
if (test_4_13(100) != 100)
{
Console.WriteLine("test_4_13() failed.");
return 186;
}
AA.verify_all(); AA.reset();
if (test_4_14(100) != 100)
{
Console.WriteLine("test_4_14() failed.");
return 187;
}
AA.verify_all(); AA.reset();
if (test_4_15(100) != 100)
{
Console.WriteLine("test_4_15() failed.");
return 188;
}
AA.verify_all(); AA.reset();
if (test_4_16(100) != 100)
{
Console.WriteLine("test_4_16() failed.");
return 189;
}
AA.verify_all(); AA.reset();
if (test_4_17(100) != 100)
{
Console.WriteLine("test_4_17() failed.");
return 190;
}
AA.verify_all(); AA.reset();
if (test_5_0(100) != 100)
{
Console.WriteLine("test_5_0() failed.");
return 191;
}
AA.verify_all(); AA.reset();
if (test_6_0(100, __makeref(AA._init)) != 100)
{
Console.WriteLine("test_6_0() failed.");
return 192;
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_0(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_0() failed.");
return 193;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_1(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_1() failed.");
return 194;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_2(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_2() failed.");
return 195;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_3(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_3() failed.");
return 196;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_4(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_4() failed.");
return 197;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_5(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_5() failed.");
return 198;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_6(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_6() failed.");
return 199;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_7(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_7() failed.");
return 200;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_8(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_8() failed.");
return 201;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_9(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_9() failed.");
return 202;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_10(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_10() failed.");
return 203;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_11(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_11() failed.");
return 204;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_12(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_12() failed.");
return 205;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_13(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_13() failed.");
return 206;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_14(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_14() failed.");
return 207;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_15(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_15() failed.");
return 208;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_16(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_16() failed.");
return 209;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_17(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_17() failed.");
return 210;
}
}
AA.verify_all(); Console.WriteLine("All tests passed.");
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;
internal class TestApp
{
private static short test_0_0(short num, AA init, AA zero)
{
return init.q;
}
private static short test_0_1(short num, AA init, AA zero)
{
zero.q = num;
return zero.q;
}
private static short test_0_2(short num, AA init, AA zero)
{
return (short)(init.q + zero.q);
}
private static short test_0_3(short num, AA init, AA zero)
{
return (short)checked(init.q - zero.q);
}
private static short test_0_4(short num, AA init, AA zero)
{
zero.q += num; return zero.q;
}
private static short test_0_5(short num, AA init, AA zero)
{
zero.q += init.q; return zero.q;
}
private static short test_0_6(short num, AA init, AA zero)
{
if (init.q == num)
return 100;
else
return zero.q;
}
private static short test_0_7(short num, AA init, AA zero)
{
return (short)(init.q < num + 1 ? 100 : -1);
}
private static short test_0_8(short num, AA init, AA zero)
{
return (short)((init.q > zero.q ? 1 : 0) + 99);
}
private static short test_0_9(short num, AA init, AA zero)
{
return (short)((init.q ^ zero.q) | num);
}
private static short test_0_10(short num, AA init, AA zero)
{
zero.q |= init.q;
return (short)(zero.q & num);
}
private static short test_0_11(short num, AA init, AA zero)
{
return (short)(init.q >> zero.q);
}
private static short test_0_12(short num, AA init, AA zero)
{
return AA.a_init[init.q].q;
}
private static short test_0_13(short num, AA init, AA zero)
{
return AA.aa_init[num - 100, (init.q | 1) - 2, 1 + zero.q].q;
}
private static short test_0_14(short num, AA init, AA zero)
{
object bb = init.q;
return (short)bb;
}
private static short test_0_15(short num, AA init, AA zero)
{
double dbl = init.q;
return (short)dbl;
}
private static short test_0_16(short num, AA init, AA zero)
{
return AA.call_target(init.q);
}
private static short test_0_17(short num, AA init, AA zero)
{
return AA.call_target_ref(ref init.q);
}
private static short test_1_0(short num, ref AA r_init, ref AA r_zero)
{
return r_init.q;
}
private static short test_1_1(short num, ref AA r_init, ref AA r_zero)
{
r_zero.q = num;
return r_zero.q;
}
private static short test_1_2(short num, ref AA r_init, ref AA r_zero)
{
return (short)(r_init.q + r_zero.q);
}
private static short test_1_3(short num, ref AA r_init, ref AA r_zero)
{
return (short)checked(r_init.q - r_zero.q);
}
private static short test_1_4(short num, ref AA r_init, ref AA r_zero)
{
r_zero.q += num; return r_zero.q;
}
private static short test_1_5(short num, ref AA r_init, ref AA r_zero)
{
r_zero.q += r_init.q; return r_zero.q;
}
private static short test_1_6(short num, ref AA r_init, ref AA r_zero)
{
if (r_init.q == num)
return 100;
else
return r_zero.q;
}
private static short test_1_7(short num, ref AA r_init, ref AA r_zero)
{
return (short)(r_init.q < num + 1 ? 100 : -1);
}
private static short test_1_8(short num, ref AA r_init, ref AA r_zero)
{
return (short)((r_init.q > r_zero.q ? 1 : 0) + 99);
}
private static short test_1_9(short num, ref AA r_init, ref AA r_zero)
{
return (short)((r_init.q ^ r_zero.q) | num);
}
private static short test_1_10(short num, ref AA r_init, ref AA r_zero)
{
r_zero.q |= r_init.q;
return (short)(r_zero.q & num);
}
private static short test_1_11(short num, ref AA r_init, ref AA r_zero)
{
return (short)(r_init.q >> r_zero.q);
}
private static short test_1_12(short num, ref AA r_init, ref AA r_zero)
{
return AA.a_init[r_init.q].q;
}
private static short test_1_13(short num, ref AA r_init, ref AA r_zero)
{
return AA.aa_init[num - 100, (r_init.q | 1) - 2, 1 + r_zero.q].q;
}
private static short test_1_14(short num, ref AA r_init, ref AA r_zero)
{
object bb = r_init.q;
return (short)bb;
}
private static short test_1_15(short num, ref AA r_init, ref AA r_zero)
{
double dbl = r_init.q;
return (short)dbl;
}
private static short test_1_16(short num, ref AA r_init, ref AA r_zero)
{
return AA.call_target(r_init.q);
}
private static short test_1_17(short num, ref AA r_init, ref AA r_zero)
{
return AA.call_target_ref(ref r_init.q);
}
private static short test_2_0(short num)
{
return AA.a_init[num].q;
}
private static short test_2_1(short num)
{
AA.a_zero[num].q = num;
return AA.a_zero[num].q;
}
private static short test_2_2(short num)
{
return (short)(AA.a_init[num].q + AA.a_zero[num].q);
}
private static short test_2_3(short num)
{
return (short)checked(AA.a_init[num].q - AA.a_zero[num].q);
}
private static short test_2_4(short num)
{
AA.a_zero[num].q += num; return AA.a_zero[num].q;
}
private static short test_2_5(short num)
{
AA.a_zero[num].q += AA.a_init[num].q; return AA.a_zero[num].q;
}
private static short test_2_6(short num)
{
if (AA.a_init[num].q == num)
return 100;
else
return AA.a_zero[num].q;
}
private static short test_2_7(short num)
{
return (short)(AA.a_init[num].q < num + 1 ? 100 : -1);
}
private static short test_2_8(short num)
{
return (short)((AA.a_init[num].q > AA.a_zero[num].q ? 1 : 0) + 99);
}
private static short test_2_9(short num)
{
return (short)((AA.a_init[num].q ^ AA.a_zero[num].q) | num);
}
private static short test_2_10(short num)
{
AA.a_zero[num].q |= AA.a_init[num].q;
return (short)(AA.a_zero[num].q & num);
}
private static short test_2_11(short num)
{
return (short)(AA.a_init[num].q >> AA.a_zero[num].q);
}
private static short test_2_12(short num)
{
return AA.a_init[AA.a_init[num].q].q;
}
private static short test_2_13(short num)
{
return AA.aa_init[num - 100, (AA.a_init[num].q | 1) - 2, 1 + AA.a_zero[num].q].q;
}
private static short test_2_14(short num)
{
object bb = AA.a_init[num].q;
return (short)bb;
}
private static short test_2_15(short num)
{
double dbl = AA.a_init[num].q;
return (short)dbl;
}
private static short test_2_16(short num)
{
return AA.call_target(AA.a_init[num].q);
}
private static short test_2_17(short num)
{
return AA.call_target_ref(ref AA.a_init[num].q);
}
private static short test_3_0(short num)
{
return AA.aa_init[0, num - 1, num / 100].q;
}
private static short test_3_1(short num)
{
AA.aa_zero[0, num - 1, num / 100].q = num;
return AA.aa_zero[0, num - 1, num / 100].q;
}
private static short test_3_2(short num)
{
return (short)(AA.aa_init[0, num - 1, num / 100].q + AA.aa_zero[0, num - 1, num / 100].q);
}
private static short test_3_3(short num)
{
return (short)checked(AA.aa_init[0, num - 1, num / 100].q - AA.aa_zero[0, num - 1, num / 100].q);
}
private static short test_3_4(short num)
{
AA.aa_zero[0, num - 1, num / 100].q += num; return AA.aa_zero[0, num - 1, num / 100].q;
}
private static short test_3_5(short num)
{
AA.aa_zero[0, num - 1, num / 100].q += AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q;
}
private static short test_3_6(short num)
{
if (AA.aa_init[0, num - 1, num / 100].q == num)
return 100;
else
return AA.aa_zero[0, num - 1, num / 100].q;
}
private static short test_3_7(short num)
{
return (short)(AA.aa_init[0, num - 1, num / 100].q < num + 1 ? 100 : -1);
}
private static short test_3_8(short num)
{
return (short)((AA.aa_init[0, num - 1, num / 100].q > AA.aa_zero[0, num - 1, num / 100].q ? 1 : 0) + 99);
}
private static short test_3_9(short num)
{
return (short)((AA.aa_init[0, num - 1, num / 100].q ^ AA.aa_zero[0, num - 1, num / 100].q) | num);
}
private static short test_3_10(short num)
{
AA.aa_zero[0, num - 1, num / 100].q |= AA.aa_init[0, num - 1, num / 100].q;
return (short)(AA.aa_zero[0, num - 1, num / 100].q & num);
}
private static short test_3_11(short num)
{
return (short)(AA.aa_init[0, num - 1, num / 100].q >> AA.aa_zero[0, num - 1, num / 100].q);
}
private static short test_3_12(short num)
{
return AA.a_init[AA.aa_init[0, num - 1, num / 100].q].q;
}
private static short test_3_13(short num)
{
return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q].q;
}
private static short test_3_14(short num)
{
object bb = AA.aa_init[0, num - 1, num / 100].q;
return (short)bb;
}
private static short test_3_15(short num)
{
double dbl = AA.aa_init[0, num - 1, num / 100].q;
return (short)dbl;
}
private static short test_3_16(short num)
{
return AA.call_target(AA.aa_init[0, num - 1, num / 100].q);
}
private static short test_3_17(short num)
{
return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q);
}
private static short test_4_0(short num)
{
return BB.f_init.q;
}
private static short test_4_1(short num)
{
BB.f_zero.q = num;
return BB.f_zero.q;
}
private static short test_4_2(short num)
{
return (short)(BB.f_init.q + BB.f_zero.q);
}
private static short test_4_3(short num)
{
return (short)checked(BB.f_init.q - BB.f_zero.q);
}
private static short test_4_4(short num)
{
BB.f_zero.q += num; return BB.f_zero.q;
}
private static short test_4_5(short num)
{
BB.f_zero.q += BB.f_init.q; return BB.f_zero.q;
}
private static short test_4_6(short num)
{
if (BB.f_init.q == num)
return 100;
else
return BB.f_zero.q;
}
private static short test_4_7(short num)
{
return (short)(BB.f_init.q < num + 1 ? 100 : -1);
}
private static short test_4_8(short num)
{
return (short)((BB.f_init.q > BB.f_zero.q ? 1 : 0) + 99);
}
private static short test_4_9(short num)
{
return (short)((BB.f_init.q ^ BB.f_zero.q) | num);
}
private static short test_4_10(short num)
{
BB.f_zero.q |= BB.f_init.q;
return (short)(BB.f_zero.q & num);
}
private static short test_4_11(short num)
{
return (short)(BB.f_init.q >> BB.f_zero.q);
}
private static short test_4_12(short num)
{
return AA.a_init[BB.f_init.q].q;
}
private static short test_4_13(short num)
{
return AA.aa_init[num - 100, (BB.f_init.q | 1) - 2, 1 + BB.f_zero.q].q;
}
private static short test_4_14(short num)
{
object bb = BB.f_init.q;
return (short)bb;
}
private static short test_4_15(short num)
{
double dbl = BB.f_init.q;
return (short)dbl;
}
private static short test_4_16(short num)
{
return AA.call_target(BB.f_init.q);
}
private static short test_4_17(short num)
{
return AA.call_target_ref(ref BB.f_init.q);
}
private static short test_5_0(short num)
{
return ((AA)AA.b_init).q;
}
private static short test_6_0(short num, TypedReference tr_init)
{
return __refvalue(tr_init, AA).q;
}
private static unsafe short test_7_0(short num, void* ptr_init, void* ptr_zero)
{
return (*((AA*)ptr_init)).q;
}
private static unsafe short test_7_1(short num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q = num;
return (*((AA*)ptr_zero)).q;
}
private static unsafe short test_7_2(short num, void* ptr_init, void* ptr_zero)
{
return (short)((*((AA*)ptr_init)).q + (*((AA*)ptr_zero)).q);
}
private static unsafe short test_7_3(short num, void* ptr_init, void* ptr_zero)
{
return (short)checked((*((AA*)ptr_init)).q - (*((AA*)ptr_zero)).q);
}
private static unsafe short test_7_4(short num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q += num; return (*((AA*)ptr_zero)).q;
}
private static unsafe short test_7_5(short num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q += (*((AA*)ptr_init)).q; return (*((AA*)ptr_zero)).q;
}
private static unsafe short test_7_6(short num, void* ptr_init, void* ptr_zero)
{
if ((*((AA*)ptr_init)).q == num)
return 100;
else
return (*((AA*)ptr_zero)).q;
}
private static unsafe short test_7_7(short num, void* ptr_init, void* ptr_zero)
{
return (short)((*((AA*)ptr_init)).q < num + 1 ? 100 : -1);
}
private static unsafe short test_7_8(short num, void* ptr_init, void* ptr_zero)
{
return (short)(((*((AA*)ptr_init)).q > (*((AA*)ptr_zero)).q ? 1 : 0) + 99);
}
private static unsafe short test_7_9(short num, void* ptr_init, void* ptr_zero)
{
return (short)(((*((AA*)ptr_init)).q ^ (*((AA*)ptr_zero)).q) | num);
}
private static unsafe short test_7_10(short num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q |= (*((AA*)ptr_init)).q;
return (short)((*((AA*)ptr_zero)).q & num);
}
private static unsafe short test_7_11(short num, void* ptr_init, void* ptr_zero)
{
return (short)((*((AA*)ptr_init)).q >> (*((AA*)ptr_zero)).q);
}
private static unsafe short test_7_12(short num, void* ptr_init, void* ptr_zero)
{
return AA.a_init[(*((AA*)ptr_init)).q].q;
}
private static unsafe short test_7_13(short num, void* ptr_init, void* ptr_zero)
{
return AA.aa_init[num - 100, ((*((AA*)ptr_init)).q | 1) - 2, 1 + (*((AA*)ptr_zero)).q].q;
}
private static unsafe short test_7_14(short num, void* ptr_init, void* ptr_zero)
{
object bb = (*((AA*)ptr_init)).q;
return (short)bb;
}
private static unsafe short test_7_15(short num, void* ptr_init, void* ptr_zero)
{
double dbl = (*((AA*)ptr_init)).q;
return (short)dbl;
}
private static unsafe short test_7_16(short num, void* ptr_init, void* ptr_zero)
{
return AA.call_target((*((AA*)ptr_init)).q);
}
private static unsafe short test_7_17(short num, void* ptr_init, void* ptr_zero)
{
return AA.call_target_ref(ref (*((AA*)ptr_init)).q);
}
internal static unsafe int RunAllTests()
{
AA.reset();
if (test_0_0(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_0() failed.");
return 101;
}
AA.verify_all(); AA.reset();
if (test_0_1(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_1() failed.");
return 102;
}
AA.verify_all(); AA.reset();
if (test_0_2(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_2() failed.");
return 103;
}
AA.verify_all(); AA.reset();
if (test_0_3(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_3() failed.");
return 104;
}
AA.verify_all(); AA.reset();
if (test_0_4(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_4() failed.");
return 105;
}
AA.verify_all(); AA.reset();
if (test_0_5(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_5() failed.");
return 106;
}
AA.verify_all(); AA.reset();
if (test_0_6(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_6() failed.");
return 107;
}
AA.verify_all(); AA.reset();
if (test_0_7(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_7() failed.");
return 108;
}
AA.verify_all(); AA.reset();
if (test_0_8(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_8() failed.");
return 109;
}
AA.verify_all(); AA.reset();
if (test_0_9(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_9() failed.");
return 110;
}
AA.verify_all(); AA.reset();
if (test_0_10(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_10() failed.");
return 111;
}
AA.verify_all(); AA.reset();
if (test_0_11(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_11() failed.");
return 112;
}
AA.verify_all(); AA.reset();
if (test_0_12(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_12() failed.");
return 113;
}
AA.verify_all(); AA.reset();
if (test_0_13(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_13() failed.");
return 114;
}
AA.verify_all(); AA.reset();
if (test_0_14(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_14() failed.");
return 115;
}
AA.verify_all(); AA.reset();
if (test_0_15(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_15() failed.");
return 116;
}
AA.verify_all(); AA.reset();
if (test_0_16(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_16() failed.");
return 117;
}
AA.verify_all(); AA.reset();
if (test_0_17(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_17() failed.");
return 118;
}
AA.verify_all(); AA.reset();
if (test_1_0(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_0() failed.");
return 119;
}
AA.verify_all(); AA.reset();
if (test_1_1(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_1() failed.");
return 120;
}
AA.verify_all(); AA.reset();
if (test_1_2(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_2() failed.");
return 121;
}
AA.verify_all(); AA.reset();
if (test_1_3(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_3() failed.");
return 122;
}
AA.verify_all(); AA.reset();
if (test_1_4(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_4() failed.");
return 123;
}
AA.verify_all(); AA.reset();
if (test_1_5(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_5() failed.");
return 124;
}
AA.verify_all(); AA.reset();
if (test_1_6(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_6() failed.");
return 125;
}
AA.verify_all(); AA.reset();
if (test_1_7(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_7() failed.");
return 126;
}
AA.verify_all(); AA.reset();
if (test_1_8(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_8() failed.");
return 127;
}
AA.verify_all(); AA.reset();
if (test_1_9(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_9() failed.");
return 128;
}
AA.verify_all(); AA.reset();
if (test_1_10(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_10() failed.");
return 129;
}
AA.verify_all(); AA.reset();
if (test_1_11(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_11() failed.");
return 130;
}
AA.verify_all(); AA.reset();
if (test_1_12(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_12() failed.");
return 131;
}
AA.verify_all(); AA.reset();
if (test_1_13(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_13() failed.");
return 132;
}
AA.verify_all(); AA.reset();
if (test_1_14(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_14() failed.");
return 133;
}
AA.verify_all(); AA.reset();
if (test_1_15(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_15() failed.");
return 134;
}
AA.verify_all(); AA.reset();
if (test_1_16(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_16() failed.");
return 135;
}
AA.verify_all(); AA.reset();
if (test_1_17(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_17() failed.");
return 136;
}
AA.verify_all(); AA.reset();
if (test_2_0(100) != 100)
{
Console.WriteLine("test_2_0() failed.");
return 137;
}
AA.verify_all(); AA.reset();
if (test_2_1(100) != 100)
{
Console.WriteLine("test_2_1() failed.");
return 138;
}
AA.verify_all(); AA.reset();
if (test_2_2(100) != 100)
{
Console.WriteLine("test_2_2() failed.");
return 139;
}
AA.verify_all(); AA.reset();
if (test_2_3(100) != 100)
{
Console.WriteLine("test_2_3() failed.");
return 140;
}
AA.verify_all(); AA.reset();
if (test_2_4(100) != 100)
{
Console.WriteLine("test_2_4() failed.");
return 141;
}
AA.verify_all(); AA.reset();
if (test_2_5(100) != 100)
{
Console.WriteLine("test_2_5() failed.");
return 142;
}
AA.verify_all(); AA.reset();
if (test_2_6(100) != 100)
{
Console.WriteLine("test_2_6() failed.");
return 143;
}
AA.verify_all(); AA.reset();
if (test_2_7(100) != 100)
{
Console.WriteLine("test_2_7() failed.");
return 144;
}
AA.verify_all(); AA.reset();
if (test_2_8(100) != 100)
{
Console.WriteLine("test_2_8() failed.");
return 145;
}
AA.verify_all(); AA.reset();
if (test_2_9(100) != 100)
{
Console.WriteLine("test_2_9() failed.");
return 146;
}
AA.verify_all(); AA.reset();
if (test_2_10(100) != 100)
{
Console.WriteLine("test_2_10() failed.");
return 147;
}
AA.verify_all(); AA.reset();
if (test_2_11(100) != 100)
{
Console.WriteLine("test_2_11() failed.");
return 148;
}
AA.verify_all(); AA.reset();
if (test_2_12(100) != 100)
{
Console.WriteLine("test_2_12() failed.");
return 149;
}
AA.verify_all(); AA.reset();
if (test_2_13(100) != 100)
{
Console.WriteLine("test_2_13() failed.");
return 150;
}
AA.verify_all(); AA.reset();
if (test_2_14(100) != 100)
{
Console.WriteLine("test_2_14() failed.");
return 151;
}
AA.verify_all(); AA.reset();
if (test_2_15(100) != 100)
{
Console.WriteLine("test_2_15() failed.");
return 152;
}
AA.verify_all(); AA.reset();
if (test_2_16(100) != 100)
{
Console.WriteLine("test_2_16() failed.");
return 153;
}
AA.verify_all(); AA.reset();
if (test_2_17(100) != 100)
{
Console.WriteLine("test_2_17() failed.");
return 154;
}
AA.verify_all(); AA.reset();
if (test_3_0(100) != 100)
{
Console.WriteLine("test_3_0() failed.");
return 155;
}
AA.verify_all(); AA.reset();
if (test_3_1(100) != 100)
{
Console.WriteLine("test_3_1() failed.");
return 156;
}
AA.verify_all(); AA.reset();
if (test_3_2(100) != 100)
{
Console.WriteLine("test_3_2() failed.");
return 157;
}
AA.verify_all(); AA.reset();
if (test_3_3(100) != 100)
{
Console.WriteLine("test_3_3() failed.");
return 158;
}
AA.verify_all(); AA.reset();
if (test_3_4(100) != 100)
{
Console.WriteLine("test_3_4() failed.");
return 159;
}
AA.verify_all(); AA.reset();
if (test_3_5(100) != 100)
{
Console.WriteLine("test_3_5() failed.");
return 160;
}
AA.verify_all(); AA.reset();
if (test_3_6(100) != 100)
{
Console.WriteLine("test_3_6() failed.");
return 161;
}
AA.verify_all(); AA.reset();
if (test_3_7(100) != 100)
{
Console.WriteLine("test_3_7() failed.");
return 162;
}
AA.verify_all(); AA.reset();
if (test_3_8(100) != 100)
{
Console.WriteLine("test_3_8() failed.");
return 163;
}
AA.verify_all(); AA.reset();
if (test_3_9(100) != 100)
{
Console.WriteLine("test_3_9() failed.");
return 164;
}
AA.verify_all(); AA.reset();
if (test_3_10(100) != 100)
{
Console.WriteLine("test_3_10() failed.");
return 165;
}
AA.verify_all(); AA.reset();
if (test_3_11(100) != 100)
{
Console.WriteLine("test_3_11() failed.");
return 166;
}
AA.verify_all(); AA.reset();
if (test_3_12(100) != 100)
{
Console.WriteLine("test_3_12() failed.");
return 167;
}
AA.verify_all(); AA.reset();
if (test_3_13(100) != 100)
{
Console.WriteLine("test_3_13() failed.");
return 168;
}
AA.verify_all(); AA.reset();
if (test_3_14(100) != 100)
{
Console.WriteLine("test_3_14() failed.");
return 169;
}
AA.verify_all(); AA.reset();
if (test_3_15(100) != 100)
{
Console.WriteLine("test_3_15() failed.");
return 170;
}
AA.verify_all(); AA.reset();
if (test_3_16(100) != 100)
{
Console.WriteLine("test_3_16() failed.");
return 171;
}
AA.verify_all(); AA.reset();
if (test_3_17(100) != 100)
{
Console.WriteLine("test_3_17() failed.");
return 172;
}
AA.verify_all(); AA.reset();
if (test_4_0(100) != 100)
{
Console.WriteLine("test_4_0() failed.");
return 173;
}
AA.verify_all(); AA.reset();
if (test_4_1(100) != 100)
{
Console.WriteLine("test_4_1() failed.");
return 174;
}
AA.verify_all(); AA.reset();
if (test_4_2(100) != 100)
{
Console.WriteLine("test_4_2() failed.");
return 175;
}
AA.verify_all(); AA.reset();
if (test_4_3(100) != 100)
{
Console.WriteLine("test_4_3() failed.");
return 176;
}
AA.verify_all(); AA.reset();
if (test_4_4(100) != 100)
{
Console.WriteLine("test_4_4() failed.");
return 177;
}
AA.verify_all(); AA.reset();
if (test_4_5(100) != 100)
{
Console.WriteLine("test_4_5() failed.");
return 178;
}
AA.verify_all(); AA.reset();
if (test_4_6(100) != 100)
{
Console.WriteLine("test_4_6() failed.");
return 179;
}
AA.verify_all(); AA.reset();
if (test_4_7(100) != 100)
{
Console.WriteLine("test_4_7() failed.");
return 180;
}
AA.verify_all(); AA.reset();
if (test_4_8(100) != 100)
{
Console.WriteLine("test_4_8() failed.");
return 181;
}
AA.verify_all(); AA.reset();
if (test_4_9(100) != 100)
{
Console.WriteLine("test_4_9() failed.");
return 182;
}
AA.verify_all(); AA.reset();
if (test_4_10(100) != 100)
{
Console.WriteLine("test_4_10() failed.");
return 183;
}
AA.verify_all(); AA.reset();
if (test_4_11(100) != 100)
{
Console.WriteLine("test_4_11() failed.");
return 184;
}
AA.verify_all(); AA.reset();
if (test_4_12(100) != 100)
{
Console.WriteLine("test_4_12() failed.");
return 185;
}
AA.verify_all(); AA.reset();
if (test_4_13(100) != 100)
{
Console.WriteLine("test_4_13() failed.");
return 186;
}
AA.verify_all(); AA.reset();
if (test_4_14(100) != 100)
{
Console.WriteLine("test_4_14() failed.");
return 187;
}
AA.verify_all(); AA.reset();
if (test_4_15(100) != 100)
{
Console.WriteLine("test_4_15() failed.");
return 188;
}
AA.verify_all(); AA.reset();
if (test_4_16(100) != 100)
{
Console.WriteLine("test_4_16() failed.");
return 189;
}
AA.verify_all(); AA.reset();
if (test_4_17(100) != 100)
{
Console.WriteLine("test_4_17() failed.");
return 190;
}
AA.verify_all(); AA.reset();
if (test_5_0(100) != 100)
{
Console.WriteLine("test_5_0() failed.");
return 191;
}
AA.verify_all(); AA.reset();
if (test_6_0(100, __makeref(AA._init)) != 100)
{
Console.WriteLine("test_6_0() failed.");
return 192;
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_0(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_0() failed.");
return 193;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_1(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_1() failed.");
return 194;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_2(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_2() failed.");
return 195;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_3(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_3() failed.");
return 196;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_4(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_4() failed.");
return 197;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_5(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_5() failed.");
return 198;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_6(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_6() failed.");
return 199;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_7(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_7() failed.");
return 200;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_8(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_8() failed.");
return 201;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_9(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_9() failed.");
return 202;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_10(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_10() failed.");
return 203;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_11(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_11() failed.");
return 204;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_12(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_12() failed.");
return 205;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_13(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_13() failed.");
return 206;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_14(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_14() failed.");
return 207;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_15(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_15() failed.");
return 208;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_16(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_16() failed.");
return 209;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_17(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_17() failed.");
return 210;
}
}
AA.verify_all(); Console.WriteLine("All tests passed.");
return 100;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/Common/CoreCLRTestLibrary/OutOfProcessTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CoreclrTestLib;
using Xunit;
namespace TestLibrary
{
public static class OutOfProcessTest
{
internal static bool runningInWindows;
internal static string reportBase;
internal static string testBinaryBase;
internal static string helixUploadRoot;
static OutOfProcessTest()
{
reportBase = Directory.GetCurrentDirectory();
testBinaryBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
helixUploadRoot = Environment.GetEnvironmentVariable("HELIX_WORKITEM_UPLOAD_ROOT");
if (!String.IsNullOrEmpty(helixUploadRoot))
{
reportBase = Path.Combine(Path.GetFullPath(helixUploadRoot), "Reports");
}
if (String.IsNullOrEmpty(reportBase))
{
reportBase = Path.Combine(testBinaryBase, "Reports");
}
else
{
reportBase = Path.GetFullPath(reportBase);
}
}
public static void RunOutOfProcessTest(string basePath, string assemblyPath)
{
int ret = -100;
string baseDir = Path.GetDirectoryName(basePath);
string outputDir = System.IO.Path.GetFullPath(Path.Combine(reportBase, Path.GetDirectoryName(assemblyPath)));
string outputFile = Path.Combine(outputDir, "output.txt");
string errorFile = Path.Combine(outputDir, "error.txt");
string testExecutable = null;
Exception infraEx = null;
try
{
CoreclrTestWrapperLib wrapper = new CoreclrTestWrapperLib();
if (OperatingSystem.IsWindows())
{
testExecutable = Path.Combine(baseDir, Path.ChangeExtension(assemblyPath, ".cmd"));
}
else
{
testExecutable = Path.Combine(baseDir, Path.ChangeExtension(assemblyPath.Replace("\\", "/"), ".sh"));
}
System.IO.Directory.CreateDirectory(outputDir);
ret = wrapper.RunTest(testExecutable, outputFile, errorFile, Assembly.GetEntryAssembly()!.FullName!, testBinaryBase, outputDir);
}
catch (Exception ex)
{
infraEx = ex;
}
if (infraEx != null)
{
Assert.True(false, "Test Infrastructure Failure: " + infraEx.ToString());
}
else
{
List<string> testOutput = new List<string>();
try
{
testOutput.AddRange(System.IO.File.ReadAllLines(errorFile));
}
catch (Exception ex)
{
testOutput.Add("Unable to read error file: " + errorFile);
testOutput.Add(ex.ToString());
}
testOutput.Add(string.Empty);
testOutput.Add("Return code: " + ret);
testOutput.Add("Raw output file: " + outputFile);
testOutput.Add("Raw output:");
try
{
testOutput.AddRange(System.IO.File.ReadAllLines(outputFile));
}
catch (Exception ex)
{
testOutput.Add("Unable to read output file: " + outputFile);
testOutput.Add(ex.ToString());
}
testOutput.Add("To run the test:");
testOutput.Add("Set up CORE_ROOT and run.");
testOutput.Add("> " + testExecutable);
var unicodeControlCharsRegex = new Regex("%5C%5Cp{C}+");
// Remove all characters that have no visual or spatial representation.
for (int i = 0; i < testOutput.Count; i++)
{
string line = testOutput[i];
line = unicodeControlCharsRegex.Replace(line, string.Empty);
testOutput[i] = line;
}
foreach (string line in testOutput)
{
Console.WriteLine(line);
}
Assert.True(ret == CoreclrTestWrapperLib.EXIT_SUCCESS_CODE, string.Join(Environment.NewLine, testOutput));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CoreclrTestLib;
using Xunit;
namespace TestLibrary
{
public static class OutOfProcessTest
{
internal static bool runningInWindows;
internal static string reportBase;
internal static string testBinaryBase;
internal static string helixUploadRoot;
static OutOfProcessTest()
{
reportBase = Directory.GetCurrentDirectory();
testBinaryBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
helixUploadRoot = Environment.GetEnvironmentVariable("HELIX_WORKITEM_UPLOAD_ROOT");
if (!String.IsNullOrEmpty(helixUploadRoot))
{
reportBase = Path.Combine(Path.GetFullPath(helixUploadRoot), "Reports");
}
if (String.IsNullOrEmpty(reportBase))
{
reportBase = Path.Combine(testBinaryBase, "Reports");
}
else
{
reportBase = Path.GetFullPath(reportBase);
}
}
public static void RunOutOfProcessTest(string basePath, string assemblyPath)
{
int ret = -100;
string baseDir = Path.GetDirectoryName(basePath);
string outputDir = System.IO.Path.GetFullPath(Path.Combine(reportBase, Path.GetDirectoryName(assemblyPath)));
string outputFile = Path.Combine(outputDir, "output.txt");
string errorFile = Path.Combine(outputDir, "error.txt");
string testExecutable = null;
Exception infraEx = null;
try
{
CoreclrTestWrapperLib wrapper = new CoreclrTestWrapperLib();
if (OperatingSystem.IsWindows())
{
testExecutable = Path.Combine(baseDir, Path.ChangeExtension(assemblyPath, ".cmd"));
}
else
{
testExecutable = Path.Combine(baseDir, Path.ChangeExtension(assemblyPath.Replace("\\", "/"), ".sh"));
}
System.IO.Directory.CreateDirectory(outputDir);
ret = wrapper.RunTest(testExecutable, outputFile, errorFile, Assembly.GetEntryAssembly()!.FullName!, testBinaryBase, outputDir);
}
catch (Exception ex)
{
infraEx = ex;
}
if (infraEx != null)
{
Assert.True(false, "Test Infrastructure Failure: " + infraEx.ToString());
}
else
{
List<string> testOutput = new List<string>();
try
{
testOutput.AddRange(System.IO.File.ReadAllLines(errorFile));
}
catch (Exception ex)
{
testOutput.Add("Unable to read error file: " + errorFile);
testOutput.Add(ex.ToString());
}
testOutput.Add(string.Empty);
testOutput.Add("Return code: " + ret);
testOutput.Add("Raw output file: " + outputFile);
testOutput.Add("Raw output:");
try
{
testOutput.AddRange(System.IO.File.ReadAllLines(outputFile));
}
catch (Exception ex)
{
testOutput.Add("Unable to read output file: " + outputFile);
testOutput.Add(ex.ToString());
}
testOutput.Add("To run the test:");
testOutput.Add("Set up CORE_ROOT and run.");
testOutput.Add("> " + testExecutable);
var unicodeControlCharsRegex = new Regex("%5C%5Cp{C}+");
// Remove all characters that have no visual or spatial representation.
for (int i = 0; i < testOutput.Count; i++)
{
string line = testOutput[i];
line = unicodeControlCharsRegex.Replace(line, string.Empty);
testOutput[i] = line;
}
foreach (string line in testOutput)
{
Console.WriteLine(line);
}
Assert.True(ret == CoreclrTestWrapperLib.EXIT_SUCCESS_CODE, string.Join(Environment.NewLine, testOutput));
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/X86/Fma_Vector256/MultiplySubtract.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;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplySubtractSingle()
{
var test = new SimpleTernaryOpTest__MultiplySubtractSingle();
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 SimpleTernaryOpTest__MultiplySubtractSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Single> _fld2;
public Vector256<Single> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractSingle testClass)
{
var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractSingle testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
fixed (Vector256<Single>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Single[] _data3 = new Single[Op3ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private static Vector256<Single> _clsVar3;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private Vector256<Single> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplySubtractSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleTernaryOpTest__MultiplySubtractSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtract(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtract(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtract(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
fixed (Vector256<Single>* pClsVar2 = &_clsVar2)
fixed (Vector256<Single>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(pClsVar1)),
Avx.LoadVector256((Single*)(pClsVar2)),
Avx.LoadVector256((Single*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplySubtractSingle();
var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplySubtractSingle();
fixed (Vector256<Single>* pFld1 = &test._fld1)
fixed (Vector256<Single>* pFld2 = &test._fld2)
fixed (Vector256<Single>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
fixed (Vector256<Single>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(&test._fld1)),
Avx.LoadVector256((Single*)(&test._fld2)),
Avx.LoadVector256((Single*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, Vector256<Single> op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[0] * secondOp[0]) - thirdOp[0], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[0], 3)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[i] * secondOp[i]) - thirdOp[i], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i], 3)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtract)}<Single>(Vector256<Single>, Vector256<Single>, Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplySubtractSingle()
{
var test = new SimpleTernaryOpTest__MultiplySubtractSingle();
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 SimpleTernaryOpTest__MultiplySubtractSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Single> _fld2;
public Vector256<Single> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractSingle testClass)
{
var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractSingle testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
fixed (Vector256<Single>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Single[] _data3 = new Single[Op3ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private static Vector256<Single> _clsVar3;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private Vector256<Single> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplySubtractSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleTernaryOpTest__MultiplySubtractSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtract(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtract(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtract(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
fixed (Vector256<Single>* pClsVar2 = &_clsVar2)
fixed (Vector256<Single>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(pClsVar1)),
Avx.LoadVector256((Single*)(pClsVar2)),
Avx.LoadVector256((Single*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtract(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplySubtractSingle();
var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplySubtractSingle();
fixed (Vector256<Single>* pFld1 = &test._fld1)
fixed (Vector256<Single>* pFld2 = &test._fld2)
fixed (Vector256<Single>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
fixed (Vector256<Single>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtract(
Avx.LoadVector256((Single*)(&test._fld1)),
Avx.LoadVector256((Single*)(&test._fld2)),
Avx.LoadVector256((Single*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, Vector256<Single> op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[0] * secondOp[0]) - thirdOp[0], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[0], 3)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[i] * secondOp[i]) - thirdOp[i], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i], 3)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtract)}<Single>(Vector256<Single>, Vector256<Single>, Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/Microsoft.VisualBasic.Core/tests/ByteTypeTests.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.VisualBasic.Tests;
using System;
using System.Collections.Generic;
using Xunit;
namespace Microsoft.VisualBasic.CompilerServices.Tests
{
public class ByteTypeTests
{
[Theory]
[MemberData(nameof(FromObject_TestData))]
[MemberData(nameof(FromString_TestData))]
public void FromObject(object value, byte expected)
{
Assert.Equal(expected, ByteType.FromObject(value));
}
// The following conversions are not supported.
[Theory]
[MemberData(nameof(FromObject_NotSupported_TestData))]
public void FromObject_NotSupported(object value)
{
Assert.Throws<InvalidCastException>(() => ByteType.FromObject(value));
}
[Theory]
[MemberData(nameof(FromObject_Invalid_TestData))]
public void FromObject_ThrowsInvalidCastException(object value)
{
Assert.Throws<InvalidCastException>(() => ByteType.FromObject(value));
}
[Theory]
[MemberData(nameof(FromObject_Overflow_TestData))]
public void FromObject_ThrowsOverflowException(object value)
{
Assert.Throws<OverflowException>(() => ByteType.FromObject(value));
}
[Theory]
[MemberData(nameof(FromString_TestData))]
public void FromString(string value, byte expected)
{
Assert.Equal(expected, ByteType.FromString(value));
}
[Theory]
[MemberData(nameof(FromString_Invalid_TestData))]
public void FromString_ThrowsInvalidCastException(string value)
{
Assert.Throws<InvalidCastException>(() => ByteType.FromString(value));
}
[Theory]
[MemberData(nameof(FromString_Overflow_TestData))]
public void FromString_ThrowsOverflowException(string value)
{
Assert.Throws<OverflowException>(() => ByteType.FromString(value));
}
public static IEnumerable<object[]> FromObject_TestData()
{
// byte.
yield return new object[] { byte.MinValue, byte.MinValue };
yield return new object[] { (byte)1, (byte)1 };
yield return new object[] { byte.MaxValue, byte.MaxValue };
yield return new object[] { (ByteEnum)byte.MinValue, byte.MinValue };
yield return new object[] { (ByteEnum)1, (byte)1 };
yield return new object[] { (ByteEnum)byte.MaxValue, byte.MaxValue };
// short.
yield return new object[] { (short)0, byte.MinValue };
yield return new object[] { (short)1, (byte)1 };
yield return new object[] { (ShortEnum)0, byte.MinValue };
yield return new object[] { (ShortEnum)1, (byte)1 };
// int.
yield return new object[] { 0, byte.MinValue };
yield return new object[] { 1, (byte)1 };
yield return new object[] { (IntEnum)0, byte.MinValue };
yield return new object[] { (IntEnum)1, (byte)1 };
// long.
yield return new object[] { (long)0, byte.MinValue };
yield return new object[] { (long)1, (byte)1 };
yield return new object[] { (LongEnum)0, byte.MinValue };
yield return new object[] { (LongEnum)1, (byte)1 };
// float.
yield return new object[] { (float)0, byte.MinValue };
yield return new object[] { (float)1, (byte)1 };
// double.
yield return new object[] { (double)0, byte.MinValue };
yield return new object[] { (double)1, (byte)1 };
// decimal.
yield return new object[] { (decimal)0, byte.MinValue };
yield return new object[] { (decimal)1, (byte)1 };
// bool.
yield return new object[] { true, byte.MaxValue };
yield return new object[] { false, byte.MinValue };
// null.
yield return new object[] { null, byte.MinValue };
}
public static IEnumerable<object[]> FromObject_NotSupported_TestData()
{
// sbyte.
yield return new object[] { (sbyte)0 };
yield return new object[] { (sbyte)1 };
yield return new object[] { sbyte.MaxValue };
yield return new object[] { (SByteEnum)0 };
yield return new object[] { (SByteEnum)1 };
yield return new object[] { (SByteEnum)sbyte.MaxValue };
// ushort.
yield return new object[] { ushort.MinValue };
yield return new object[] { (ushort)1 };
yield return new object[] { (UShortEnum)ushort.MinValue };
yield return new object[] { (UShortEnum)1 };
// uint.
yield return new object[] { uint.MinValue };
yield return new object[] { (uint)1 };
yield return new object[] { (UIntEnum)uint.MinValue };
yield return new object[] { (UIntEnum)1 };
// ulong.
yield return new object[] { ulong.MinValue };
yield return new object[] { (ulong)1 };
yield return new object[] { (ULongEnum)ulong.MinValue };
yield return new object[] { (ULongEnum)1 };
}
public static IEnumerable<object[]> FromObject_Invalid_TestData()
{
// char.
yield return new object[] { char.MinValue };
yield return new object[] { (char)1 };
yield return new object[] { char.MaxValue };
// DateTime.
yield return new object[] { new DateTime(10) };
// object.
yield return new object[] { new object() };
// ushort.
yield return new object[] { ushort.MaxValue };
yield return new object[] { (UShortEnum)ushort.MaxValue };
}
public static IEnumerable<object[]> FromObject_Overflow_TestData()
{
yield return new object[] { short.MaxValue };
yield return new object[] { (ShortEnum)short.MaxValue };
}
public static IEnumerable<object[]> FromString_TestData()
{
yield return new object[] { null, byte.MinValue };
yield return new object[] { "0", byte.MinValue };
yield return new object[] { "1", (byte)1 };
yield return new object[] { "&h5", (byte)5 };
yield return new object[] { "&h0", byte.MinValue };
yield return new object[] { "&o5", (byte)5 };
yield return new object[] { " &o5", (byte)5 };
yield return new object[] { "&o0", byte.MinValue };
yield return new object[] { 1.1.ToString(), (byte)1 };
}
public static IEnumerable<object[]> FromString_Invalid_TestData()
{
yield return new object[] { "" };
yield return new object[] { "&" };
yield return new object[] { "&a" };
yield return new object[] { "&a0" };
yield return new object[] { "true" };
yield return new object[] { "false" };
yield return new object[] { "invalid" };
}
public static IEnumerable<object[]> FromString_Overflow_TestData()
{
yield return new object[] { "256" };
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.VisualBasic.Tests;
using System;
using System.Collections.Generic;
using Xunit;
namespace Microsoft.VisualBasic.CompilerServices.Tests
{
public class ByteTypeTests
{
[Theory]
[MemberData(nameof(FromObject_TestData))]
[MemberData(nameof(FromString_TestData))]
public void FromObject(object value, byte expected)
{
Assert.Equal(expected, ByteType.FromObject(value));
}
// The following conversions are not supported.
[Theory]
[MemberData(nameof(FromObject_NotSupported_TestData))]
public void FromObject_NotSupported(object value)
{
Assert.Throws<InvalidCastException>(() => ByteType.FromObject(value));
}
[Theory]
[MemberData(nameof(FromObject_Invalid_TestData))]
public void FromObject_ThrowsInvalidCastException(object value)
{
Assert.Throws<InvalidCastException>(() => ByteType.FromObject(value));
}
[Theory]
[MemberData(nameof(FromObject_Overflow_TestData))]
public void FromObject_ThrowsOverflowException(object value)
{
Assert.Throws<OverflowException>(() => ByteType.FromObject(value));
}
[Theory]
[MemberData(nameof(FromString_TestData))]
public void FromString(string value, byte expected)
{
Assert.Equal(expected, ByteType.FromString(value));
}
[Theory]
[MemberData(nameof(FromString_Invalid_TestData))]
public void FromString_ThrowsInvalidCastException(string value)
{
Assert.Throws<InvalidCastException>(() => ByteType.FromString(value));
}
[Theory]
[MemberData(nameof(FromString_Overflow_TestData))]
public void FromString_ThrowsOverflowException(string value)
{
Assert.Throws<OverflowException>(() => ByteType.FromString(value));
}
public static IEnumerable<object[]> FromObject_TestData()
{
// byte.
yield return new object[] { byte.MinValue, byte.MinValue };
yield return new object[] { (byte)1, (byte)1 };
yield return new object[] { byte.MaxValue, byte.MaxValue };
yield return new object[] { (ByteEnum)byte.MinValue, byte.MinValue };
yield return new object[] { (ByteEnum)1, (byte)1 };
yield return new object[] { (ByteEnum)byte.MaxValue, byte.MaxValue };
// short.
yield return new object[] { (short)0, byte.MinValue };
yield return new object[] { (short)1, (byte)1 };
yield return new object[] { (ShortEnum)0, byte.MinValue };
yield return new object[] { (ShortEnum)1, (byte)1 };
// int.
yield return new object[] { 0, byte.MinValue };
yield return new object[] { 1, (byte)1 };
yield return new object[] { (IntEnum)0, byte.MinValue };
yield return new object[] { (IntEnum)1, (byte)1 };
// long.
yield return new object[] { (long)0, byte.MinValue };
yield return new object[] { (long)1, (byte)1 };
yield return new object[] { (LongEnum)0, byte.MinValue };
yield return new object[] { (LongEnum)1, (byte)1 };
// float.
yield return new object[] { (float)0, byte.MinValue };
yield return new object[] { (float)1, (byte)1 };
// double.
yield return new object[] { (double)0, byte.MinValue };
yield return new object[] { (double)1, (byte)1 };
// decimal.
yield return new object[] { (decimal)0, byte.MinValue };
yield return new object[] { (decimal)1, (byte)1 };
// bool.
yield return new object[] { true, byte.MaxValue };
yield return new object[] { false, byte.MinValue };
// null.
yield return new object[] { null, byte.MinValue };
}
public static IEnumerable<object[]> FromObject_NotSupported_TestData()
{
// sbyte.
yield return new object[] { (sbyte)0 };
yield return new object[] { (sbyte)1 };
yield return new object[] { sbyte.MaxValue };
yield return new object[] { (SByteEnum)0 };
yield return new object[] { (SByteEnum)1 };
yield return new object[] { (SByteEnum)sbyte.MaxValue };
// ushort.
yield return new object[] { ushort.MinValue };
yield return new object[] { (ushort)1 };
yield return new object[] { (UShortEnum)ushort.MinValue };
yield return new object[] { (UShortEnum)1 };
// uint.
yield return new object[] { uint.MinValue };
yield return new object[] { (uint)1 };
yield return new object[] { (UIntEnum)uint.MinValue };
yield return new object[] { (UIntEnum)1 };
// ulong.
yield return new object[] { ulong.MinValue };
yield return new object[] { (ulong)1 };
yield return new object[] { (ULongEnum)ulong.MinValue };
yield return new object[] { (ULongEnum)1 };
}
public static IEnumerable<object[]> FromObject_Invalid_TestData()
{
// char.
yield return new object[] { char.MinValue };
yield return new object[] { (char)1 };
yield return new object[] { char.MaxValue };
// DateTime.
yield return new object[] { new DateTime(10) };
// object.
yield return new object[] { new object() };
// ushort.
yield return new object[] { ushort.MaxValue };
yield return new object[] { (UShortEnum)ushort.MaxValue };
}
public static IEnumerable<object[]> FromObject_Overflow_TestData()
{
yield return new object[] { short.MaxValue };
yield return new object[] { (ShortEnum)short.MaxValue };
}
public static IEnumerable<object[]> FromString_TestData()
{
yield return new object[] { null, byte.MinValue };
yield return new object[] { "0", byte.MinValue };
yield return new object[] { "1", (byte)1 };
yield return new object[] { "&h5", (byte)5 };
yield return new object[] { "&h0", byte.MinValue };
yield return new object[] { "&o5", (byte)5 };
yield return new object[] { " &o5", (byte)5 };
yield return new object[] { "&o0", byte.MinValue };
yield return new object[] { 1.1.ToString(), (byte)1 };
}
public static IEnumerable<object[]> FromString_Invalid_TestData()
{
yield return new object[] { "" };
yield return new object[] { "&" };
yield return new object[] { "&a" };
yield return new object[] { "&a0" };
yield return new object[] { "true" };
yield return new object[] { "false" };
yield return new object[] { "invalid" };
}
public static IEnumerable<object[]> FromString_Overflow_TestData()
{
yield return new object[] { "256" };
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/LocalVariable.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class ExprLocal : Expr
{
public ExprLocal(LocalVariableSymbol local)
: base(ExpressionKind.Local)
{
Flags = EXPRFLAG.EXF_LVALUE;
Local = local;
Type = local?.GetType();
}
public LocalVariableSymbol Local { 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;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class ExprLocal : Expr
{
public ExprLocal(LocalVariableSymbol local)
: base(ExpressionKind.Local)
{
Flags = EXPRFLAG.EXF_LVALUE;
Local = local;
Type = local?.GetType();
}
public LocalVariableSymbol Local { get; }
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AddPairwiseWideningAndAddScalar.Vector64.Int32.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AddPairwiseWideningAndAddScalar_Vector64_Int32()
{
var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int32[] inArray2, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public Vector64<Int32> _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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32 testClass)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32 testClass)
{
fixed (Vector64<Int64>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int64> _clsVar1;
private static Vector64<Int32> _clsVar2;
private Vector64<Int64> _fld1;
private Vector64<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwiseWideningAndAddScalar), new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwiseWideningAndAddScalar), new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.AddPairwiseWideningAndAddScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32();
var result = AdvSimd.AddPairwiseWideningAndAddScalar(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__AddPairwiseWideningAndAddScalar_Vector64_Int32();
fixed (Vector64<Int64>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int64>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AddPairwiseWideningAndAddScalar(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.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int64> op1, Vector64<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int32[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.AddPairwiseWideningAndAdd(left, right, 0) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddPairwiseWideningAndAddScalar)}<Int64>(Vector64<Int64>, Vector64<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AddPairwiseWideningAndAddScalar_Vector64_Int32()
{
var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int32[] inArray2, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public Vector64<Int32> _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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32 testClass)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32 testClass)
{
fixed (Vector64<Int64>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int64> _clsVar1;
private static Vector64<Int32> _clsVar2;
private Vector64<Int64> _fld1;
private Vector64<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwiseWideningAndAddScalar), new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwiseWideningAndAddScalar), new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.AddPairwiseWideningAndAddScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAddScalar_Vector64_Int32();
var result = AdvSimd.AddPairwiseWideningAndAddScalar(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__AddPairwiseWideningAndAddScalar_Vector64_Int32();
fixed (Vector64<Int64>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddPairwiseWideningAndAddScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int64>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AddPairwiseWideningAndAddScalar(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.AddPairwiseWideningAndAddScalar(
AdvSimd.LoadVector64((Int64*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int64> op1, Vector64<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int32[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.AddPairwiseWideningAndAdd(left, right, 0) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddPairwiseWideningAndAddScalar)}<Int64>(Vector64<Int64>, Vector64<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Versioning;
namespace System.Xml
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class XmlTextReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
//
// Member fields
//
private readonly XmlTextReaderImpl _impl;
//
//
// Constructors
//
protected XmlTextReader()
{
_impl = new XmlTextReaderImpl();
_impl.OuterReader = this;
}
protected XmlTextReader(XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(nt);
_impl.OuterReader = this;
}
public XmlTextReader(Stream input)
{
_impl = new XmlTextReaderImpl(input);
_impl.OuterReader = this;
}
public XmlTextReader(string url, Stream input)
{
_impl = new XmlTextReaderImpl(url, input);
_impl.OuterReader = this;
}
public XmlTextReader(Stream input, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(input, nt);
_impl.OuterReader = this;
}
public XmlTextReader(string url, Stream input, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(url, input, nt);
_impl.OuterReader = this;
}
public XmlTextReader(TextReader input)
{
_impl = new XmlTextReaderImpl(input);
_impl.OuterReader = this;
}
public XmlTextReader(string url, TextReader input)
{
_impl = new XmlTextReaderImpl(url, input);
_impl.OuterReader = this;
}
public XmlTextReader(TextReader input, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(input, nt);
_impl.OuterReader = this;
}
public XmlTextReader(string url, TextReader input, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(url, input, nt);
_impl.OuterReader = this;
}
public XmlTextReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext? context)
{
_impl = new XmlTextReaderImpl(xmlFragment, fragType, context);
_impl.OuterReader = this;
}
public XmlTextReader(string xmlFragment, XmlNodeType fragType, XmlParserContext? context)
{
_impl = new XmlTextReaderImpl(xmlFragment, fragType, context);
_impl.OuterReader = this;
}
public XmlTextReader(string url)
{
_impl = new XmlTextReaderImpl(url, new NameTable());
_impl.OuterReader = this;
}
public XmlTextReader(string url, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(url, nt);
_impl.OuterReader = this;
}
//
// XmlReader members
//
public override XmlNodeType NodeType
{
get { return _impl.NodeType; }
}
public override string Name
{
get { return _impl.Name; }
}
public override string LocalName
{
get { return _impl.LocalName; }
}
public override string NamespaceURI
{
get { return _impl.NamespaceURI; }
}
public override string Prefix
{
get { return _impl.Prefix; }
}
public override bool HasValue
{
get { return _impl.HasValue; }
}
public override string Value
{
get { return _impl.Value; }
}
public override int Depth
{
get { return _impl.Depth; }
}
public override string BaseURI
{
get { return _impl.BaseURI; }
}
public override bool IsEmptyElement
{
get { return _impl.IsEmptyElement; }
}
public override bool IsDefault
{
get { return _impl.IsDefault; }
}
public override char QuoteChar
{
get { return _impl.QuoteChar; }
}
public override XmlSpace XmlSpace
{
get { return _impl.XmlSpace; }
}
public override string XmlLang
{
get { return _impl.XmlLang; }
}
// XmlTextReader does not override SchemaInfo, ValueType and ReadTypeValue
public override int AttributeCount { get { return _impl.AttributeCount; } }
public override string? GetAttribute(string name)
{
return _impl.GetAttribute(name);
}
public override string? GetAttribute(string localName, string? namespaceURI)
{
return _impl.GetAttribute(localName, namespaceURI);
}
public override string GetAttribute(int i)
{
return _impl.GetAttribute(i);
}
public override bool MoveToAttribute(string name)
{
return _impl.MoveToAttribute(name);
}
public override bool MoveToAttribute(string localName, string? namespaceURI)
{
return _impl.MoveToAttribute(localName, namespaceURI);
}
public override void MoveToAttribute(int i)
{
_impl.MoveToAttribute(i);
}
public override bool MoveToFirstAttribute()
{
return _impl.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
return _impl.MoveToNextAttribute();
}
public override bool MoveToElement()
{
return _impl.MoveToElement();
}
public override bool ReadAttributeValue()
{
return _impl.ReadAttributeValue();
}
public override bool Read()
{
return _impl.Read();
}
public override bool EOF
{
get { return _impl.EOF; }
}
public override void Close()
{
_impl.Close();
}
public override ReadState ReadState
{
get { return _impl.ReadState; }
}
public override void Skip()
{
_impl.Skip();
}
public override XmlNameTable NameTable
{
get { return _impl.NameTable; }
}
public override string? LookupNamespace(string prefix)
{
string? ns = _impl.LookupNamespace(prefix);
if (ns != null && ns.Length == 0)
{
ns = null;
}
return ns;
}
public override bool CanResolveEntity
{
get { return true; }
}
public override void ResolveEntity()
{
_impl.ResolveEntity();
}
// Binary content access methods
public override bool CanReadBinaryContent
{
get { return true; }
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
return _impl.ReadContentAsBase64(buffer, index, count);
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
return _impl.ReadElementContentAsBase64(buffer, index, count);
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
return _impl.ReadContentAsBinHex(buffer, index, count);
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
return _impl.ReadElementContentAsBinHex(buffer, index, count);
}
// Text streaming methods
// XmlTextReader does do support streaming of Value (there are backwards compatibility issues when enabled)
public override bool CanReadValueChunk
{
get { return false; }
}
// Overriden helper methods
public override string ReadString()
{
_impl.MoveOffEntityReference();
return base.ReadString();
}
//
// IXmlLineInfo members
//
public bool HasLineInfo() { return true; }
public int LineNumber { get { return _impl.LineNumber; } }
public int LinePosition { get { return _impl.LinePosition; } }
//
// IXmlNamespaceResolver members
//
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return _impl.GetNamespacesInScope(scope);
}
string? IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _impl.LookupNamespace(prefix);
}
string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _impl.LookupPrefix(namespaceName);
}
// FXCOP: ExplicitMethodImplementationsInUnsealedClassesHaveVisibleAlternates
// public versions of IXmlNamespaceResolver methods, so that XmlTextReader subclasses can access them
public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
return _impl.GetNamespacesInScope(scope);
}
//
// XmlTextReader
//
public bool Namespaces
{
get { return _impl.Namespaces; }
set { _impl.Namespaces = value; }
}
public bool Normalization
{
get { return _impl.Normalization; }
set { _impl.Normalization = value; }
}
public Encoding? Encoding
{
get { return _impl.Encoding; }
}
public WhitespaceHandling WhitespaceHandling
{
get { return _impl.WhitespaceHandling; }
set { _impl.WhitespaceHandling = value; }
}
[Obsolete("XmlTextReader.ProhibitDtd has been deprecated. Use DtdProcessing instead.")]
public bool ProhibitDtd
{
get { return _impl.DtdProcessing == DtdProcessing.Prohibit; }
set { _impl.DtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse; }
}
public DtdProcessing DtdProcessing
{
get { return _impl.DtdProcessing; }
set { _impl.DtdProcessing = value; }
}
public EntityHandling EntityHandling
{
get { return _impl.EntityHandling; }
set { _impl.EntityHandling = value; }
}
public XmlResolver? XmlResolver
{
set { _impl.XmlResolver = value; }
}
public void ResetState()
{
_impl.ResetState();
}
public TextReader GetRemainder()
{
return _impl.GetRemainder();
}
public int ReadChars(char[] buffer, int index, int count)
{
return _impl.ReadChars(buffer, index, count);
}
public int ReadBase64(byte[] array, int offset, int len)
{
return _impl.ReadBase64(array, offset, len);
}
public int ReadBinHex(byte[] array, int offset, int len)
{
return _impl.ReadBinHex(array, offset, len);
}
//
// Internal helper methods
//
internal XmlTextReaderImpl Impl
{
get { return _impl; }
}
internal override XmlNamespaceManager? NamespaceManager
{
get { return _impl.NamespaceManager; }
}
// NOTE: System.Data.SqlXml.XmlDataSourceResolver accesses this property via reflection
internal bool XmlValidatingReaderCompatibilityMode
{
set { _impl.XmlValidatingReaderCompatibilityMode = value; }
}
internal override IDtdInfo? DtdInfo
{
get { return _impl.DtdInfo; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Versioning;
namespace System.Xml
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class XmlTextReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
//
// Member fields
//
private readonly XmlTextReaderImpl _impl;
//
//
// Constructors
//
protected XmlTextReader()
{
_impl = new XmlTextReaderImpl();
_impl.OuterReader = this;
}
protected XmlTextReader(XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(nt);
_impl.OuterReader = this;
}
public XmlTextReader(Stream input)
{
_impl = new XmlTextReaderImpl(input);
_impl.OuterReader = this;
}
public XmlTextReader(string url, Stream input)
{
_impl = new XmlTextReaderImpl(url, input);
_impl.OuterReader = this;
}
public XmlTextReader(Stream input, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(input, nt);
_impl.OuterReader = this;
}
public XmlTextReader(string url, Stream input, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(url, input, nt);
_impl.OuterReader = this;
}
public XmlTextReader(TextReader input)
{
_impl = new XmlTextReaderImpl(input);
_impl.OuterReader = this;
}
public XmlTextReader(string url, TextReader input)
{
_impl = new XmlTextReaderImpl(url, input);
_impl.OuterReader = this;
}
public XmlTextReader(TextReader input, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(input, nt);
_impl.OuterReader = this;
}
public XmlTextReader(string url, TextReader input, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(url, input, nt);
_impl.OuterReader = this;
}
public XmlTextReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext? context)
{
_impl = new XmlTextReaderImpl(xmlFragment, fragType, context);
_impl.OuterReader = this;
}
public XmlTextReader(string xmlFragment, XmlNodeType fragType, XmlParserContext? context)
{
_impl = new XmlTextReaderImpl(xmlFragment, fragType, context);
_impl.OuterReader = this;
}
public XmlTextReader(string url)
{
_impl = new XmlTextReaderImpl(url, new NameTable());
_impl.OuterReader = this;
}
public XmlTextReader(string url, XmlNameTable nt)
{
_impl = new XmlTextReaderImpl(url, nt);
_impl.OuterReader = this;
}
//
// XmlReader members
//
public override XmlNodeType NodeType
{
get { return _impl.NodeType; }
}
public override string Name
{
get { return _impl.Name; }
}
public override string LocalName
{
get { return _impl.LocalName; }
}
public override string NamespaceURI
{
get { return _impl.NamespaceURI; }
}
public override string Prefix
{
get { return _impl.Prefix; }
}
public override bool HasValue
{
get { return _impl.HasValue; }
}
public override string Value
{
get { return _impl.Value; }
}
public override int Depth
{
get { return _impl.Depth; }
}
public override string BaseURI
{
get { return _impl.BaseURI; }
}
public override bool IsEmptyElement
{
get { return _impl.IsEmptyElement; }
}
public override bool IsDefault
{
get { return _impl.IsDefault; }
}
public override char QuoteChar
{
get { return _impl.QuoteChar; }
}
public override XmlSpace XmlSpace
{
get { return _impl.XmlSpace; }
}
public override string XmlLang
{
get { return _impl.XmlLang; }
}
// XmlTextReader does not override SchemaInfo, ValueType and ReadTypeValue
public override int AttributeCount { get { return _impl.AttributeCount; } }
public override string? GetAttribute(string name)
{
return _impl.GetAttribute(name);
}
public override string? GetAttribute(string localName, string? namespaceURI)
{
return _impl.GetAttribute(localName, namespaceURI);
}
public override string GetAttribute(int i)
{
return _impl.GetAttribute(i);
}
public override bool MoveToAttribute(string name)
{
return _impl.MoveToAttribute(name);
}
public override bool MoveToAttribute(string localName, string? namespaceURI)
{
return _impl.MoveToAttribute(localName, namespaceURI);
}
public override void MoveToAttribute(int i)
{
_impl.MoveToAttribute(i);
}
public override bool MoveToFirstAttribute()
{
return _impl.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
return _impl.MoveToNextAttribute();
}
public override bool MoveToElement()
{
return _impl.MoveToElement();
}
public override bool ReadAttributeValue()
{
return _impl.ReadAttributeValue();
}
public override bool Read()
{
return _impl.Read();
}
public override bool EOF
{
get { return _impl.EOF; }
}
public override void Close()
{
_impl.Close();
}
public override ReadState ReadState
{
get { return _impl.ReadState; }
}
public override void Skip()
{
_impl.Skip();
}
public override XmlNameTable NameTable
{
get { return _impl.NameTable; }
}
public override string? LookupNamespace(string prefix)
{
string? ns = _impl.LookupNamespace(prefix);
if (ns != null && ns.Length == 0)
{
ns = null;
}
return ns;
}
public override bool CanResolveEntity
{
get { return true; }
}
public override void ResolveEntity()
{
_impl.ResolveEntity();
}
// Binary content access methods
public override bool CanReadBinaryContent
{
get { return true; }
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
return _impl.ReadContentAsBase64(buffer, index, count);
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
return _impl.ReadElementContentAsBase64(buffer, index, count);
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
return _impl.ReadContentAsBinHex(buffer, index, count);
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
return _impl.ReadElementContentAsBinHex(buffer, index, count);
}
// Text streaming methods
// XmlTextReader does do support streaming of Value (there are backwards compatibility issues when enabled)
public override bool CanReadValueChunk
{
get { return false; }
}
// Overriden helper methods
public override string ReadString()
{
_impl.MoveOffEntityReference();
return base.ReadString();
}
//
// IXmlLineInfo members
//
public bool HasLineInfo() { return true; }
public int LineNumber { get { return _impl.LineNumber; } }
public int LinePosition { get { return _impl.LinePosition; } }
//
// IXmlNamespaceResolver members
//
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return _impl.GetNamespacesInScope(scope);
}
string? IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _impl.LookupNamespace(prefix);
}
string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _impl.LookupPrefix(namespaceName);
}
// FXCOP: ExplicitMethodImplementationsInUnsealedClassesHaveVisibleAlternates
// public versions of IXmlNamespaceResolver methods, so that XmlTextReader subclasses can access them
public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
return _impl.GetNamespacesInScope(scope);
}
//
// XmlTextReader
//
public bool Namespaces
{
get { return _impl.Namespaces; }
set { _impl.Namespaces = value; }
}
public bool Normalization
{
get { return _impl.Normalization; }
set { _impl.Normalization = value; }
}
public Encoding? Encoding
{
get { return _impl.Encoding; }
}
public WhitespaceHandling WhitespaceHandling
{
get { return _impl.WhitespaceHandling; }
set { _impl.WhitespaceHandling = value; }
}
[Obsolete("XmlTextReader.ProhibitDtd has been deprecated. Use DtdProcessing instead.")]
public bool ProhibitDtd
{
get { return _impl.DtdProcessing == DtdProcessing.Prohibit; }
set { _impl.DtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse; }
}
public DtdProcessing DtdProcessing
{
get { return _impl.DtdProcessing; }
set { _impl.DtdProcessing = value; }
}
public EntityHandling EntityHandling
{
get { return _impl.EntityHandling; }
set { _impl.EntityHandling = value; }
}
public XmlResolver? XmlResolver
{
set { _impl.XmlResolver = value; }
}
public void ResetState()
{
_impl.ResetState();
}
public TextReader GetRemainder()
{
return _impl.GetRemainder();
}
public int ReadChars(char[] buffer, int index, int count)
{
return _impl.ReadChars(buffer, index, count);
}
public int ReadBase64(byte[] array, int offset, int len)
{
return _impl.ReadBase64(array, offset, len);
}
public int ReadBinHex(byte[] array, int offset, int len)
{
return _impl.ReadBinHex(array, offset, len);
}
//
// Internal helper methods
//
internal XmlTextReaderImpl Impl
{
get { return _impl; }
}
internal override XmlNamespaceManager? NamespaceManager
{
get { return _impl.NamespaceManager; }
}
// NOTE: System.Data.SqlXml.XmlDataSourceResolver accesses this property via reflection
internal bool XmlValidatingReaderCompatibilityMode
{
set { _impl.XmlValidatingReaderCompatibilityMode = value; }
}
internal override IDtdInfo? DtdInfo
{
get { return _impl.DtdInfo; }
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/op_ExclusiveOr.Int64.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_ExclusiveOrInt64()
{
var test = new VectorBinaryOpTest__op_ExclusiveOrInt64();
// 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_ExclusiveOrInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public Vector64<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__op_ExclusiveOrInt64 testClass)
{
var result = _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<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = 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 VectorBinaryOpTest__op_ExclusiveOrInt64()
{
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 VectorBinaryOpTest__op_ExclusiveOrInt64()
{
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, new Int64[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr) ^ Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector64<Int64>).GetMethod("op_ExclusiveOr", new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(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<Vector64<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int64>>(_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_ExclusiveOrInt64();
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(Vector64<Int64> op1, Vector64<Int64> op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (long)(left[0] ^ right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (long)(left[i] ^ right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_ExclusiveOr<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: ({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_ExclusiveOrInt64()
{
var test = new VectorBinaryOpTest__op_ExclusiveOrInt64();
// 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_ExclusiveOrInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public Vector64<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__op_ExclusiveOrInt64 testClass)
{
var result = _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<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = 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 VectorBinaryOpTest__op_ExclusiveOrInt64()
{
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 VectorBinaryOpTest__op_ExclusiveOrInt64()
{
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, new Int64[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr) ^ Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector64<Int64>).GetMethod("op_ExclusiveOr", new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(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<Vector64<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int64>>(_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_ExclusiveOrInt64();
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(Vector64<Int64> op1, Vector64<Int64> op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (long)(left[0] ^ right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (long)(left[i] ^ right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_ExclusiveOr<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: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/Regression/CLR-x86-JIT/V1-M10/b06464/b06464.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
class Test_b06464
{
static int[] a = new int[10];
static int[] A()
{
Console.WriteLine("A");
return a;
}
static int F()
{
Console.WriteLine("F");
return 1;
}
static int G()
{
Console.WriteLine("G");
return 1;
}
public static int Main()
{
A()[F()] = G();
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;
class Test_b06464
{
static int[] a = new int[10];
static int[] A()
{
Console.WriteLine("A");
return a;
}
static int F()
{
Console.WriteLine("F");
return 1;
}
static int G()
{
Console.WriteLine("G");
return 1;
}
public static int Main()
{
A()[F()] = G();
return 100;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Linq.Expressions/tests/Variables/ParameterTests.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 Xunit;
namespace System.Linq.Expressions.Tests
{
public class ParameterTests : ParameterExpressionTests
{
[Theory]
[MemberData(nameof(ValidTypeData))]
public void CreateParameterForValidTypeNoName(Type type)
{
ParameterExpression param = Expression.Parameter(type);
Assert.Equal(type, param.Type);
Assert.False(param.IsByRef);
Assert.Null(param.Name);
}
[Theory]
[MemberData(nameof(ValidTypeData))]
public void CrateParamForValidTypeWithName(Type type)
{
ParameterExpression param = Expression.Parameter(type, "name");
Assert.Equal(type, param.Type);
Assert.False(param.IsByRef);
Assert.Equal("name", param.Name);
}
[Fact]
public void NameNeedNotBeCSharpValid()
{
ParameterExpression param = Expression.Parameter(typeof(int), "a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.");
Assert.Equal("a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.", param.Name);
}
[Fact]
public void ParameterCannotBeTypeVoid()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(void)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(void), "var"));
}
[Theory]
[ClassData(typeof(InvalidTypesData))]
public void OpenGenericType_ThrowsArgumentException(Type type)
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(type));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(type, "name"));
}
[Fact]
public void NullType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Parameter(null));
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Parameter(null, "var"));
}
[Theory]
[MemberData(nameof(ByRefTypeData))]
public void ParameterCanBeByRef(Type type)
{
ParameterExpression param = Expression.Parameter(type);
Assert.Equal(type.GetElementType(), param.Type);
Assert.True(param.IsByRef);
Assert.Null(param.Name);
}
[Theory]
[MemberData(nameof(ByRefTypeData))]
public void NamedParameterCanBeByRef(Type type)
{
ParameterExpression param = Expression.Parameter(type, "name");
Assert.Equal(type.GetElementType(), param.Type);
Assert.True(param.IsByRef);
Assert.Equal("name", param.Name);
}
[Theory]
[PerCompilationType(nameof(ValueData))]
public void CanWriteAndReadBack(object value, bool useInterpreter)
{
Type type = value.GetType();
ParameterExpression param = Expression.Parameter(type);
Assert.True(
Expression.Lambda<Func<bool>>(
Expression.Equal(
Expression.Constant(value),
Expression.Block(
type,
new[] { param },
Expression.Assign(param, Expression.Constant(value)),
param
)
)
).Compile(useInterpreter)()
);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaParameter(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(int));
Func<int, int> addOne = Expression.Lambda<Func<int, int>>(
Expression.Add(param, Expression.Constant(1)),
param
).Compile(useInterpreter);
Assert.Equal(3, addOne(2));
}
public delegate void ByRefFunc<T>(ref T arg);
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaByRefParameter(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(int).MakeByRefType());
ByRefFunc<int> addOneInPlace = Expression.Lambda<ByRefFunc<int>>(
Expression.PreIncrementAssign(param),
param
).Compile(useInterpreter);
int argument = 5;
addOneInPlace(ref argument);
Assert.Equal(6, argument);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaByRefParameter_String(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(string).MakeByRefType());
ByRefFunc<string> f = Expression.Lambda<ByRefFunc<string>>(
Expression.Assign(param, Expression.Call(param, typeof(string).GetMethod(nameof(string.ToUpper), Type.EmptyTypes))),
param
).Compile(useInterpreter);
string argument = "bar";
f(ref argument);
Assert.Equal("BAR", argument);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaByRefParameter_Char(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(char).MakeByRefType());
ByRefFunc<char> f = Expression.Lambda<ByRefFunc<char>>(
Expression.Assign(param, Expression.Call(typeof(char).GetMethod(nameof(char.ToUpper), new[] { typeof(char) }), param)),
param
).Compile(useInterpreter);
char argument = 'a';
f(ref argument);
Assert.Equal('A', argument);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaByRefParameter_Bool(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(bool).MakeByRefType());
ByRefFunc<bool> f = Expression.Lambda<ByRefFunc<bool>>(
Expression.ExclusiveOrAssign(param, Expression.Constant(true)),
param
).Compile(useInterpreter);
bool b1 = false;
f(ref b1);
Assert.Equal(false ^ true, b1);
bool b2 = true;
f(ref b2);
Assert.Equal(true ^ true, b2);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanReadFromRefParameter(bool useInterpreter)
{
AssertCanReadFromRefParameter<byte>(byte.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<sbyte>(sbyte.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<short>(short.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<ushort>(ushort.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<int>(int.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<uint>(uint.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<long>(long.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<ulong>(ulong.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<decimal>(49.94m, useInterpreter);
AssertCanReadFromRefParameter<float>(3.1415926535897931f, useInterpreter);
AssertCanReadFromRefParameter<double>(2.7182818284590451, useInterpreter);
AssertCanReadFromRefParameter('a', useInterpreter);
AssertCanReadFromRefParameter(ByteEnum.A, useInterpreter);
AssertCanReadFromRefParameter(SByteEnum.A, useInterpreter);
AssertCanReadFromRefParameter(Int16Enum.A, useInterpreter);
AssertCanReadFromRefParameter(UInt16Enum.A, useInterpreter);
AssertCanReadFromRefParameter(Int32Enum.A, useInterpreter);
AssertCanReadFromRefParameter(UInt32Enum.A, useInterpreter);
AssertCanReadFromRefParameter(Int64Enum.A, useInterpreter);
AssertCanReadFromRefParameter(UInt64Enum.A, useInterpreter);
AssertCanReadFromRefParameter(new DateTime(1983, 2, 11), useInterpreter);
AssertCanReadFromRefParameter<object>(null, useInterpreter);
AssertCanReadFromRefParameter<object>(new object(), useInterpreter);
AssertCanReadFromRefParameter<string>("bar", useInterpreter);
AssertCanReadFromRefParameter<int?>(null, useInterpreter);
AssertCanReadFromRefParameter<int?>(int.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<Int64Enum?>(null, useInterpreter);
AssertCanReadFromRefParameter<Int64Enum?>(Int64Enum.A, useInterpreter);
AssertCanReadFromRefParameter<DateTime?>(null, useInterpreter);
AssertCanReadFromRefParameter<DateTime?>(new DateTime(1983, 2, 11), useInterpreter);
}
public delegate T ByRefReadFunc<T>(ref T arg);
private void AssertCanReadFromRefParameter<T>(T value, bool useInterpreter)
{
ParameterExpression @ref = Expression.Parameter(typeof(T).MakeByRefType());
ByRefReadFunc<T> f =
Expression.Lambda<ByRefReadFunc<T>>(
@ref,
@ref
).Compile(useInterpreter);
Assert.Equal(value, f(ref value));
}
public delegate void ByRefWriteAction<T>(ref T arg, T value);
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanWriteToRefParameter(bool useInterpreter)
{
AssertCanWriteToRefParameter<byte>(byte.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<sbyte>(sbyte.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<short>(short.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<ushort>(ushort.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<int>(int.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<uint>(uint.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<long>(long.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<ulong>(ulong.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<decimal>(49.94m, useInterpreter);
AssertCanWriteToRefParameter<float>(3.1415926535897931f, useInterpreter);
AssertCanWriteToRefParameter<double>(2.7182818284590451, useInterpreter);
AssertCanWriteToRefParameter('a', useInterpreter);
AssertCanWriteToRefParameter(ByteEnum.A, useInterpreter);
AssertCanWriteToRefParameter(SByteEnum.A, useInterpreter);
AssertCanWriteToRefParameter(Int16Enum.A, useInterpreter);
AssertCanWriteToRefParameter(UInt16Enum.A, useInterpreter);
AssertCanWriteToRefParameter(Int32Enum.A, useInterpreter);
AssertCanWriteToRefParameter(UInt32Enum.A, useInterpreter);
AssertCanWriteToRefParameter(Int64Enum.A, useInterpreter);
AssertCanWriteToRefParameter(UInt64Enum.A, useInterpreter);
AssertCanWriteToRefParameter(new DateTime(1983, 2, 11), useInterpreter);
AssertCanWriteToRefParameter<object>(null, useInterpreter);
AssertCanWriteToRefParameter<object>(new object(), useInterpreter);
AssertCanWriteToRefParameter<string>("bar", useInterpreter);
AssertCanWriteToRefParameter<int?>(null, useInterpreter, original: 42);
AssertCanWriteToRefParameter<int?>(int.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<Int64Enum?>(null, useInterpreter, original: Int64Enum.A);
AssertCanWriteToRefParameter<Int64Enum?>(Int64Enum.A, useInterpreter);
AssertCanWriteToRefParameter<DateTime?>(null, useInterpreter, original: new DateTime(1983, 2, 11));
AssertCanWriteToRefParameter<DateTime?>(new DateTime(1983, 2, 11), useInterpreter);
}
private void AssertCanWriteToRefParameter<T>(T value, bool useInterpreter, T original = default(T))
{
ParameterExpression @ref = Expression.Parameter(typeof(T).MakeByRefType());
ParameterExpression val = Expression.Parameter(typeof(T));
ByRefWriteAction<T> f =
Expression.Lambda<ByRefWriteAction<T>>(
Expression.Assign(@ref, val),
@ref, val
).Compile(useInterpreter);
T res = original;
f(ref res, value);
Assert.Equal(res, value);
}
[Fact]
public void CannotReduce()
{
ParameterExpression param = Expression.Parameter(typeof(int));
Assert.False(param.CanReduce);
Assert.Same(param, param.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => param.ReduceAndCheck());
}
[Fact]
public void CannotBePointerType()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(int*)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(int*), "pointer"));
}
[Theory]
[MemberData(nameof(ReadAndWriteRefCases))]
public void ReadAndWriteRefParameters(bool useInterpreter, object value, object increment, object result)
{
Type type = value.GetType();
MethodInfo method = typeof(ParameterTests).GetMethod(nameof(AssertReadAndWriteRefParameters), BindingFlags.NonPublic | BindingFlags.Static);
method.MakeGenericMethod(type).Invoke(null, new object[] { useInterpreter, value, increment, result });
}
private static void AssertReadAndWriteRefParameters<T>(bool useInterpreter, T value, T increment, T result)
{
ParameterExpression param = Expression.Parameter(typeof(T).MakeByRefType());
ByRefFunc<T> addOneInPlace = Expression.Lambda<ByRefFunc<T>>(
Expression.AddAssign(param, Expression.Constant(increment, typeof(T))),
param
).Compile(useInterpreter);
T argument = value;
addOneInPlace(ref argument);
Assert.Equal(result, argument);
}
public static IEnumerable<object[]> ReadAndWriteRefCases()
{
foreach (var useInterpreter in new[] { true, false })
{
yield return new object[] { useInterpreter, (short)41, (short)1, (short)42 };
yield return new object[] { useInterpreter, (ushort)41, (ushort)1, (ushort)42 };
yield return new object[] { useInterpreter, 41, 1, 42 };
yield return new object[] { useInterpreter, 41U, 1U, 42U };
yield return new object[] { useInterpreter, 41L, 1L, 42L };
yield return new object[] { useInterpreter, 41UL, 1UL, 42UL };
yield return new object[] { useInterpreter, 41.0F, 1.0F, Apply((x, y) => x + y, 41.0F, 1.0F) };
yield return new object[] { useInterpreter, 41.0D, 1.0D, Apply((x, y) => x + y, 41.0D, 1.0D) };
yield return new object[] { useInterpreter, TimeSpan.FromSeconds(41), TimeSpan.FromSeconds(1), Apply((x, y) => x + y, TimeSpan.FromSeconds(41), TimeSpan.FromSeconds(1)) };
}
}
private static T Apply<T>(Func<T, T, T> f, T x, T y) => f(x, y);
}
}
| // 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public class ParameterTests : ParameterExpressionTests
{
[Theory]
[MemberData(nameof(ValidTypeData))]
public void CreateParameterForValidTypeNoName(Type type)
{
ParameterExpression param = Expression.Parameter(type);
Assert.Equal(type, param.Type);
Assert.False(param.IsByRef);
Assert.Null(param.Name);
}
[Theory]
[MemberData(nameof(ValidTypeData))]
public void CrateParamForValidTypeWithName(Type type)
{
ParameterExpression param = Expression.Parameter(type, "name");
Assert.Equal(type, param.Type);
Assert.False(param.IsByRef);
Assert.Equal("name", param.Name);
}
[Fact]
public void NameNeedNotBeCSharpValid()
{
ParameterExpression param = Expression.Parameter(typeof(int), "a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.");
Assert.Equal("a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.", param.Name);
}
[Fact]
public void ParameterCannotBeTypeVoid()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(void)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(void), "var"));
}
[Theory]
[ClassData(typeof(InvalidTypesData))]
public void OpenGenericType_ThrowsArgumentException(Type type)
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(type));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(type, "name"));
}
[Fact]
public void NullType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Parameter(null));
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Parameter(null, "var"));
}
[Theory]
[MemberData(nameof(ByRefTypeData))]
public void ParameterCanBeByRef(Type type)
{
ParameterExpression param = Expression.Parameter(type);
Assert.Equal(type.GetElementType(), param.Type);
Assert.True(param.IsByRef);
Assert.Null(param.Name);
}
[Theory]
[MemberData(nameof(ByRefTypeData))]
public void NamedParameterCanBeByRef(Type type)
{
ParameterExpression param = Expression.Parameter(type, "name");
Assert.Equal(type.GetElementType(), param.Type);
Assert.True(param.IsByRef);
Assert.Equal("name", param.Name);
}
[Theory]
[PerCompilationType(nameof(ValueData))]
public void CanWriteAndReadBack(object value, bool useInterpreter)
{
Type type = value.GetType();
ParameterExpression param = Expression.Parameter(type);
Assert.True(
Expression.Lambda<Func<bool>>(
Expression.Equal(
Expression.Constant(value),
Expression.Block(
type,
new[] { param },
Expression.Assign(param, Expression.Constant(value)),
param
)
)
).Compile(useInterpreter)()
);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaParameter(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(int));
Func<int, int> addOne = Expression.Lambda<Func<int, int>>(
Expression.Add(param, Expression.Constant(1)),
param
).Compile(useInterpreter);
Assert.Equal(3, addOne(2));
}
public delegate void ByRefFunc<T>(ref T arg);
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaByRefParameter(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(int).MakeByRefType());
ByRefFunc<int> addOneInPlace = Expression.Lambda<ByRefFunc<int>>(
Expression.PreIncrementAssign(param),
param
).Compile(useInterpreter);
int argument = 5;
addOneInPlace(ref argument);
Assert.Equal(6, argument);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaByRefParameter_String(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(string).MakeByRefType());
ByRefFunc<string> f = Expression.Lambda<ByRefFunc<string>>(
Expression.Assign(param, Expression.Call(param, typeof(string).GetMethod(nameof(string.ToUpper), Type.EmptyTypes))),
param
).Compile(useInterpreter);
string argument = "bar";
f(ref argument);
Assert.Equal("BAR", argument);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaByRefParameter_Char(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(char).MakeByRefType());
ByRefFunc<char> f = Expression.Lambda<ByRefFunc<char>>(
Expression.Assign(param, Expression.Call(typeof(char).GetMethod(nameof(char.ToUpper), new[] { typeof(char) }), param)),
param
).Compile(useInterpreter);
char argument = 'a';
f(ref argument);
Assert.Equal('A', argument);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaByRefParameter_Bool(bool useInterpreter)
{
ParameterExpression param = Expression.Parameter(typeof(bool).MakeByRefType());
ByRefFunc<bool> f = Expression.Lambda<ByRefFunc<bool>>(
Expression.ExclusiveOrAssign(param, Expression.Constant(true)),
param
).Compile(useInterpreter);
bool b1 = false;
f(ref b1);
Assert.Equal(false ^ true, b1);
bool b2 = true;
f(ref b2);
Assert.Equal(true ^ true, b2);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanReadFromRefParameter(bool useInterpreter)
{
AssertCanReadFromRefParameter<byte>(byte.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<sbyte>(sbyte.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<short>(short.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<ushort>(ushort.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<int>(int.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<uint>(uint.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<long>(long.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<ulong>(ulong.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<decimal>(49.94m, useInterpreter);
AssertCanReadFromRefParameter<float>(3.1415926535897931f, useInterpreter);
AssertCanReadFromRefParameter<double>(2.7182818284590451, useInterpreter);
AssertCanReadFromRefParameter('a', useInterpreter);
AssertCanReadFromRefParameter(ByteEnum.A, useInterpreter);
AssertCanReadFromRefParameter(SByteEnum.A, useInterpreter);
AssertCanReadFromRefParameter(Int16Enum.A, useInterpreter);
AssertCanReadFromRefParameter(UInt16Enum.A, useInterpreter);
AssertCanReadFromRefParameter(Int32Enum.A, useInterpreter);
AssertCanReadFromRefParameter(UInt32Enum.A, useInterpreter);
AssertCanReadFromRefParameter(Int64Enum.A, useInterpreter);
AssertCanReadFromRefParameter(UInt64Enum.A, useInterpreter);
AssertCanReadFromRefParameter(new DateTime(1983, 2, 11), useInterpreter);
AssertCanReadFromRefParameter<object>(null, useInterpreter);
AssertCanReadFromRefParameter<object>(new object(), useInterpreter);
AssertCanReadFromRefParameter<string>("bar", useInterpreter);
AssertCanReadFromRefParameter<int?>(null, useInterpreter);
AssertCanReadFromRefParameter<int?>(int.MaxValue, useInterpreter);
AssertCanReadFromRefParameter<Int64Enum?>(null, useInterpreter);
AssertCanReadFromRefParameter<Int64Enum?>(Int64Enum.A, useInterpreter);
AssertCanReadFromRefParameter<DateTime?>(null, useInterpreter);
AssertCanReadFromRefParameter<DateTime?>(new DateTime(1983, 2, 11), useInterpreter);
}
public delegate T ByRefReadFunc<T>(ref T arg);
private void AssertCanReadFromRefParameter<T>(T value, bool useInterpreter)
{
ParameterExpression @ref = Expression.Parameter(typeof(T).MakeByRefType());
ByRefReadFunc<T> f =
Expression.Lambda<ByRefReadFunc<T>>(
@ref,
@ref
).Compile(useInterpreter);
Assert.Equal(value, f(ref value));
}
public delegate void ByRefWriteAction<T>(ref T arg, T value);
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanWriteToRefParameter(bool useInterpreter)
{
AssertCanWriteToRefParameter<byte>(byte.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<sbyte>(sbyte.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<short>(short.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<ushort>(ushort.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<int>(int.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<uint>(uint.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<long>(long.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<ulong>(ulong.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<decimal>(49.94m, useInterpreter);
AssertCanWriteToRefParameter<float>(3.1415926535897931f, useInterpreter);
AssertCanWriteToRefParameter<double>(2.7182818284590451, useInterpreter);
AssertCanWriteToRefParameter('a', useInterpreter);
AssertCanWriteToRefParameter(ByteEnum.A, useInterpreter);
AssertCanWriteToRefParameter(SByteEnum.A, useInterpreter);
AssertCanWriteToRefParameter(Int16Enum.A, useInterpreter);
AssertCanWriteToRefParameter(UInt16Enum.A, useInterpreter);
AssertCanWriteToRefParameter(Int32Enum.A, useInterpreter);
AssertCanWriteToRefParameter(UInt32Enum.A, useInterpreter);
AssertCanWriteToRefParameter(Int64Enum.A, useInterpreter);
AssertCanWriteToRefParameter(UInt64Enum.A, useInterpreter);
AssertCanWriteToRefParameter(new DateTime(1983, 2, 11), useInterpreter);
AssertCanWriteToRefParameter<object>(null, useInterpreter);
AssertCanWriteToRefParameter<object>(new object(), useInterpreter);
AssertCanWriteToRefParameter<string>("bar", useInterpreter);
AssertCanWriteToRefParameter<int?>(null, useInterpreter, original: 42);
AssertCanWriteToRefParameter<int?>(int.MaxValue, useInterpreter);
AssertCanWriteToRefParameter<Int64Enum?>(null, useInterpreter, original: Int64Enum.A);
AssertCanWriteToRefParameter<Int64Enum?>(Int64Enum.A, useInterpreter);
AssertCanWriteToRefParameter<DateTime?>(null, useInterpreter, original: new DateTime(1983, 2, 11));
AssertCanWriteToRefParameter<DateTime?>(new DateTime(1983, 2, 11), useInterpreter);
}
private void AssertCanWriteToRefParameter<T>(T value, bool useInterpreter, T original = default(T))
{
ParameterExpression @ref = Expression.Parameter(typeof(T).MakeByRefType());
ParameterExpression val = Expression.Parameter(typeof(T));
ByRefWriteAction<T> f =
Expression.Lambda<ByRefWriteAction<T>>(
Expression.Assign(@ref, val),
@ref, val
).Compile(useInterpreter);
T res = original;
f(ref res, value);
Assert.Equal(res, value);
}
[Fact]
public void CannotReduce()
{
ParameterExpression param = Expression.Parameter(typeof(int));
Assert.False(param.CanReduce);
Assert.Same(param, param.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => param.ReduceAndCheck());
}
[Fact]
public void CannotBePointerType()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(int*)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(int*), "pointer"));
}
[Theory]
[MemberData(nameof(ReadAndWriteRefCases))]
public void ReadAndWriteRefParameters(bool useInterpreter, object value, object increment, object result)
{
Type type = value.GetType();
MethodInfo method = typeof(ParameterTests).GetMethod(nameof(AssertReadAndWriteRefParameters), BindingFlags.NonPublic | BindingFlags.Static);
method.MakeGenericMethod(type).Invoke(null, new object[] { useInterpreter, value, increment, result });
}
private static void AssertReadAndWriteRefParameters<T>(bool useInterpreter, T value, T increment, T result)
{
ParameterExpression param = Expression.Parameter(typeof(T).MakeByRefType());
ByRefFunc<T> addOneInPlace = Expression.Lambda<ByRefFunc<T>>(
Expression.AddAssign(param, Expression.Constant(increment, typeof(T))),
param
).Compile(useInterpreter);
T argument = value;
addOneInPlace(ref argument);
Assert.Equal(result, argument);
}
public static IEnumerable<object[]> ReadAndWriteRefCases()
{
foreach (var useInterpreter in new[] { true, false })
{
yield return new object[] { useInterpreter, (short)41, (short)1, (short)42 };
yield return new object[] { useInterpreter, (ushort)41, (ushort)1, (ushort)42 };
yield return new object[] { useInterpreter, 41, 1, 42 };
yield return new object[] { useInterpreter, 41U, 1U, 42U };
yield return new object[] { useInterpreter, 41L, 1L, 42L };
yield return new object[] { useInterpreter, 41UL, 1UL, 42UL };
yield return new object[] { useInterpreter, 41.0F, 1.0F, Apply((x, y) => x + y, 41.0F, 1.0F) };
yield return new object[] { useInterpreter, 41.0D, 1.0D, Apply((x, y) => x + y, 41.0D, 1.0D) };
yield return new object[] { useInterpreter, TimeSpan.FromSeconds(41), TimeSpan.FromSeconds(1), Apply((x, y) => x + y, TimeSpan.FromSeconds(41), TimeSpan.FromSeconds(1)) };
}
}
private static T Apply<T>(Func<T, T, T> f, T x, T y) => f(x, y);
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/General/Vector128/GreaterThan.Byte.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GreaterThanByte()
{
var test = new VectorBinaryOpTest__GreaterThanByte();
// 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__GreaterThanByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16 && alignment != 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(VectorBinaryOpTest__GreaterThanByte testClass)
{
var result = Vector128.GreaterThan(_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<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 VectorBinaryOpTest__GreaterThanByte()
{
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 VectorBinaryOpTest__GreaterThanByte()
{
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 Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.GreaterThan(
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 RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThan), new Type[] {
typeof(Vector128<Byte>),
typeof(Vector128<Byte>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThan), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Byte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.GreaterThan(
_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<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Vector128.GreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__GreaterThanByte();
var result = Vector128.GreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.GreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.GreaterThan(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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] > right[0]) ? byte.MaxValue : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] > right[i]) ? byte.MaxValue : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThan)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GreaterThanByte()
{
var test = new VectorBinaryOpTest__GreaterThanByte();
// 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__GreaterThanByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16 && alignment != 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(VectorBinaryOpTest__GreaterThanByte testClass)
{
var result = Vector128.GreaterThan(_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<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 VectorBinaryOpTest__GreaterThanByte()
{
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 VectorBinaryOpTest__GreaterThanByte()
{
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 Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.GreaterThan(
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 RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThan), new Type[] {
typeof(Vector128<Byte>),
typeof(Vector128<Byte>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThan), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Byte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.GreaterThan(
_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<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Vector128.GreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__GreaterThanByte();
var result = Vector128.GreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.GreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.GreaterThan(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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] > right[0]) ? byte.MaxValue : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] > right[i]) ? byte.MaxValue : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThan)}<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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/Common/src/Interop/Windows/Gdi32/Interop.DeleteObject.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 Gdi32
{
[GeneratedDllImport(Libraries.Gdi32)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeleteObject(IntPtr ho);
public static bool DeleteObject(HandleRef ho)
{
bool result = DeleteObject(ho.Handle);
GC.KeepAlive(ho.Wrapper);
return result;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Gdi32
{
[GeneratedDllImport(Libraries.Gdi32)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeleteObject(IntPtr ho);
public static bool DeleteObject(HandleRef ho)
{
bool result = DeleteObject(ho.Handle);
GC.KeepAlive(ho.Wrapper);
return result;
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/Common/src/Interop/Windows/WinMm/Interop.waveOutGetDevCaps.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 WinMM
{
#pragma warning disable CA1823 // unused fields
internal struct WAVEOUTCAPS
{
private ushort wMid;
private ushort wPid;
private uint vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
internal string szPname;
private uint dwFormats;
private ushort wChannels;
private ushort wReserved1;
private ushort dwSupport;
}
#pragma warning restore CA1823
/// <summary>
/// This function queries a specified waveform device to determine its
/// capabilities.
/// </summary>
/// <param name="uDeviceID">Identifier of the waveform-audio output device.
/// It can be either a device identifier or a Handle to an open waveform-audio
/// output device.</param>
/// <param name="caps">Pointer to a WAVEOUTCAPS structure to be filled with
/// information about the capabilities of the device.</param>
/// <param name="cbwoc">Size, in bytes, of the WAVEOUTCAPS structure.</param>
/// <returns>MMSYSERR</returns>
#pragma warning disable DLLIMPORTGENANALYZER015 // Use 'GeneratedDllImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
// TODO: [DllImportGenerator] Switch to use GeneratedDllImport once we support non-blittable types.
[DllImport(Libraries.WinMM)]
internal static extern MMSYSERR waveOutGetDevCaps(IntPtr uDeviceID, ref WAVEOUTCAPS caps, int cbwoc);
#pragma warning restore DLLIMPORTGENANALYZER015
}
}
| // 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 WinMM
{
#pragma warning disable CA1823 // unused fields
internal struct WAVEOUTCAPS
{
private ushort wMid;
private ushort wPid;
private uint vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
internal string szPname;
private uint dwFormats;
private ushort wChannels;
private ushort wReserved1;
private ushort dwSupport;
}
#pragma warning restore CA1823
/// <summary>
/// This function queries a specified waveform device to determine its
/// capabilities.
/// </summary>
/// <param name="uDeviceID">Identifier of the waveform-audio output device.
/// It can be either a device identifier or a Handle to an open waveform-audio
/// output device.</param>
/// <param name="caps">Pointer to a WAVEOUTCAPS structure to be filled with
/// information about the capabilities of the device.</param>
/// <param name="cbwoc">Size, in bytes, of the WAVEOUTCAPS structure.</param>
/// <returns>MMSYSERR</returns>
#pragma warning disable DLLIMPORTGENANALYZER015 // Use 'GeneratedDllImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
// TODO: [DllImportGenerator] Switch to use GeneratedDllImport once we support non-blittable types.
[DllImport(Libraries.WinMM)]
internal static extern MMSYSERR waveOutGetDevCaps(IntPtr uDeviceID, ref WAVEOUTCAPS caps, int cbwoc);
#pragma warning restore DLLIMPORTGENANALYZER015
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/General/Vector128/Xor.UInt64.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void XorUInt64()
{
var test = new VectorBinaryOpTest__XorUInt64();
// 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__XorUInt64
{
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 != 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<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(VectorBinaryOpTest__XorUInt64 testClass)
{
var result = Vector128.Xor(_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<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 VectorBinaryOpTest__XorUInt64()
{
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 VectorBinaryOpTest__XorUInt64()
{
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 Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.Xor(
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 RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.Xor), new Type[] {
typeof(Vector128<UInt64>),
typeof(Vector128<UInt64>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.Xor), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(UInt64));
}
var result = method.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 RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.Xor(
_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<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Vector128.Xor(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__XorUInt64();
var result = Vector128.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.Xor(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<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;
if (result[0] != (ulong)(left[0] ^ right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (ulong)(left[i] ^ right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Xor)}<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\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 XorUInt64()
{
var test = new VectorBinaryOpTest__XorUInt64();
// 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__XorUInt64
{
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 != 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<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(VectorBinaryOpTest__XorUInt64 testClass)
{
var result = Vector128.Xor(_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<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 VectorBinaryOpTest__XorUInt64()
{
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 VectorBinaryOpTest__XorUInt64()
{
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 Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.Xor(
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 RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.Xor), new Type[] {
typeof(Vector128<UInt64>),
typeof(Vector128<UInt64>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.Xor), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(UInt64));
}
var result = method.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 RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.Xor(
_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<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Vector128.Xor(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__XorUInt64();
var result = Vector128.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.Xor(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<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;
if (result[0] != (ulong)(left[0] ^ right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (ulong)(left[i] ^ right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Xor)}<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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Uri/src/System/PercentEncodingHelper.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.Text;
namespace System
{
internal static class PercentEncodingHelper
{
public static unsafe int UnescapePercentEncodedUTF8Sequence(char* input, int length, ref ValueStringBuilder dest, bool isQuery, bool iriParsing)
{
// The following assertions rely on the input not mutating mid-operation, as is the case currently since callers are working with strings
// If we start accepting input such as spans, this method must be audited to ensure no buffer overruns/infinite loops could occur
// As an optimization, this method should only be called after the first character is known to be a part of a non-ascii UTF8 sequence
Debug.Assert(length >= 3);
Debug.Assert(input[0] == '%');
Debug.Assert(UriHelper.DecodeHexChars(input[1], input[2]) != Uri.c_DummyChar);
Debug.Assert(UriHelper.DecodeHexChars(input[1], input[2]) >= 128);
uint fourByteBuffer = 0;
int bytesLeftInBuffer = 0;
int totalCharsConsumed = 0;
int charsToCopy = 0;
int bytesConsumed = 0;
RefillBuffer:
int i = totalCharsConsumed + (bytesLeftInBuffer * 3);
ReadByteFromInput:
if ((uint)(length - i) <= 2 || input[i] != '%')
goto NoMoreOrInvalidInput;
uint value = input[i + 1];
if ((uint)((value - 'A') & ~0x20) <= ('F' - 'A'))
{
value = (value | 0x20) - 'a' + 10;
}
else if ((value - '8') <= ('9' - '8'))
{
value -= '0';
}
else goto NoMoreOrInvalidInput; // First character wasn't hex or was <= 7F (Ascii)
uint second = (uint)input[i + 2] - '0';
if (second <= 9)
{
// second is already [0, 9]
}
else if ((uint)((second - ('A' - '0')) & ~0x20) <= ('F' - 'A'))
{
second = ((second + '0') | 0x20) - 'a' + 10;
}
else goto NoMoreOrInvalidInput; // Second character wasn't Hex
value = (value << 4) | second;
Debug.Assert(value >= 128);
// Rotate the buffer and overwrite the last byte
if (BitConverter.IsLittleEndian)
{
fourByteBuffer = (fourByteBuffer >> 8) | (value << 24);
}
else
{
fourByteBuffer = (fourByteBuffer << 8) | value;
}
if (++bytesLeftInBuffer != 4)
{
i += 3;
goto ReadByteFromInput;
}
DecodeRune:
Debug.Assert(totalCharsConsumed % 3 == 0);
Debug.Assert(bytesLeftInBuffer == 2 || bytesLeftInBuffer == 3 || bytesLeftInBuffer == 4);
Debug.Assert((fourByteBuffer & (BitConverter.IsLittleEndian ? 0x00000080 : 0x80000000)) != 0);
Debug.Assert((fourByteBuffer & (BitConverter.IsLittleEndian ? 0x00008000 : 0x00800000)) != 0);
Debug.Assert(bytesLeftInBuffer < 3 || (fourByteBuffer & (BitConverter.IsLittleEndian ? 0x00800000 : 0x00008000)) != 0);
Debug.Assert(bytesLeftInBuffer < 4 || (fourByteBuffer & (BitConverter.IsLittleEndian ? 0x80000000 : 0x00000080)) != 0);
uint temp = fourByteBuffer; // make a copy so that the *copy* (not the original) is marked address-taken
if (Rune.DecodeFromUtf8(new ReadOnlySpan<byte>(&temp, bytesLeftInBuffer), out Rune rune, out bytesConsumed) == OperationStatus.Done)
{
Debug.Assert(bytesConsumed >= 2, $"Rune.DecodeFromUtf8 consumed {bytesConsumed} bytes, likely indicating input was modified concurrently during UnescapePercentEncodedUTF8Sequence's execution");
if (!iriParsing || IriHelper.CheckIriUnicodeRange((uint)rune.Value, isQuery))
{
if (charsToCopy != 0)
{
dest.Append(input + totalCharsConsumed - charsToCopy, charsToCopy);
charsToCopy = 0;
}
dest.Append(rune);
goto AfterDecodeRune;
}
}
else
{
Debug.Assert(bytesConsumed > 0, $"Rune.DecodeFromUtf8 consumed {bytesConsumed} bytes when decoding {bytesLeftInBuffer} bytes");
}
charsToCopy += bytesConsumed * 3;
AfterDecodeRune:
bytesLeftInBuffer -= bytesConsumed;
totalCharsConsumed += bytesConsumed * 3;
goto RefillBuffer;
NoMoreOrInvalidInput:
Debug.Assert(bytesLeftInBuffer < 4);
// If we have more than 1 byte left, we try to decode it
if (bytesLeftInBuffer > 1)
{
Debug.Assert(bytesLeftInBuffer == 2 || bytesLeftInBuffer == 3);
// We reach this branch if we don't have 4 valid bytes to consume
// We have to allign the read bytes to the start of fourByteBuffer memory
// We do this by shifting the fourByteBuffer, the shift direction is determined by system endianness
// If we read 3 bytes, we shift by 1; if we read 2, we shift by 2
// (32 - (bytesLeftInBuffer << 3)) calculates this offset:
// bytesLeftInBuffer == 3 => (32 - (3 << 3)) => 32 - 24 => 8 bits
// bytesLeftInBuffer == 2 => (32 - (2 << 3)) => 32 - 16 => 16 bits
// For invalid input we tried to decode in DecodeRune, we may return here if we have more than 1 byte left
// If bytesConsumed is 1, shift by 1 byte
// If bytesConsumed is 2:
// a) We had 4 bytes in the buffer and now only have 2 => Shift by 2 bytes
// b) We read 1 more byte, leaving us with 3 bytes in the buffer => Shift by 1 byte
// The case for bytesConsumed == 2 is handeled by the else block as the offsets are the same as for valid input described above
if (bytesConsumed == 1)
{
if (BitConverter.IsLittleEndian)
{
fourByteBuffer >>= 8;
}
else
{
fourByteBuffer <<= 8;
}
}
else
{
if (BitConverter.IsLittleEndian)
{
fourByteBuffer >>= (32 - (bytesLeftInBuffer << 3));
}
else
{
fourByteBuffer <<= (32 - (bytesLeftInBuffer << 3));
}
}
goto DecodeRune;
}
Debug.Assert(bytesLeftInBuffer == 0 || bytesLeftInBuffer == 1);
if ((bytesLeftInBuffer | charsToCopy) == 0)
return totalCharsConsumed;
bytesLeftInBuffer *= 3;
dest.Append(input + totalCharsConsumed - charsToCopy, charsToCopy + bytesLeftInBuffer);
return totalCharsConsumed + bytesLeftInBuffer;
}
}
}
| // 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.Text;
namespace System
{
internal static class PercentEncodingHelper
{
public static unsafe int UnescapePercentEncodedUTF8Sequence(char* input, int length, ref ValueStringBuilder dest, bool isQuery, bool iriParsing)
{
// The following assertions rely on the input not mutating mid-operation, as is the case currently since callers are working with strings
// If we start accepting input such as spans, this method must be audited to ensure no buffer overruns/infinite loops could occur
// As an optimization, this method should only be called after the first character is known to be a part of a non-ascii UTF8 sequence
Debug.Assert(length >= 3);
Debug.Assert(input[0] == '%');
Debug.Assert(UriHelper.DecodeHexChars(input[1], input[2]) != Uri.c_DummyChar);
Debug.Assert(UriHelper.DecodeHexChars(input[1], input[2]) >= 128);
uint fourByteBuffer = 0;
int bytesLeftInBuffer = 0;
int totalCharsConsumed = 0;
int charsToCopy = 0;
int bytesConsumed = 0;
RefillBuffer:
int i = totalCharsConsumed + (bytesLeftInBuffer * 3);
ReadByteFromInput:
if ((uint)(length - i) <= 2 || input[i] != '%')
goto NoMoreOrInvalidInput;
uint value = input[i + 1];
if ((uint)((value - 'A') & ~0x20) <= ('F' - 'A'))
{
value = (value | 0x20) - 'a' + 10;
}
else if ((value - '8') <= ('9' - '8'))
{
value -= '0';
}
else goto NoMoreOrInvalidInput; // First character wasn't hex or was <= 7F (Ascii)
uint second = (uint)input[i + 2] - '0';
if (second <= 9)
{
// second is already [0, 9]
}
else if ((uint)((second - ('A' - '0')) & ~0x20) <= ('F' - 'A'))
{
second = ((second + '0') | 0x20) - 'a' + 10;
}
else goto NoMoreOrInvalidInput; // Second character wasn't Hex
value = (value << 4) | second;
Debug.Assert(value >= 128);
// Rotate the buffer and overwrite the last byte
if (BitConverter.IsLittleEndian)
{
fourByteBuffer = (fourByteBuffer >> 8) | (value << 24);
}
else
{
fourByteBuffer = (fourByteBuffer << 8) | value;
}
if (++bytesLeftInBuffer != 4)
{
i += 3;
goto ReadByteFromInput;
}
DecodeRune:
Debug.Assert(totalCharsConsumed % 3 == 0);
Debug.Assert(bytesLeftInBuffer == 2 || bytesLeftInBuffer == 3 || bytesLeftInBuffer == 4);
Debug.Assert((fourByteBuffer & (BitConverter.IsLittleEndian ? 0x00000080 : 0x80000000)) != 0);
Debug.Assert((fourByteBuffer & (BitConverter.IsLittleEndian ? 0x00008000 : 0x00800000)) != 0);
Debug.Assert(bytesLeftInBuffer < 3 || (fourByteBuffer & (BitConverter.IsLittleEndian ? 0x00800000 : 0x00008000)) != 0);
Debug.Assert(bytesLeftInBuffer < 4 || (fourByteBuffer & (BitConverter.IsLittleEndian ? 0x80000000 : 0x00000080)) != 0);
uint temp = fourByteBuffer; // make a copy so that the *copy* (not the original) is marked address-taken
if (Rune.DecodeFromUtf8(new ReadOnlySpan<byte>(&temp, bytesLeftInBuffer), out Rune rune, out bytesConsumed) == OperationStatus.Done)
{
Debug.Assert(bytesConsumed >= 2, $"Rune.DecodeFromUtf8 consumed {bytesConsumed} bytes, likely indicating input was modified concurrently during UnescapePercentEncodedUTF8Sequence's execution");
if (!iriParsing || IriHelper.CheckIriUnicodeRange((uint)rune.Value, isQuery))
{
if (charsToCopy != 0)
{
dest.Append(input + totalCharsConsumed - charsToCopy, charsToCopy);
charsToCopy = 0;
}
dest.Append(rune);
goto AfterDecodeRune;
}
}
else
{
Debug.Assert(bytesConsumed > 0, $"Rune.DecodeFromUtf8 consumed {bytesConsumed} bytes when decoding {bytesLeftInBuffer} bytes");
}
charsToCopy += bytesConsumed * 3;
AfterDecodeRune:
bytesLeftInBuffer -= bytesConsumed;
totalCharsConsumed += bytesConsumed * 3;
goto RefillBuffer;
NoMoreOrInvalidInput:
Debug.Assert(bytesLeftInBuffer < 4);
// If we have more than 1 byte left, we try to decode it
if (bytesLeftInBuffer > 1)
{
Debug.Assert(bytesLeftInBuffer == 2 || bytesLeftInBuffer == 3);
// We reach this branch if we don't have 4 valid bytes to consume
// We have to allign the read bytes to the start of fourByteBuffer memory
// We do this by shifting the fourByteBuffer, the shift direction is determined by system endianness
// If we read 3 bytes, we shift by 1; if we read 2, we shift by 2
// (32 - (bytesLeftInBuffer << 3)) calculates this offset:
// bytesLeftInBuffer == 3 => (32 - (3 << 3)) => 32 - 24 => 8 bits
// bytesLeftInBuffer == 2 => (32 - (2 << 3)) => 32 - 16 => 16 bits
// For invalid input we tried to decode in DecodeRune, we may return here if we have more than 1 byte left
// If bytesConsumed is 1, shift by 1 byte
// If bytesConsumed is 2:
// a) We had 4 bytes in the buffer and now only have 2 => Shift by 2 bytes
// b) We read 1 more byte, leaving us with 3 bytes in the buffer => Shift by 1 byte
// The case for bytesConsumed == 2 is handeled by the else block as the offsets are the same as for valid input described above
if (bytesConsumed == 1)
{
if (BitConverter.IsLittleEndian)
{
fourByteBuffer >>= 8;
}
else
{
fourByteBuffer <<= 8;
}
}
else
{
if (BitConverter.IsLittleEndian)
{
fourByteBuffer >>= (32 - (bytesLeftInBuffer << 3));
}
else
{
fourByteBuffer <<= (32 - (bytesLeftInBuffer << 3));
}
}
goto DecodeRune;
}
Debug.Assert(bytesLeftInBuffer == 0 || bytesLeftInBuffer == 1);
if ((bytesLeftInBuffer | charsToCopy) == 0)
return totalCharsConsumed;
bytesLeftInBuffer *= 3;
dest.Append(input + totalCharsConsumed - charsToCopy, charsToCopy + bytesLeftInBuffer);
return totalCharsConsumed + bytesLeftInBuffer;
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Or.Vector64.Int32.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Or_Vector64_Int32()
{
var test = new SimpleBinaryOpTest__Or_Vector64_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__Or_Vector64_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector64<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__Or_Vector64_Int32 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_Vector64_Int32 testClass)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector64<Int32> _clsVar2;
private Vector64<Int32> _fld1;
private Vector64<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__Or_Vector64_Int32()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public SimpleBinaryOpTest__Or_Vector64_Int32()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Or(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(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 (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_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.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_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_Vector64_Int32();
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_Vector64_Int32();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.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.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int32> op1, Vector64<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Or(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Or)}<Int32>(Vector64<Int32>, Vector64<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Or_Vector64_Int32()
{
var test = new SimpleBinaryOpTest__Or_Vector64_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__Or_Vector64_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector64<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__Or_Vector64_Int32 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_Vector64_Int32 testClass)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector64<Int32> _clsVar2;
private Vector64<Int32> _fld1;
private Vector64<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__Or_Vector64_Int32()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public SimpleBinaryOpTest__Or_Vector64_Int32()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Or(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(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 (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_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.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_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_Vector64_Int32();
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_Vector64_Int32();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.Or(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.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.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int32> op1, Vector64<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Or(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Or)}<Int32>(Vector64<Int32>, Vector64<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.CoreLib/src/System/Numerics/Vector2.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.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Numerics
{
/// <summary>Represents a vector with two single-precision floating-point values.</summary>
/// <remarks><format type="text/markdown"><]
/// ]]></format></remarks>
[Intrinsic]
public partial struct Vector2 : IEquatable<Vector2>, IFormattable
{
/// <summary>The X component of the vector.</summary>
public float X;
/// <summary>The Y component of the vector.</summary>
public float Y;
internal const int Count = 2;
/// <summary>Creates a new <see cref="System.Numerics.Vector2" /> object whose two elements have the same value.</summary>
/// <param name="value">The value to assign to both elements.</param>
[Intrinsic]
public Vector2(float value) : this(value, value)
{
}
/// <summary>Creates a vector whose elements have the specified values.</summary>
/// <param name="x">The value to assign to the <see cref="System.Numerics.Vector2.X" /> field.</param>
/// <param name="y">The value to assign to the <see cref="System.Numerics.Vector2.Y" /> field.</param>
[Intrinsic]
public Vector2(float x, float y)
{
X = x;
Y = y;
}
/// <summary>Constructs a vector from the given <see cref="ReadOnlySpan{Single}" />. The span must contain at least 2 elements.</summary>
/// <param name="values">The span of elements to assign to the vector.</param>
public Vector2(ReadOnlySpan<float> values)
{
if (values.Length < 2)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.values);
}
this = Unsafe.ReadUnaligned<Vector2>(ref Unsafe.As<float, byte>(ref MemoryMarshal.GetReference(values)));
}
/// <summary>Returns a vector whose 2 elements are equal to zero.</summary>
/// <value>A vector whose two elements are equal to zero (that is, it returns the vector <c>(0,0)</c>.</value>
public static Vector2 Zero
{
[Intrinsic]
get => default;
}
/// <summary>Gets a vector whose 2 elements are equal to one.</summary>
/// <value>A vector whose two elements are equal to one (that is, it returns the vector <c>(1,1)</c>.</value>
public static Vector2 One
{
[Intrinsic]
get => new Vector2(1.0f);
}
/// <summary>Gets the vector (1,0).</summary>
/// <value>The vector <c>(1,0)</c>.</value>
public static Vector2 UnitX
{
get => new Vector2(1.0f, 0.0f);
}
/// <summary>Gets the vector (0,1).</summary>
/// <value>The vector <c>(0,1)</c>.</value>
public static Vector2 UnitY
{
get => new Vector2(0.0f, 1.0f);
}
public float this[int index]
{
get => GetElement(this, index);
set => this = WithElement(this, index, value);
}
/// <summary>Gets the element at the specified index.</summary>
/// <param name="vector">The vector of the element to get.</param>
/// <param name="index">The index of the element to get.</param>
/// <returns>The value of the element at <paramref name="index" />.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> was less than zero or greater than the number of elements.</exception>
[Intrinsic]
internal static float GetElement(Vector2 vector, int index)
{
if ((uint)index >= Count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
return GetElementUnsafe(ref vector, index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static float GetElementUnsafe(ref Vector2 vector, int index)
{
Debug.Assert(index is >= 0 and < Count);
return Unsafe.Add(ref Unsafe.As<Vector2, float>(ref vector), index);
}
/// <summary>Sets the element at the specified index.</summary>
/// <param name="vector">The vector of the element to get.</param>
/// <param name="index">The index of the element to set.</param>
/// <param name="value">The value of the element to set.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> was less than zero or greater than the number of elements.</exception>
[Intrinsic]
internal static Vector2 WithElement(Vector2 vector, int index, float value)
{
if ((uint)index >= Count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
Vector2 result = vector;
SetElementUnsafe(ref result, index, value);
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void SetElementUnsafe(ref Vector2 vector, int index, float value)
{
Debug.Assert(index is >= 0 and < Count);
Unsafe.Add(ref Unsafe.As<Vector2, float>(ref vector), index) = value;
}
/// <summary>Adds two vectors together.</summary>
/// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param>
/// <returns>The summed vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Addition" /> method defines the addition operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator +(Vector2 left, Vector2 right)
{
return new Vector2(
left.X + right.X,
left.Y + right.Y
);
}
/// <summary>Divides the first vector by the second.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The vector that results from dividing <paramref name="left" /> by <paramref name="right" />.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Division" /> method defines the division operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 left, Vector2 right)
{
return new Vector2(
left.X / right.X,
left.Y / right.Y
);
}
/// <summary>Divides the specified vector by a specified scalar value.</summary>
/// <param name="value1">The vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Division" /> method defines the division operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 value1, float value2)
{
return value1 / new Vector2(value2);
}
/// <summary>Returns a value that indicates whether each pair of elements in two specified vectors is equal.</summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns><see langword="true" /> if <paramref name="left" /> and <paramref name="right" /> are equal; otherwise, <see langword="false" />.</returns>
/// <remarks>Two <see cref="System.Numerics.Vector2" /> objects are equal if each value in <paramref name="left" /> is equal to the corresponding value in <paramref name="right" />.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector2 left, Vector2 right)
{
return (left.X == right.X)
&& (left.Y == right.Y);
}
/// <summary>Returns a value that indicates whether two specified vectors are not equal.</summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns><see langword="true" /> if <paramref name="left" /> and <paramref name="right" /> are not equal; otherwise, <see langword="false" />.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector2 left, Vector2 right)
{
return !(left == right);
}
/// <summary>Returns a new vector whose values are the product of each pair of elements in two specified vectors.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The element-wise product vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, Vector2 right)
{
return new Vector2(
left.X * right.X,
left.Y * right.Y
);
}
/// <summary>Multiplies the specified vector by the specified scalar value.</summary>
/// <param name="left">The vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, float right)
{
return left * new Vector2(right);
}
/// <summary>Multiplies the scalar value by the specified vector.</summary>
/// <param name="left">The vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(float left, Vector2 right)
{
return right * left;
}
/// <summary>Subtracts the second vector from the first.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The vector that results from subtracting <paramref name="right" /> from <paramref name="left" />.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Subtraction" /> method defines the subtraction operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 left, Vector2 right)
{
return new Vector2(
left.X - right.X,
left.Y - right.Y
);
}
/// <summary>Negates the specified vector.</summary>
/// <param name="value">The vector to negate.</param>
/// <returns>The negated vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_UnaryNegation" /> method defines the unary negation operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 value)
{
return Zero - value;
}
/// <summary>Returns a vector whose elements are the absolute values of each of the specified vector's elements.</summary>
/// <param name="value">A vector.</param>
/// <returns>The absolute value vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Abs(Vector2 value)
{
return new Vector2(
MathF.Abs(value.X),
MathF.Abs(value.Y)
);
}
/// <summary>Adds two vectors together.</summary>
/// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param>
/// <returns>The summed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Add(Vector2 left, Vector2 right)
{
return left + right;
}
/// <summary>Restricts a vector between a minimum and a maximum value.</summary>
/// <param name="value1">The vector to restrict.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The restricted vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max)
{
// We must follow HLSL behavior in the case user specified min value is bigger than max value.
return Min(Max(value1, min), max);
}
/// <summary>Computes the Euclidean distance between the two given points.</summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector2 value1, Vector2 value2)
{
float distanceSquared = DistanceSquared(value1, value2);
return MathF.Sqrt(distanceSquared);
}
/// <summary>Returns the Euclidean distance squared between two specified points.</summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector2 value1, Vector2 value2)
{
Vector2 difference = value1 - value2;
return Dot(difference, difference);
}
/// <summary>Divides the first vector by the second.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The vector resulting from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Divide(Vector2 left, Vector2 right)
{
return left / right;
}
/// <summary>Divides the specified vector by a specified scalar value.</summary>
/// <param name="left">The vector.</param>
/// <param name="divisor">The scalar value.</param>
/// <returns>The vector that results from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Divide(Vector2 left, float divisor)
{
return left / divisor;
}
/// <summary>Returns the dot product of two vectors.</summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The dot product.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector2 value1, Vector2 value2)
{
return (value1.X * value2.X)
+ (value1.Y * value2.Y);
}
/// <summary>Performs a linear interpolation between two vectors based on the given weighting.</summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <param name="amount">A value between 0 and 1 that indicates the weight of <paramref name="value2" />.</param>
/// <returns>The interpolated vector.</returns>
/// <remarks><format type="text/markdown"><.
/// ]]></format></remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount)
{
return (value1 * (1.0f - amount)) + (value2 * amount);
}
/// <summary>Returns a vector whose elements are the maximum of each of the pairs of elements in two specified vectors.</summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The maximized vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Max(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y
);
}
/// <summary>Returns a vector whose elements are the minimum of each of the pairs of elements in two specified vectors.</summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The minimized vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y
);
}
/// <summary>Returns a new vector whose values are the product of each pair of elements in two specified vectors.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The element-wise product vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(Vector2 left, Vector2 right)
{
return left * right;
}
/// <summary>Multiplies a vector by a specified scalar.</summary>
/// <param name="left">The vector to multiply.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(Vector2 left, float right)
{
return left * right;
}
/// <summary>Multiplies a scalar value by a specified vector.</summary>
/// <param name="left">The scaled value.</param>
/// <param name="right">The vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(float left, Vector2 right)
{
return left * right;
}
/// <summary>Negates a specified vector.</summary>
/// <param name="value">The vector to negate.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Negate(Vector2 value)
{
return -value;
}
/// <summary>Returns a vector with the same direction as the specified vector, but with a length of one.</summary>
/// <param name="value">The vector to normalize.</param>
/// <returns>The normalized vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Normalize(Vector2 value)
{
return value / value.Length();
}
/// <summary>Returns the reflection of a vector off a surface that has the specified normal.</summary>
/// <param name="vector">The source vector.</param>
/// <param name="normal">The normal of the surface being reflected off.</param>
/// <returns>The reflected vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Reflect(Vector2 vector, Vector2 normal)
{
float dot = Dot(vector, normal);
return vector - (2 * dot * normal);
}
/// <summary>Returns a vector whose elements are the square root of each of a specified vector's elements.</summary>
/// <param name="value">A vector.</param>
/// <returns>The square root vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 SquareRoot(Vector2 value)
{
return new Vector2(
MathF.Sqrt(value.X),
MathF.Sqrt(value.Y)
);
}
/// <summary>Subtracts the second vector from the first.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The difference vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Subtract(Vector2 left, Vector2 right)
{
return left - right;
}
/// <summary>Transforms a vector by a specified 3x2 matrix.</summary>
/// <param name="position">The vector to transform.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 position, Matrix3x2 matrix)
{
return new Vector2(
(position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M31,
(position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M32
);
}
/// <summary>Transforms a vector by a specified 4x4 matrix.</summary>
/// <param name="position">The vector to transform.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 position, Matrix4x4 matrix)
{
return new Vector2(
(position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41,
(position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42
);
}
/// <summary>Transforms a vector by the specified Quaternion rotation value.</summary>
/// <param name="value">The vector to rotate.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float yy2 = rotation.Y * y2;
float zz2 = rotation.Z * z2;
return new Vector2(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2)
);
}
/// <summary>Transforms a vector normal by the given 3x2 matrix.</summary>
/// <param name="normal">The source vector.</param>
/// <param name="matrix">The matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix)
{
return new Vector2(
(normal.X * matrix.M11) + (normal.Y * matrix.M21),
(normal.X * matrix.M12) + (normal.Y * matrix.M22)
);
}
/// <summary>Transforms a vector normal by the given 4x4 matrix.</summary>
/// <param name="normal">The source vector.</param>
/// <param name="matrix">The matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix)
{
return new Vector2(
(normal.X * matrix.M11) + (normal.Y * matrix.M21),
(normal.X * matrix.M12) + (normal.Y * matrix.M22)
);
}
/// <summary>Copies the elements of the vector to a specified array.</summary>
/// <param name="array">The destination array.</param>
/// <remarks><paramref name="array" /> must have at least two elements. The method copies the vector's elements starting at index 0.</remarks>
/// <exception cref="System.NullReferenceException"><paramref name="array" /> is <see langword="null" />.</exception>
/// <exception cref="System.ArgumentException">The number of elements in the current instance is greater than in the array.</exception>
/// <exception cref="System.RankException"><paramref name="array" /> is multidimensional.</exception>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void CopyTo(float[] array)
{
CopyTo(array, 0);
}
/// <summary>Copies the elements of the vector to a specified array starting at a specified index position.</summary>
/// <param name="array">The destination array.</param>
/// <param name="index">The index at which to copy the first element of the vector.</param>
/// <remarks><paramref name="array" /> must have a sufficient number of elements to accommodate the two vector elements. In other words, elements <paramref name="index" /> and <paramref name="index" /> + 1 must already exist in <paramref name="array" />.</remarks>
/// <exception cref="System.NullReferenceException"><paramref name="array" /> is <see langword="null" />.</exception>
/// <exception cref="System.ArgumentException">The number of elements in the current instance is greater than in the array.</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index" /> is less than zero.
/// -or-
/// <paramref name="index" /> is greater than or equal to the array length.</exception>
/// <exception cref="System.RankException"><paramref name="array" /> is multidimensional.</exception>
[Intrinsic]
public readonly void CopyTo(float[] array, int index)
{
if (array is null)
{
ThrowHelper.ThrowNullReferenceException();
}
if ((index < 0) || (index >= array.Length))
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if ((array.Length - index) < 2)
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
array[index] = X;
array[index + 1] = Y;
}
/// <summary>Copies the vector to the given <see cref="Span{T}" />.The length of the destination span must be at least 2.</summary>
/// <param name="destination">The destination span which the values are copied into.</param>
/// <exception cref="System.ArgumentException">If number of elements in source vector is greater than those available in destination span.</exception>
public readonly void CopyTo(Span<float> destination)
{
if (destination.Length < 2)
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
Unsafe.WriteUnaligned(ref Unsafe.As<float, byte>(ref MemoryMarshal.GetReference(destination)), this);
}
/// <summary>Attempts to copy the vector to the given <see cref="Span{Single}" />. The length of the destination span must be at least 2.</summary>
/// <param name="destination">The destination span which the values are copied into.</param>
/// <returns><see langword="true" /> if the source vector was successfully copied to <paramref name="destination" />. <see langword="false" /> if <paramref name="destination" /> is not large enough to hold the source vector.</returns>
public readonly bool TryCopyTo(Span<float> destination)
{
if (destination.Length < 2)
{
return false;
}
Unsafe.WriteUnaligned(ref Unsafe.As<float, byte>(ref MemoryMarshal.GetReference(destination)), this);
return true;
}
/// <summary>Returns a value that indicates whether this instance and a specified object are equal.</summary>
/// <param name="obj">The object to compare with the current instance.</param>
/// <returns><see langword="true" /> if the current instance and <paramref name="obj" /> are equal; otherwise, <see langword="false" />. If <paramref name="obj" /> is <see langword="null" />, the method returns <see langword="false" />.</returns>
/// <remarks>The current instance and <paramref name="obj" /> are equal if <paramref name="obj" /> is a <see cref="System.Numerics.Vector2" /> object and their <see cref="System.Numerics.Vector2.X" /> and <see cref="System.Numerics.Vector2.Y" /> elements are equal.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly bool Equals([NotNullWhen(true)] object? obj)
{
return (obj is Vector2 other) && Equals(other);
}
/// <summary>Returns a value that indicates whether this instance and another vector are equal.</summary>
/// <param name="other">The other vector.</param>
/// <returns><see langword="true" /> if the two vectors are equal; otherwise, <see langword="false" />.</returns>
/// <remarks>Two vectors are equal if their <see cref="System.Numerics.Vector2.X" /> and <see cref="System.Numerics.Vector2.Y" /> elements are equal.</remarks>
[Intrinsic]
public readonly bool Equals(Vector2 other)
{
return this == other;
}
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>The hash code.</returns>
public override readonly int GetHashCode()
{
return HashCode.Combine(X, Y);
}
/// <summary>Returns the length of the vector.</summary>
/// <returns>The vector's length.</returns>
/// <altmember cref="System.Numerics.Vector2.LengthSquared"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float Length()
{
float lengthSquared = LengthSquared();
return MathF.Sqrt(lengthSquared);
}
/// <summary>Returns the length of the vector squared.</summary>
/// <returns>The vector's length squared.</returns>
/// <remarks>This operation offers better performance than a call to the <see cref="System.Numerics.Vector2.Length" /> method.</remarks>
/// <altmember cref="System.Numerics.Vector2.Length"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float LengthSquared()
{
return Dot(this, this);
}
/// <summary>Returns the string representation of the current instance using default formatting.</summary>
/// <returns>The string representation of the current instance.</returns>
/// <remarks>This method returns a string in which each element of the vector is formatted using the "G" (general) format string and the formatting conventions of the current thread culture. The "<" and ">" characters are used to begin and end the string, and the current culture's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks>
public override readonly string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
/// <summary>Returns the string representation of the current instance using the specified format string to format individual elements.</summary>
/// <param name="format">A standard or custom numeric format string that defines the format of individual elements.</param>
/// <returns>The string representation of the current instance.</returns>
/// <remarks>This method returns a string in which each element of the vector is formatted using <paramref name="format" /> and the current culture's formatting conventions. The "<" and ">" characters are used to begin and end the string, and the current culture's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks>
/// <related type="Article" href="/dotnet/standard/base-types/standard-numeric-format-strings">Standard Numeric Format Strings</related>
/// <related type="Article" href="/dotnet/standard/base-types/custom-numeric-format-strings">Custom Numeric Format Strings</related>
public readonly string ToString(string? format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>Returns the string representation of the current instance using the specified format string to format individual elements and the specified format provider to define culture-specific formatting.</summary>
/// <param name="format">A standard or custom numeric format string that defines the format of individual elements.</param>
/// <param name="formatProvider">A format provider that supplies culture-specific formatting information.</param>
/// <returns>The string representation of the current instance.</returns>
/// <remarks>This method returns a string in which each element of the vector is formatted using <paramref name="format" /> and <paramref name="formatProvider" />. The "<" and ">" characters are used to begin and end the string, and the format provider's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks>
/// <related type="Article" href="/dotnet/standard/base-types/custom-numeric-format-strings">Custom Numeric Format Strings</related>
/// <related type="Article" href="/dotnet/standard/base-types/standard-numeric-format-strings">Standard Numeric Format Strings</related>
public readonly string ToString(string? format, IFormatProvider? formatProvider)
{
StringBuilder sb = new StringBuilder();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
sb.Append('<');
sb.Append(X.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(Y.ToString(format, formatProvider));
sb.Append('>');
return sb.ToString();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Numerics
{
/// <summary>Represents a vector with two single-precision floating-point values.</summary>
/// <remarks><format type="text/markdown"><]
/// ]]></format></remarks>
[Intrinsic]
public partial struct Vector2 : IEquatable<Vector2>, IFormattable
{
/// <summary>The X component of the vector.</summary>
public float X;
/// <summary>The Y component of the vector.</summary>
public float Y;
internal const int Count = 2;
/// <summary>Creates a new <see cref="System.Numerics.Vector2" /> object whose two elements have the same value.</summary>
/// <param name="value">The value to assign to both elements.</param>
[Intrinsic]
public Vector2(float value) : this(value, value)
{
}
/// <summary>Creates a vector whose elements have the specified values.</summary>
/// <param name="x">The value to assign to the <see cref="System.Numerics.Vector2.X" /> field.</param>
/// <param name="y">The value to assign to the <see cref="System.Numerics.Vector2.Y" /> field.</param>
[Intrinsic]
public Vector2(float x, float y)
{
X = x;
Y = y;
}
/// <summary>Constructs a vector from the given <see cref="ReadOnlySpan{Single}" />. The span must contain at least 2 elements.</summary>
/// <param name="values">The span of elements to assign to the vector.</param>
public Vector2(ReadOnlySpan<float> values)
{
if (values.Length < 2)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.values);
}
this = Unsafe.ReadUnaligned<Vector2>(ref Unsafe.As<float, byte>(ref MemoryMarshal.GetReference(values)));
}
/// <summary>Returns a vector whose 2 elements are equal to zero.</summary>
/// <value>A vector whose two elements are equal to zero (that is, it returns the vector <c>(0,0)</c>.</value>
public static Vector2 Zero
{
[Intrinsic]
get => default;
}
/// <summary>Gets a vector whose 2 elements are equal to one.</summary>
/// <value>A vector whose two elements are equal to one (that is, it returns the vector <c>(1,1)</c>.</value>
public static Vector2 One
{
[Intrinsic]
get => new Vector2(1.0f);
}
/// <summary>Gets the vector (1,0).</summary>
/// <value>The vector <c>(1,0)</c>.</value>
public static Vector2 UnitX
{
get => new Vector2(1.0f, 0.0f);
}
/// <summary>Gets the vector (0,1).</summary>
/// <value>The vector <c>(0,1)</c>.</value>
public static Vector2 UnitY
{
get => new Vector2(0.0f, 1.0f);
}
public float this[int index]
{
get => GetElement(this, index);
set => this = WithElement(this, index, value);
}
/// <summary>Gets the element at the specified index.</summary>
/// <param name="vector">The vector of the element to get.</param>
/// <param name="index">The index of the element to get.</param>
/// <returns>The value of the element at <paramref name="index" />.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> was less than zero or greater than the number of elements.</exception>
[Intrinsic]
internal static float GetElement(Vector2 vector, int index)
{
if ((uint)index >= Count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
return GetElementUnsafe(ref vector, index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static float GetElementUnsafe(ref Vector2 vector, int index)
{
Debug.Assert(index is >= 0 and < Count);
return Unsafe.Add(ref Unsafe.As<Vector2, float>(ref vector), index);
}
/// <summary>Sets the element at the specified index.</summary>
/// <param name="vector">The vector of the element to get.</param>
/// <param name="index">The index of the element to set.</param>
/// <param name="value">The value of the element to set.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> was less than zero or greater than the number of elements.</exception>
[Intrinsic]
internal static Vector2 WithElement(Vector2 vector, int index, float value)
{
if ((uint)index >= Count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
Vector2 result = vector;
SetElementUnsafe(ref result, index, value);
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void SetElementUnsafe(ref Vector2 vector, int index, float value)
{
Debug.Assert(index is >= 0 and < Count);
Unsafe.Add(ref Unsafe.As<Vector2, float>(ref vector), index) = value;
}
/// <summary>Adds two vectors together.</summary>
/// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param>
/// <returns>The summed vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Addition" /> method defines the addition operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator +(Vector2 left, Vector2 right)
{
return new Vector2(
left.X + right.X,
left.Y + right.Y
);
}
/// <summary>Divides the first vector by the second.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The vector that results from dividing <paramref name="left" /> by <paramref name="right" />.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Division" /> method defines the division operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 left, Vector2 right)
{
return new Vector2(
left.X / right.X,
left.Y / right.Y
);
}
/// <summary>Divides the specified vector by a specified scalar value.</summary>
/// <param name="value1">The vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Division" /> method defines the division operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 value1, float value2)
{
return value1 / new Vector2(value2);
}
/// <summary>Returns a value that indicates whether each pair of elements in two specified vectors is equal.</summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns><see langword="true" /> if <paramref name="left" /> and <paramref name="right" /> are equal; otherwise, <see langword="false" />.</returns>
/// <remarks>Two <see cref="System.Numerics.Vector2" /> objects are equal if each value in <paramref name="left" /> is equal to the corresponding value in <paramref name="right" />.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector2 left, Vector2 right)
{
return (left.X == right.X)
&& (left.Y == right.Y);
}
/// <summary>Returns a value that indicates whether two specified vectors are not equal.</summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns><see langword="true" /> if <paramref name="left" /> and <paramref name="right" /> are not equal; otherwise, <see langword="false" />.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector2 left, Vector2 right)
{
return !(left == right);
}
/// <summary>Returns a new vector whose values are the product of each pair of elements in two specified vectors.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The element-wise product vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, Vector2 right)
{
return new Vector2(
left.X * right.X,
left.Y * right.Y
);
}
/// <summary>Multiplies the specified vector by the specified scalar value.</summary>
/// <param name="left">The vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, float right)
{
return left * new Vector2(right);
}
/// <summary>Multiplies the scalar value by the specified vector.</summary>
/// <param name="left">The vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(float left, Vector2 right)
{
return right * left;
}
/// <summary>Subtracts the second vector from the first.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The vector that results from subtracting <paramref name="right" /> from <paramref name="left" />.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_Subtraction" /> method defines the subtraction operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 left, Vector2 right)
{
return new Vector2(
left.X - right.X,
left.Y - right.Y
);
}
/// <summary>Negates the specified vector.</summary>
/// <param name="value">The vector to negate.</param>
/// <returns>The negated vector.</returns>
/// <remarks>The <see cref="System.Numerics.Vector2.op_UnaryNegation" /> method defines the unary negation operation for <see cref="System.Numerics.Vector2" /> objects.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 value)
{
return Zero - value;
}
/// <summary>Returns a vector whose elements are the absolute values of each of the specified vector's elements.</summary>
/// <param name="value">A vector.</param>
/// <returns>The absolute value vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Abs(Vector2 value)
{
return new Vector2(
MathF.Abs(value.X),
MathF.Abs(value.Y)
);
}
/// <summary>Adds two vectors together.</summary>
/// <param name="left">The first vector to add.</param>
/// <param name="right">The second vector to add.</param>
/// <returns>The summed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Add(Vector2 left, Vector2 right)
{
return left + right;
}
/// <summary>Restricts a vector between a minimum and a maximum value.</summary>
/// <param name="value1">The vector to restrict.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The restricted vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max)
{
// We must follow HLSL behavior in the case user specified min value is bigger than max value.
return Min(Max(value1, min), max);
}
/// <summary>Computes the Euclidean distance between the two given points.</summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector2 value1, Vector2 value2)
{
float distanceSquared = DistanceSquared(value1, value2);
return MathF.Sqrt(distanceSquared);
}
/// <summary>Returns the Euclidean distance squared between two specified points.</summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector2 value1, Vector2 value2)
{
Vector2 difference = value1 - value2;
return Dot(difference, difference);
}
/// <summary>Divides the first vector by the second.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The vector resulting from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Divide(Vector2 left, Vector2 right)
{
return left / right;
}
/// <summary>Divides the specified vector by a specified scalar value.</summary>
/// <param name="left">The vector.</param>
/// <param name="divisor">The scalar value.</param>
/// <returns>The vector that results from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Divide(Vector2 left, float divisor)
{
return left / divisor;
}
/// <summary>Returns the dot product of two vectors.</summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The dot product.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector2 value1, Vector2 value2)
{
return (value1.X * value2.X)
+ (value1.Y * value2.Y);
}
/// <summary>Performs a linear interpolation between two vectors based on the given weighting.</summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <param name="amount">A value between 0 and 1 that indicates the weight of <paramref name="value2" />.</param>
/// <returns>The interpolated vector.</returns>
/// <remarks><format type="text/markdown"><.
/// ]]></format></remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount)
{
return (value1 * (1.0f - amount)) + (value2 * amount);
}
/// <summary>Returns a vector whose elements are the maximum of each of the pairs of elements in two specified vectors.</summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The maximized vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Max(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y
);
}
/// <summary>Returns a vector whose elements are the minimum of each of the pairs of elements in two specified vectors.</summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The minimized vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y
);
}
/// <summary>Returns a new vector whose values are the product of each pair of elements in two specified vectors.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The element-wise product vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(Vector2 left, Vector2 right)
{
return left * right;
}
/// <summary>Multiplies a vector by a specified scalar.</summary>
/// <param name="left">The vector to multiply.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(Vector2 left, float right)
{
return left * right;
}
/// <summary>Multiplies a scalar value by a specified vector.</summary>
/// <param name="left">The scaled value.</param>
/// <param name="right">The vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Multiply(float left, Vector2 right)
{
return left * right;
}
/// <summary>Negates a specified vector.</summary>
/// <param name="value">The vector to negate.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Negate(Vector2 value)
{
return -value;
}
/// <summary>Returns a vector with the same direction as the specified vector, but with a length of one.</summary>
/// <param name="value">The vector to normalize.</param>
/// <returns>The normalized vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Normalize(Vector2 value)
{
return value / value.Length();
}
/// <summary>Returns the reflection of a vector off a surface that has the specified normal.</summary>
/// <param name="vector">The source vector.</param>
/// <param name="normal">The normal of the surface being reflected off.</param>
/// <returns>The reflected vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Reflect(Vector2 vector, Vector2 normal)
{
float dot = Dot(vector, normal);
return vector - (2 * dot * normal);
}
/// <summary>Returns a vector whose elements are the square root of each of a specified vector's elements.</summary>
/// <param name="value">A vector.</param>
/// <returns>The square root vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 SquareRoot(Vector2 value)
{
return new Vector2(
MathF.Sqrt(value.X),
MathF.Sqrt(value.Y)
);
}
/// <summary>Subtracts the second vector from the first.</summary>
/// <param name="left">The first vector.</param>
/// <param name="right">The second vector.</param>
/// <returns>The difference vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Subtract(Vector2 left, Vector2 right)
{
return left - right;
}
/// <summary>Transforms a vector by a specified 3x2 matrix.</summary>
/// <param name="position">The vector to transform.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 position, Matrix3x2 matrix)
{
return new Vector2(
(position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M31,
(position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M32
);
}
/// <summary>Transforms a vector by a specified 4x4 matrix.</summary>
/// <param name="position">The vector to transform.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 position, Matrix4x4 matrix)
{
return new Vector2(
(position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41,
(position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42
);
}
/// <summary>Transforms a vector by the specified Quaternion rotation value.</summary>
/// <param name="value">The vector to rotate.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Transform(Vector2 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float yy2 = rotation.Y * y2;
float zz2 = rotation.Z * z2;
return new Vector2(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2)
);
}
/// <summary>Transforms a vector normal by the given 3x2 matrix.</summary>
/// <param name="normal">The source vector.</param>
/// <param name="matrix">The matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix)
{
return new Vector2(
(normal.X * matrix.M11) + (normal.Y * matrix.M21),
(normal.X * matrix.M12) + (normal.Y * matrix.M22)
);
}
/// <summary>Transforms a vector normal by the given 4x4 matrix.</summary>
/// <param name="normal">The source vector.</param>
/// <param name="matrix">The matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix)
{
return new Vector2(
(normal.X * matrix.M11) + (normal.Y * matrix.M21),
(normal.X * matrix.M12) + (normal.Y * matrix.M22)
);
}
/// <summary>Copies the elements of the vector to a specified array.</summary>
/// <param name="array">The destination array.</param>
/// <remarks><paramref name="array" /> must have at least two elements. The method copies the vector's elements starting at index 0.</remarks>
/// <exception cref="System.NullReferenceException"><paramref name="array" /> is <see langword="null" />.</exception>
/// <exception cref="System.ArgumentException">The number of elements in the current instance is greater than in the array.</exception>
/// <exception cref="System.RankException"><paramref name="array" /> is multidimensional.</exception>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void CopyTo(float[] array)
{
CopyTo(array, 0);
}
/// <summary>Copies the elements of the vector to a specified array starting at a specified index position.</summary>
/// <param name="array">The destination array.</param>
/// <param name="index">The index at which to copy the first element of the vector.</param>
/// <remarks><paramref name="array" /> must have a sufficient number of elements to accommodate the two vector elements. In other words, elements <paramref name="index" /> and <paramref name="index" /> + 1 must already exist in <paramref name="array" />.</remarks>
/// <exception cref="System.NullReferenceException"><paramref name="array" /> is <see langword="null" />.</exception>
/// <exception cref="System.ArgumentException">The number of elements in the current instance is greater than in the array.</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index" /> is less than zero.
/// -or-
/// <paramref name="index" /> is greater than or equal to the array length.</exception>
/// <exception cref="System.RankException"><paramref name="array" /> is multidimensional.</exception>
[Intrinsic]
public readonly void CopyTo(float[] array, int index)
{
if (array is null)
{
ThrowHelper.ThrowNullReferenceException();
}
if ((index < 0) || (index >= array.Length))
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if ((array.Length - index) < 2)
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
array[index] = X;
array[index + 1] = Y;
}
/// <summary>Copies the vector to the given <see cref="Span{T}" />.The length of the destination span must be at least 2.</summary>
/// <param name="destination">The destination span which the values are copied into.</param>
/// <exception cref="System.ArgumentException">If number of elements in source vector is greater than those available in destination span.</exception>
public readonly void CopyTo(Span<float> destination)
{
if (destination.Length < 2)
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
Unsafe.WriteUnaligned(ref Unsafe.As<float, byte>(ref MemoryMarshal.GetReference(destination)), this);
}
/// <summary>Attempts to copy the vector to the given <see cref="Span{Single}" />. The length of the destination span must be at least 2.</summary>
/// <param name="destination">The destination span which the values are copied into.</param>
/// <returns><see langword="true" /> if the source vector was successfully copied to <paramref name="destination" />. <see langword="false" /> if <paramref name="destination" /> is not large enough to hold the source vector.</returns>
public readonly bool TryCopyTo(Span<float> destination)
{
if (destination.Length < 2)
{
return false;
}
Unsafe.WriteUnaligned(ref Unsafe.As<float, byte>(ref MemoryMarshal.GetReference(destination)), this);
return true;
}
/// <summary>Returns a value that indicates whether this instance and a specified object are equal.</summary>
/// <param name="obj">The object to compare with the current instance.</param>
/// <returns><see langword="true" /> if the current instance and <paramref name="obj" /> are equal; otherwise, <see langword="false" />. If <paramref name="obj" /> is <see langword="null" />, the method returns <see langword="false" />.</returns>
/// <remarks>The current instance and <paramref name="obj" /> are equal if <paramref name="obj" /> is a <see cref="System.Numerics.Vector2" /> object and their <see cref="System.Numerics.Vector2.X" /> and <see cref="System.Numerics.Vector2.Y" /> elements are equal.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly bool Equals([NotNullWhen(true)] object? obj)
{
return (obj is Vector2 other) && Equals(other);
}
/// <summary>Returns a value that indicates whether this instance and another vector are equal.</summary>
/// <param name="other">The other vector.</param>
/// <returns><see langword="true" /> if the two vectors are equal; otherwise, <see langword="false" />.</returns>
/// <remarks>Two vectors are equal if their <see cref="System.Numerics.Vector2.X" /> and <see cref="System.Numerics.Vector2.Y" /> elements are equal.</remarks>
[Intrinsic]
public readonly bool Equals(Vector2 other)
{
return this == other;
}
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>The hash code.</returns>
public override readonly int GetHashCode()
{
return HashCode.Combine(X, Y);
}
/// <summary>Returns the length of the vector.</summary>
/// <returns>The vector's length.</returns>
/// <altmember cref="System.Numerics.Vector2.LengthSquared"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float Length()
{
float lengthSquared = LengthSquared();
return MathF.Sqrt(lengthSquared);
}
/// <summary>Returns the length of the vector squared.</summary>
/// <returns>The vector's length squared.</returns>
/// <remarks>This operation offers better performance than a call to the <see cref="System.Numerics.Vector2.Length" /> method.</remarks>
/// <altmember cref="System.Numerics.Vector2.Length"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float LengthSquared()
{
return Dot(this, this);
}
/// <summary>Returns the string representation of the current instance using default formatting.</summary>
/// <returns>The string representation of the current instance.</returns>
/// <remarks>This method returns a string in which each element of the vector is formatted using the "G" (general) format string and the formatting conventions of the current thread culture. The "<" and ">" characters are used to begin and end the string, and the current culture's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks>
public override readonly string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
/// <summary>Returns the string representation of the current instance using the specified format string to format individual elements.</summary>
/// <param name="format">A standard or custom numeric format string that defines the format of individual elements.</param>
/// <returns>The string representation of the current instance.</returns>
/// <remarks>This method returns a string in which each element of the vector is formatted using <paramref name="format" /> and the current culture's formatting conventions. The "<" and ">" characters are used to begin and end the string, and the current culture's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks>
/// <related type="Article" href="/dotnet/standard/base-types/standard-numeric-format-strings">Standard Numeric Format Strings</related>
/// <related type="Article" href="/dotnet/standard/base-types/custom-numeric-format-strings">Custom Numeric Format Strings</related>
public readonly string ToString(string? format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>Returns the string representation of the current instance using the specified format string to format individual elements and the specified format provider to define culture-specific formatting.</summary>
/// <param name="format">A standard or custom numeric format string that defines the format of individual elements.</param>
/// <param name="formatProvider">A format provider that supplies culture-specific formatting information.</param>
/// <returns>The string representation of the current instance.</returns>
/// <remarks>This method returns a string in which each element of the vector is formatted using <paramref name="format" /> and <paramref name="formatProvider" />. The "<" and ">" characters are used to begin and end the string, and the format provider's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks>
/// <related type="Article" href="/dotnet/standard/base-types/custom-numeric-format-strings">Custom Numeric Format Strings</related>
/// <related type="Article" href="/dotnet/standard/base-types/standard-numeric-format-strings">Standard Numeric Format Strings</related>
public readonly string ToString(string? format, IFormatProvider? formatProvider)
{
StringBuilder sb = new StringBuilder();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
sb.Append('<');
sb.Append(X.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(Y.ToString(format, formatProvider));
sb.Append('>');
return sb.ToString();
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Windows.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.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
public partial class Pen
{
/// <summary>
/// Gets or sets a custom cap style to use at the beginning of lines drawn with this <see cref='Pen'/>.
/// </summary>
public CustomLineCap CustomStartCap
{
get
{
IntPtr lineCap;
int status = Gdip.GdipGetPenCustomStartCap(new HandleRef(this, NativePen), out lineCap);
Gdip.CheckStatus(status);
return CustomLineCap.CreateCustomLineCapObject(lineCap);
}
set
{
if (_immutable)
{
throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen)));
}
int status = Gdip.GdipSetPenCustomStartCap(new HandleRef(this, NativePen),
new HandleRef(value, (value == null) ? IntPtr.Zero : value.nativeCap));
Gdip.CheckStatus(status);
}
}
/// <summary>
/// Gets or sets a custom cap style to use at the end of lines drawn with this <see cref='Pen'/>.
/// </summary>
public CustomLineCap CustomEndCap
{
get
{
IntPtr lineCap;
int status = Gdip.GdipGetPenCustomEndCap(new HandleRef(this, NativePen), out lineCap);
Gdip.CheckStatus(status);
return CustomLineCap.CreateCustomLineCapObject(lineCap);
}
set
{
if (_immutable)
{
throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen)));
}
int status = Gdip.GdipSetPenCustomEndCap(
new HandleRef(this, NativePen),
new HandleRef(value, (value == null) ? IntPtr.Zero : value.nativeCap));
Gdip.CheckStatus(status);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
public partial class Pen
{
/// <summary>
/// Gets or sets a custom cap style to use at the beginning of lines drawn with this <see cref='Pen'/>.
/// </summary>
public CustomLineCap CustomStartCap
{
get
{
IntPtr lineCap;
int status = Gdip.GdipGetPenCustomStartCap(new HandleRef(this, NativePen), out lineCap);
Gdip.CheckStatus(status);
return CustomLineCap.CreateCustomLineCapObject(lineCap);
}
set
{
if (_immutable)
{
throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen)));
}
int status = Gdip.GdipSetPenCustomStartCap(new HandleRef(this, NativePen),
new HandleRef(value, (value == null) ? IntPtr.Zero : value.nativeCap));
Gdip.CheckStatus(status);
}
}
/// <summary>
/// Gets or sets a custom cap style to use at the end of lines drawn with this <see cref='Pen'/>.
/// </summary>
public CustomLineCap CustomEndCap
{
get
{
IntPtr lineCap;
int status = Gdip.GdipGetPenCustomEndCap(new HandleRef(this, NativePen), out lineCap);
Gdip.CheckStatus(status);
return CustomLineCap.CreateCustomLineCapObject(lineCap);
}
set
{
if (_immutable)
{
throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen)));
}
int status = Gdip.GdipSetPenCustomEndCap(
new HandleRef(this, NativePen),
new HandleRef(value, (value == null) ? IntPtr.Zero : value.nativeCap));
Gdip.CheckStatus(status);
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ConvertToUInt64RoundToPositiveInfinity.Vector128.Double.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ConvertToUInt64RoundToPositiveInfinity_Vector128_Double()
{
var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double testClass)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar1;
private Vector128<Double> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double();
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(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__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double();
fixed (Vector128<Double>* pFld1 = &test._fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Double[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ConvertToUInt64RoundToPositiveInfinity(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity)}<UInt64>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ConvertToUInt64RoundToPositiveInfinity_Vector128_Double()
{
var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double testClass)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar1;
private Vector128<Double> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double();
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(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__ConvertToUInt64RoundToPositiveInfinity_Vector128_Double();
fixed (Vector128<Double>* pFld1 = &test._fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity(
AdvSimd.LoadVector128((Double*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Double[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ConvertToUInt64RoundToPositiveInfinity(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ConvertToUInt64RoundToPositiveInfinity)}<UInt64>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/Generics/Locals/instance_passing_struct01.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 struct Gen<T>
{
public T PassAsIn(T t)
{
return t;
}
public T PassAsRef(ref T t, T Fld2)
{
T temp = t;
t = Fld2;
return temp;
}
public void PassAsOut(out T t, T Fld2)
{
t = Fld2;
}
public void PassAsParameter(T t1, T t2)
{
T Fld1 = t1;
T Fld2 = t2;
T temp = t1;
Test_instance_passing_struct01.Eval(Fld1.Equals(PassAsIn(temp)));
Test_instance_passing_struct01.Eval(Fld1.Equals(PassAsRef(ref temp, Fld2)));
Test_instance_passing_struct01.Eval(Fld2.Equals(temp));
temp = t1;
PassAsOut(out temp, Fld2);
Test_instance_passing_struct01.Eval(Fld2.Equals(temp));
}
}
public class Test_instance_passing_struct01
{
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 = -1;
new Gen<int>().PassAsParameter(_int1, _int2);
double _double1 = 1;
double _double2 = -1;
new Gen<double>().PassAsParameter(_double1, _double2);
string _string1 = "string1";
string _string2 = "string2";
new Gen<string>().PassAsParameter(_string1, _string2);
object _object1 = (object)_string1;
object _object2 = (object)_string2;
new Gen<object>().PassAsParameter(_object1, _object2);
Guid _Guid1 = new Guid(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
Guid _Guid2 = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
new Gen<Guid>().PassAsParameter(_Guid1, _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 struct Gen<T>
{
public T PassAsIn(T t)
{
return t;
}
public T PassAsRef(ref T t, T Fld2)
{
T temp = t;
t = Fld2;
return temp;
}
public void PassAsOut(out T t, T Fld2)
{
t = Fld2;
}
public void PassAsParameter(T t1, T t2)
{
T Fld1 = t1;
T Fld2 = t2;
T temp = t1;
Test_instance_passing_struct01.Eval(Fld1.Equals(PassAsIn(temp)));
Test_instance_passing_struct01.Eval(Fld1.Equals(PassAsRef(ref temp, Fld2)));
Test_instance_passing_struct01.Eval(Fld2.Equals(temp));
temp = t1;
PassAsOut(out temp, Fld2);
Test_instance_passing_struct01.Eval(Fld2.Equals(temp));
}
}
public class Test_instance_passing_struct01
{
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 = -1;
new Gen<int>().PassAsParameter(_int1, _int2);
double _double1 = 1;
double _double2 = -1;
new Gen<double>().PassAsParameter(_double1, _double2);
string _string1 = "string1";
string _string2 = "string2";
new Gen<string>().PassAsParameter(_string1, _string2);
object _object1 = (object)_string1;
object _object2 = (object)_string2;
new Gen<object>().PassAsParameter(_object1, _object2);
Guid _Guid1 = new Guid(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
Guid _Guid2 = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
new Gen<Guid>().PassAsParameter(_Guid1, _Guid2);
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.ECDsa.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.CodeAnalysis;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
internal partial class CmsSignature
{
static partial void PrepareRegistrationECDsa(Dictionary<string, CmsSignature> lookup)
{
lookup.Add(Oids.ECDsaWithSha1, new ECDsaCmsSignature(Oids.ECDsaWithSha1, HashAlgorithmName.SHA1));
lookup.Add(Oids.ECDsaWithSha256, new ECDsaCmsSignature(Oids.ECDsaWithSha256, HashAlgorithmName.SHA256));
lookup.Add(Oids.ECDsaWithSha384, new ECDsaCmsSignature(Oids.ECDsaWithSha384, HashAlgorithmName.SHA384));
lookup.Add(Oids.ECDsaWithSha512, new ECDsaCmsSignature(Oids.ECDsaWithSha512, HashAlgorithmName.SHA512));
lookup.Add(Oids.EcPublicKey, new ECDsaCmsSignature(null, default));
}
private sealed partial class ECDsaCmsSignature : CmsSignature
{
private readonly HashAlgorithmName _expectedDigest;
private readonly string? _signatureAlgorithm;
internal override RSASignaturePadding? SignaturePadding => null;
internal ECDsaCmsSignature(string? signatureAlgorithm, HashAlgorithmName expectedDigest)
{
_signatureAlgorithm = signatureAlgorithm;
_expectedDigest = expectedDigest;
}
protected override bool VerifyKeyType(AsymmetricAlgorithm key)
{
return (key as ECDsa) != null;
}
internal override bool VerifySignature(
#if NETCOREAPP || NETSTANDARD2_1
ReadOnlySpan<byte> valueHash,
ReadOnlyMemory<byte> signature,
#else
byte[] valueHash,
byte[] signature,
#endif
string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
ReadOnlyMemory<byte>? signatureParameters,
X509Certificate2 certificate)
{
if (_expectedDigest != digestAlgorithmName)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_Cms_InvalidSignerHashForSignatureAlg,
digestAlgorithmOid,
_signatureAlgorithm));
}
ECDsa? key = certificate.GetECDsaPublicKey();
if (key == null)
{
return false;
}
int bufSize;
checked
{
// fieldSize = ceil(KeySizeBits / 8);
int fieldSize = (key.KeySize + 7) / 8;
bufSize = 2 * fieldSize;
}
#if NETCOREAPP || NETSTANDARD2_1
byte[] rented = CryptoPool.Rent(bufSize);
Span<byte> ieee = new Span<byte>(rented, 0, bufSize);
try
{
#else
byte[] ieee = new byte[bufSize];
#endif
if (!DsaDerToIeee(signature, ieee))
{
return false;
}
return key.VerifyHash(valueHash, ieee);
#if NETCOREAPP || NETSTANDARD2_1
}
finally
{
CryptoPool.Return(rented, bufSize);
}
#endif
}
protected override bool Sign(
#if NETCOREAPP || NETSTANDARD2_1
ReadOnlySpan<byte> dataHash,
#else
byte[] dataHash,
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
AsymmetricAlgorithm? certKey,
bool silent,
[NotNullWhen(true)] out string? signatureAlgorithm,
[NotNullWhen(true)] out byte[]? signatureValue,
out byte[]? signatureParameters)
{
signatureParameters = null;
// If there's no private key, fall back to the public key for a "no private key" exception.
ECDsa? key = certKey as ECDsa ??
PkcsPal.Instance.GetPrivateKeyForSigning<ECDsa>(certificate, silent) ??
certificate.GetECDsaPublicKey();
if (key == null)
{
signatureAlgorithm = null;
signatureValue = null;
return false;
}
string? oidValue =
hashAlgorithmName == HashAlgorithmName.SHA1 ? Oids.ECDsaWithSha1 :
hashAlgorithmName == HashAlgorithmName.SHA256 ? Oids.ECDsaWithSha256 :
hashAlgorithmName == HashAlgorithmName.SHA384 ? Oids.ECDsaWithSha384 :
hashAlgorithmName == HashAlgorithmName.SHA512 ? Oids.ECDsaWithSha512 :
null;
if (oidValue == null)
{
signatureAlgorithm = null;
signatureValue = null;
return false;
}
signatureAlgorithm = oidValue;
#if NETCOREAPP || NETSTANDARD2_1
int bufSize;
checked
{
// fieldSize = ceil(KeySizeBits / 8);
int fieldSize = (key.KeySize + 7) / 8;
bufSize = 2 * fieldSize;
}
byte[] rented = CryptoPool.Rent(bufSize);
int bytesWritten = 0;
try
{
if (key.TrySignHash(dataHash, rented, out bytesWritten))
{
var signedHash = new ReadOnlySpan<byte>(rented, 0, bytesWritten);
if (key != null && !certificate.GetECDsaPublicKey()!.VerifyHash(dataHash, signedHash))
{
// key did not match certificate
signatureValue = null;
return false;
}
signatureValue = DsaIeeeToDer(signedHash);
return true;
}
}
finally
{
CryptoPool.Return(rented, bytesWritten);
}
#endif
signatureValue = DsaIeeeToDer(key.SignHash(
#if NETCOREAPP || NETSTANDARD2_1
dataHash.ToArray()
#else
dataHash
#endif
));
return true;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
internal partial class CmsSignature
{
static partial void PrepareRegistrationECDsa(Dictionary<string, CmsSignature> lookup)
{
lookup.Add(Oids.ECDsaWithSha1, new ECDsaCmsSignature(Oids.ECDsaWithSha1, HashAlgorithmName.SHA1));
lookup.Add(Oids.ECDsaWithSha256, new ECDsaCmsSignature(Oids.ECDsaWithSha256, HashAlgorithmName.SHA256));
lookup.Add(Oids.ECDsaWithSha384, new ECDsaCmsSignature(Oids.ECDsaWithSha384, HashAlgorithmName.SHA384));
lookup.Add(Oids.ECDsaWithSha512, new ECDsaCmsSignature(Oids.ECDsaWithSha512, HashAlgorithmName.SHA512));
lookup.Add(Oids.EcPublicKey, new ECDsaCmsSignature(null, default));
}
private sealed partial class ECDsaCmsSignature : CmsSignature
{
private readonly HashAlgorithmName _expectedDigest;
private readonly string? _signatureAlgorithm;
internal override RSASignaturePadding? SignaturePadding => null;
internal ECDsaCmsSignature(string? signatureAlgorithm, HashAlgorithmName expectedDigest)
{
_signatureAlgorithm = signatureAlgorithm;
_expectedDigest = expectedDigest;
}
protected override bool VerifyKeyType(AsymmetricAlgorithm key)
{
return (key as ECDsa) != null;
}
internal override bool VerifySignature(
#if NETCOREAPP || NETSTANDARD2_1
ReadOnlySpan<byte> valueHash,
ReadOnlyMemory<byte> signature,
#else
byte[] valueHash,
byte[] signature,
#endif
string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
ReadOnlyMemory<byte>? signatureParameters,
X509Certificate2 certificate)
{
if (_expectedDigest != digestAlgorithmName)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_Cms_InvalidSignerHashForSignatureAlg,
digestAlgorithmOid,
_signatureAlgorithm));
}
ECDsa? key = certificate.GetECDsaPublicKey();
if (key == null)
{
return false;
}
int bufSize;
checked
{
// fieldSize = ceil(KeySizeBits / 8);
int fieldSize = (key.KeySize + 7) / 8;
bufSize = 2 * fieldSize;
}
#if NETCOREAPP || NETSTANDARD2_1
byte[] rented = CryptoPool.Rent(bufSize);
Span<byte> ieee = new Span<byte>(rented, 0, bufSize);
try
{
#else
byte[] ieee = new byte[bufSize];
#endif
if (!DsaDerToIeee(signature, ieee))
{
return false;
}
return key.VerifyHash(valueHash, ieee);
#if NETCOREAPP || NETSTANDARD2_1
}
finally
{
CryptoPool.Return(rented, bufSize);
}
#endif
}
protected override bool Sign(
#if NETCOREAPP || NETSTANDARD2_1
ReadOnlySpan<byte> dataHash,
#else
byte[] dataHash,
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
AsymmetricAlgorithm? certKey,
bool silent,
[NotNullWhen(true)] out string? signatureAlgorithm,
[NotNullWhen(true)] out byte[]? signatureValue,
out byte[]? signatureParameters)
{
signatureParameters = null;
// If there's no private key, fall back to the public key for a "no private key" exception.
ECDsa? key = certKey as ECDsa ??
PkcsPal.Instance.GetPrivateKeyForSigning<ECDsa>(certificate, silent) ??
certificate.GetECDsaPublicKey();
if (key == null)
{
signatureAlgorithm = null;
signatureValue = null;
return false;
}
string? oidValue =
hashAlgorithmName == HashAlgorithmName.SHA1 ? Oids.ECDsaWithSha1 :
hashAlgorithmName == HashAlgorithmName.SHA256 ? Oids.ECDsaWithSha256 :
hashAlgorithmName == HashAlgorithmName.SHA384 ? Oids.ECDsaWithSha384 :
hashAlgorithmName == HashAlgorithmName.SHA512 ? Oids.ECDsaWithSha512 :
null;
if (oidValue == null)
{
signatureAlgorithm = null;
signatureValue = null;
return false;
}
signatureAlgorithm = oidValue;
#if NETCOREAPP || NETSTANDARD2_1
int bufSize;
checked
{
// fieldSize = ceil(KeySizeBits / 8);
int fieldSize = (key.KeySize + 7) / 8;
bufSize = 2 * fieldSize;
}
byte[] rented = CryptoPool.Rent(bufSize);
int bytesWritten = 0;
try
{
if (key.TrySignHash(dataHash, rented, out bytesWritten))
{
var signedHash = new ReadOnlySpan<byte>(rented, 0, bytesWritten);
if (key != null && !certificate.GetECDsaPublicKey()!.VerifyHash(dataHash, signedHash))
{
// key did not match certificate
signatureValue = null;
return false;
}
signatureValue = DsaIeeeToDer(signedHash);
return true;
}
}
finally
{
CryptoPool.Return(rented, bytesWritten);
}
#endif
signatureValue = DsaIeeeToDer(key.SignHash(
#if NETCOREAPP || NETSTANDARD2_1
dataHash.ToArray()
#else
dataHash
#endif
));
return true;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Speech/src/Recognition/AudioLevelUpdatedEventArgs.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.Speech.Recognition
{
// EventArgs used in the AudioLevelUpdatedEventArgs event.
public class AudioLevelUpdatedEventArgs : EventArgs
{
#region Constructors
internal AudioLevelUpdatedEventArgs(int audioLevel)
{
_audioLevel = audioLevel;
}
#endregion
#region public Properties
public int AudioLevel
{
get { return _audioLevel; }
}
#endregion
#region Private Fields
private int _audioLevel;
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Speech.Recognition
{
// EventArgs used in the AudioLevelUpdatedEventArgs event.
public class AudioLevelUpdatedEventArgs : EventArgs
{
#region Constructors
internal AudioLevelUpdatedEventArgs(int audioLevel)
{
_audioLevel = audioLevel;
}
#endregion
#region public Properties
public int AudioLevel
{
get { return _audioLevel; }
}
#endregion
#region Private Fields
private int _audioLevel;
#endregion
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.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.Net;
using System.Net.Cache;
using System.Runtime.Versioning;
namespace System.Xml
{
// Resolves external XML resources named by a Uniform Resource Identifier (URI).
public partial class XmlUrlResolver : XmlResolver
{
private static XmlDownloadManager? s_downloadManager;
private ICredentials? _credentials;
private IWebProxy? _proxy;
private static XmlDownloadManager DownloadManager =>
s_downloadManager ??
Interlocked.CompareExchange(ref s_downloadManager, new XmlDownloadManager(), null) ??
s_downloadManager;
public XmlUrlResolver() { }
[UnsupportedOSPlatform("browser")]
public override ICredentials? Credentials
{
set { _credentials = value; }
}
[UnsupportedOSPlatform("browser")]
public IWebProxy? Proxy
{
set { _proxy = value; }
}
public RequestCachePolicy CachePolicy
{
set { } // nop, as caching isn't implemented
}
// Maps a URI to an Object containing the actual resource.
public override object? GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn)
{
if (ofObjectToReturn is null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object))
{
return DownloadManager.GetStream(absoluteUri, _credentials, _proxy);
}
throw new XmlException(SR.Xml_UnsupportedClass, string.Empty);
}
public override Uri ResolveUri(Uri? baseUri, string? relativeUri) =>
base.ResolveUri(baseUri, relativeUri);
}
}
| // 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.Net;
using System.Net.Cache;
using System.Runtime.Versioning;
namespace System.Xml
{
// Resolves external XML resources named by a Uniform Resource Identifier (URI).
public partial class XmlUrlResolver : XmlResolver
{
private static XmlDownloadManager? s_downloadManager;
private ICredentials? _credentials;
private IWebProxy? _proxy;
private static XmlDownloadManager DownloadManager =>
s_downloadManager ??
Interlocked.CompareExchange(ref s_downloadManager, new XmlDownloadManager(), null) ??
s_downloadManager;
public XmlUrlResolver() { }
[UnsupportedOSPlatform("browser")]
public override ICredentials? Credentials
{
set { _credentials = value; }
}
[UnsupportedOSPlatform("browser")]
public IWebProxy? Proxy
{
set { _proxy = value; }
}
public RequestCachePolicy CachePolicy
{
set { } // nop, as caching isn't implemented
}
// Maps a URI to an Object containing the actual resource.
public override object? GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn)
{
if (ofObjectToReturn is null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object))
{
return DownloadManager.GetStream(absoluteUri, _credentials, _proxy);
}
throw new XmlException(SR.Xml_UnsupportedClass, string.Empty);
}
public override Uri ResolveUri(Uri? baseUri, string? relativeUri) =>
base.ResolveUri(baseUri, relativeUri);
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/TCNewLineChars.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 XmlCoreTest.Common;
using Xunit;
namespace System.Xml.Tests
{
public class TCNewLineChars
{
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_1(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = "\x9";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, "\x9", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test\x9NewLine</root>"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_2(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = " ";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, " ", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test NewLine</root>"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_3(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = "\xA";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, "\xA", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test\xANewLine</root>"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_4(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = "\xD";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, "\xD", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test\xDNewLine</root>"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_5(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = "\x20";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, "\x20", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test\x20NewLine</root>"));
}
[Theory]
[XmlWriterInlineData("<")]
[XmlWriterInlineData("&")]
[XmlWriterInlineData("<!--")]
public void NewLineChars_6(XmlWriterUtils utils, string newLineChars)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.CloseOutput = true;
wSettings.NewLineChars = newLineChars;
XmlWriter w = null;
try
{
w = utils.CreateWriter(wSettings);
}
catch (ArgumentException e)
{
CError.WriteLineIgnore("Exception: " + e.ToString());
return;
}
CError.WriteLine("Did not throw ArgumentException");
Assert.True((utils.WriterType == WriterType.CharCheckingWriter));
}
}
}
| // 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 XmlCoreTest.Common;
using Xunit;
namespace System.Xml.Tests
{
public class TCNewLineChars
{
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_1(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = "\x9";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, "\x9", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test\x9NewLine</root>"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_2(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = " ";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, " ", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test NewLine</root>"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_3(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = "\xA";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, "\xA", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test\xANewLine</root>"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_4(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = "\xD";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, "\xD", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test\xDNewLine</root>"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineChars_5(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineChars = "\x20";
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineChars, "\x20", "Mismatch in NewLineChars");
w.WriteStartElement("root");
w.WriteString("Test\r\nNewLine");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root>Test\x20NewLine</root>"));
}
[Theory]
[XmlWriterInlineData("<")]
[XmlWriterInlineData("&")]
[XmlWriterInlineData("<!--")]
public void NewLineChars_6(XmlWriterUtils utils, string newLineChars)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.CloseOutput = true;
wSettings.NewLineChars = newLineChars;
XmlWriter w = null;
try
{
w = utils.CreateWriter(wSettings);
}
catch (ArgumentException e)
{
CError.WriteLineIgnore("Exception: " + e.ToString());
return;
}
CError.WriteLine("Did not throw ArgumentException");
Assert.True((utils.WriterType == WriterType.CharCheckingWriter));
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/FunctionalTests/iOS/Simulator/XmlFormatWriterGeneratorAOT/Program.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.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
public static class Program
{
[DllImport("__Internal")]
public static extern void mono_ios_set_summary (string value);
public static async Task<int> Main(string[] args)
{
mono_ios_set_summary($"Starting functional test");
var ds = new DataContractSerializer (typeof (IEnumerable<int>));
using (var xw = XmlWriter.Create (System.IO.Stream.Null))
ds.WriteObject (xw, new int [] { 1, 2, 3 });
Console.WriteLine("Done!");
await Task.Delay(5000);
return 42;
}
}
| // 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.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
public static class Program
{
[DllImport("__Internal")]
public static extern void mono_ios_set_summary (string value);
public static async Task<int> Main(string[] args)
{
mono_ios_set_summary($"Starting functional test");
var ds = new DataContractSerializer (typeof (IEnumerable<int>));
using (var xw = XmlWriter.Create (System.IO.Stream.Null))
ds.WriteObject (xw, new int [] { 1, 2, 3 });
Console.WriteLine("Done!");
await Task.Delay(5000);
return 42;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/NFloatTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Runtime.InteropServices.Tests
{
public class NFloatTests
{
[Fact]
public void Ctor_Empty()
{
NFloat result = new NFloat();
Assert.Equal(0, result.Value);
}
[Fact]
public void Ctor_Float()
{
NFloat result = new NFloat(42.0f);
Assert.Equal(42.0, result.Value);
}
[Fact]
public void Ctor_Double()
{
NFloat result = new NFloat(42.0);
Assert.Equal(42.0, result.Value);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is32BitProcess))]
public void Ctor_Double_OutOfRange()
{
NFloat result = new NFloat(double.MaxValue);
Assert.Equal(float.PositiveInfinity, result.Value);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))]
public void Ctor_Double_LargeValue()
{
NFloat result = new NFloat(double.MaxValue);
Assert.Equal(double.MaxValue, result.Value);
}
[Fact]
public void Epsilon()
{
NFloat result = NFloat.Epsilon;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.Epsilon, result.Value);
}
else
{
Assert.Equal(float.Epsilon, result.Value);
}
}
[Fact]
public void MaxValue()
{
NFloat result = NFloat.MaxValue;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.MaxValue, result.Value);
}
else
{
Assert.Equal(float.MaxValue, result.Value);
}
}
[Fact]
public void MinValue()
{
NFloat result = NFloat.MinValue;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.MinValue, result.Value);
}
else
{
Assert.Equal(float.MinValue, result.Value);
}
}
[Fact]
public void NaN()
{
NFloat result = NFloat.NaN;
Assert.True(double.IsNaN(result.Value));
}
[Fact]
public void NegativeInfinity()
{
NFloat result = NFloat.NegativeInfinity;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.NegativeInfinity, result.Value);
}
else
{
Assert.Equal(float.NegativeInfinity, result.Value);
}
}
[Fact]
public void PositiveInfinity()
{
NFloat result = NFloat.PositiveInfinity;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.PositiveInfinity, result.Value);
}
else
{
Assert.Equal(float.PositiveInfinity, result.Value);
}
}
[Fact]
public unsafe void Size()
{
int size = PlatformDetection.Is32BitProcess ? 4 : 8;
#pragma warning disable xUnit2000 // The value under test here is the sizeof expression
Assert.Equal(size, sizeof(NFloat));
#pragma warning restore xUnit2000
Assert.Equal(size, Marshal.SizeOf<NFloat>());
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public static void op_UnaryPlus(float value)
{
NFloat result = +(new NFloat(value));
Assert.Equal(+value, result.Value);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public static void op_UnaryNegation(float value)
{
NFloat result = -(new NFloat(value));
Assert.Equal(-value, result.Value);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public static void op_Decrement(float value)
{
NFloat result = new NFloat(value);
--result;
if (Environment.Is64BitProcess)
{
Assert.Equal((double)value - 1, result.Value);
}
else
{
Assert.Equal(value - 1, result.Value);
}
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public static void op_Increment(float value)
{
NFloat result = new NFloat(value);
++result;
if (Environment.Is64BitProcess)
{
Assert.Equal((double)value + 1, result.Value);
}
else
{
Assert.Equal(value + 1, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65557", typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid), nameof(PlatformDetection.Is32BitProcess))]
public static void op_Addition(float left, float right)
{
NFloat result = new NFloat(left) + new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left + right, result.Value);
}
else
{
Assert.Equal(left + right, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65557", typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid), nameof(PlatformDetection.Is32BitProcess))]
public static void op_Subtraction(float left, float right)
{
NFloat result = new NFloat(left) - new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left - right, result.Value);
}
else
{
Assert.Equal(left - right, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65557", typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid), nameof(PlatformDetection.Is32BitProcess))]
public static void op_Multiply(float left, float right)
{
NFloat result = new NFloat(left) * new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left * right, result.Value);
}
else
{
Assert.Equal(left * right, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65557", typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid), nameof(PlatformDetection.Is32BitProcess))]
public static void op_Division(float left, float right)
{
NFloat result = new NFloat(left) / new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left / right, result.Value);
}
else
{
Assert.Equal(left / right, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
public static void op_Modulus(float left, float right)
{
NFloat result = new NFloat(left) % new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left % right, result.Value);
}
else
{
Assert.Equal(left % right, result.Value);
}
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_Equality(float left, float right)
{
bool result = new NFloat(left) == new NFloat(right);
Assert.Equal(left == right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_Inequality(float left, float right)
{
bool result = new NFloat(left) != new NFloat(right);
Assert.Equal(left != right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_GreaterThan(float left, float right)
{
bool result = new NFloat(left) > new NFloat(right);
Assert.Equal(left > right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_GreaterThanOrEqual(float left, float right)
{
bool result = new NFloat(left) >= new NFloat(right);
Assert.Equal(left >= right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_LessThan(float left, float right)
{
bool result = new NFloat(left) < new NFloat(right);
Assert.Equal(left < right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_LessThanOrEqual(float left, float right)
{
bool result = new NFloat(left) <= new NFloat(right);
Assert.Equal(left <= right, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void DoubleToNFloat(float value)
{
NFloat result = (NFloat)(double)value;
if (Environment.Is64BitProcess)
{
Assert.Equal(value, result.Value);
}
else
{
Assert.Equal((float)value, result.Value);
}
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToByte(float value)
{
byte result = (byte)new NFloat(value);
Assert.Equal((byte)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToChar(float value)
{
char result = (char)new NFloat(value);
Assert.Equal((char)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToDecimal(float value)
{
decimal result = (decimal)new NFloat(value);
if (Environment.Is64BitProcess)
{
Assert.Equal((decimal)(double)value, result);
}
else
{
Assert.Equal((decimal)value, result);
}
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToInt16(float value)
{
short result = (short)new NFloat(value);
Assert.Equal((short)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToInt32(float value)
{
int result = (int)new NFloat(value);
Assert.Equal((int)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToInt64(float value)
{
long result = (long)new NFloat(value);
Assert.Equal((long)value, result);
}
[Theory]
[InlineData(-4567.0f, Skip = "https://github.com/dotnet/runtime/issues/64386")]
[InlineData(-4567.89101f, Skip = "https://github.com/dotnet/runtime/issues/64386")]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToIntPtr(float value)
{
nint result = (nint)new NFloat(value);
Assert.Equal((nint)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToSByte(float value)
{
sbyte result = (sbyte)new NFloat(value);
Assert.Equal((sbyte)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToSingle(float value)
{
float result = (float)new NFloat(value);
Assert.Equal(value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToUInt16(float value)
{
ushort result = (ushort)new NFloat(value);
Assert.Equal((ushort)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToUInt32(float value)
{
uint result = (uint)new NFloat(value);
Assert.Equal((uint)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToUInt64(float value)
{
ulong result = (ulong)new NFloat(value);
Assert.Equal((ulong)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToUIntPtr(float value)
{
nuint result = (nuint)new NFloat(value);
Assert.Equal((nuint)value, result);
}
[Theory]
[InlineData((byte)0)]
[InlineData((byte)5)]
[InlineData((byte)42)]
[InlineData((byte)127)]
[InlineData((byte)255)]
public void ByteToNFloat(byte value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData('A')]
[InlineData('B')]
[InlineData('C')]
[InlineData('D')]
[InlineData('E')]
public void CharToNFloat(char value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((short)-255)]
[InlineData((short)-127)]
[InlineData((short)0)]
[InlineData((short)127)]
[InlineData((short)255)]
public void Int16ToNFloat(short value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData(-255)]
[InlineData(-127)]
[InlineData(0)]
[InlineData(127)]
[InlineData(255)]
public void Int32ToNFloat(int value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((long)-255)]
[InlineData((long)-127)]
[InlineData((long)0)]
[InlineData((long)127)]
[InlineData((long)255)]
public void Int64ToNFloat(long value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((int)-255)]
[InlineData((int)-127)]
[InlineData((int)0)]
[InlineData((int)127)]
[InlineData((int)255)]
public void IntPtrToNFloat(int value)
{
NFloat result = (nint)value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((sbyte)-127)]
[InlineData((sbyte)-63)]
[InlineData((sbyte)0)]
[InlineData((sbyte)63)]
[InlineData((sbyte)127)]
public void SByteToNFloat(sbyte value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void SingleToNFloat(float value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((ushort)0)]
[InlineData((ushort)5)]
[InlineData((ushort)42)]
[InlineData((ushort)127)]
[InlineData((ushort)255)]
public void UInt16ToNFloat(ushort value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((uint)0)]
[InlineData((uint)5)]
[InlineData((uint)42)]
[InlineData((uint)127)]
[InlineData((uint)255)]
public void UInt32ToNFloat(uint value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((ulong)0)]
[InlineData((ulong)5)]
[InlineData((ulong)42)]
[InlineData((ulong)127)]
[InlineData((ulong)255)]
public void UInt64ToNFloat(ulong value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((uint)0)]
[InlineData((uint)5)]
[InlineData((uint)42)]
[InlineData((uint)127)]
[InlineData((uint)255)]
public void UIntPtrToNFloat(uint value)
{
NFloat result = (nuint)value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToDouble(float value)
{
double result = new NFloat(value);
Assert.Equal(value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsFinite(float value)
{
bool result = NFloat.IsFinite(value);
Assert.Equal(float.IsFinite(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsInfinity(float value)
{
bool result = NFloat.IsInfinity(value);
Assert.Equal(float.IsInfinity(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsNaN(float value)
{
bool result = NFloat.IsNaN(value);
Assert.Equal(float.IsNaN(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsNegative(float value)
{
bool result = NFloat.IsNegative(value);
Assert.Equal(float.IsNegative(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsNegativeInfinity(float value)
{
bool result = NFloat.IsNegativeInfinity(value);
Assert.Equal(float.IsNegativeInfinity(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsNormal(float value)
{
bool result = NFloat.IsNormal(value);
if (Environment.Is64BitProcess)
{
Assert.Equal(double.IsNormal(value), result);
}
else
{
Assert.Equal(float.IsNormal(value), result);
}
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsPositiveInfinity(float value)
{
bool result = NFloat.IsPositiveInfinity(value);
Assert.Equal(float.IsPositiveInfinity(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsSubnormal(float value)
{
bool result = NFloat.IsSubnormal(value);
if (Environment.Is64BitProcess)
{
Assert.Equal(double.IsSubnormal(value), result);
}
else
{
Assert.Equal(float.IsSubnormal(value), result);
}
}
public static IEnumerable<object[]> EqualsData()
{
yield return new object[] { new NFloat(789.0f), new NFloat(789.0f), true };
yield return new object[] { new NFloat(789.0f), new NFloat(-789.0f), false };
yield return new object[] { new NFloat(789.0f), new NFloat(0.0f), false };
yield return new object[] { new NFloat(789.0f), 789.0f, false };
yield return new object[] { new NFloat(789.0f), "789.0", false };
}
[Theory]
[MemberData(nameof(EqualsData))]
public void EqualsTest(NFloat f1, object obj, bool expected)
{
if (obj is NFloat f2)
{
Assert.Equal(expected, f1.Equals((object)f2));
Assert.Equal(expected, f1.Equals(f2));
Assert.Equal(expected, f1.GetHashCode().Equals(f2.GetHashCode()));
}
Assert.Equal(expected, f1.Equals(obj));
}
[Fact]
public void NaNEqualsTest()
{
NFloat f1 = new NFloat(float.NaN);
NFloat f2 = new NFloat(float.NaN);
Assert.Equal(f1.Value.Equals(f2.Value), f1.Equals(f2));
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.NaN)]
public static void ToStringTest64(float value)
{
NFloat nfloat = new NFloat(value);
Assert.Equal(((double)value).ToString(), nfloat.ToString());
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is32BitProcess))]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.NaN)]
public static void ToStringTest32(float value)
{
NFloat nfloat = new NFloat(value);
Assert.Equal(value.ToString(), nfloat.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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Runtime.InteropServices.Tests
{
public class NFloatTests
{
[Fact]
public void Ctor_Empty()
{
NFloat result = new NFloat();
Assert.Equal(0, result.Value);
}
[Fact]
public void Ctor_Float()
{
NFloat result = new NFloat(42.0f);
Assert.Equal(42.0, result.Value);
}
[Fact]
public void Ctor_Double()
{
NFloat result = new NFloat(42.0);
Assert.Equal(42.0, result.Value);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is32BitProcess))]
public void Ctor_Double_OutOfRange()
{
NFloat result = new NFloat(double.MaxValue);
Assert.Equal(float.PositiveInfinity, result.Value);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))]
public void Ctor_Double_LargeValue()
{
NFloat result = new NFloat(double.MaxValue);
Assert.Equal(double.MaxValue, result.Value);
}
[Fact]
public void Epsilon()
{
NFloat result = NFloat.Epsilon;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.Epsilon, result.Value);
}
else
{
Assert.Equal(float.Epsilon, result.Value);
}
}
[Fact]
public void MaxValue()
{
NFloat result = NFloat.MaxValue;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.MaxValue, result.Value);
}
else
{
Assert.Equal(float.MaxValue, result.Value);
}
}
[Fact]
public void MinValue()
{
NFloat result = NFloat.MinValue;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.MinValue, result.Value);
}
else
{
Assert.Equal(float.MinValue, result.Value);
}
}
[Fact]
public void NaN()
{
NFloat result = NFloat.NaN;
Assert.True(double.IsNaN(result.Value));
}
[Fact]
public void NegativeInfinity()
{
NFloat result = NFloat.NegativeInfinity;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.NegativeInfinity, result.Value);
}
else
{
Assert.Equal(float.NegativeInfinity, result.Value);
}
}
[Fact]
public void PositiveInfinity()
{
NFloat result = NFloat.PositiveInfinity;
if (Environment.Is64BitProcess)
{
Assert.Equal(double.PositiveInfinity, result.Value);
}
else
{
Assert.Equal(float.PositiveInfinity, result.Value);
}
}
[Fact]
public unsafe void Size()
{
int size = PlatformDetection.Is32BitProcess ? 4 : 8;
#pragma warning disable xUnit2000 // The value under test here is the sizeof expression
Assert.Equal(size, sizeof(NFloat));
#pragma warning restore xUnit2000
Assert.Equal(size, Marshal.SizeOf<NFloat>());
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public static void op_UnaryPlus(float value)
{
NFloat result = +(new NFloat(value));
Assert.Equal(+value, result.Value);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public static void op_UnaryNegation(float value)
{
NFloat result = -(new NFloat(value));
Assert.Equal(-value, result.Value);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public static void op_Decrement(float value)
{
NFloat result = new NFloat(value);
--result;
if (Environment.Is64BitProcess)
{
Assert.Equal((double)value - 1, result.Value);
}
else
{
Assert.Equal(value - 1, result.Value);
}
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public static void op_Increment(float value)
{
NFloat result = new NFloat(value);
++result;
if (Environment.Is64BitProcess)
{
Assert.Equal((double)value + 1, result.Value);
}
else
{
Assert.Equal(value + 1, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65557", typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid), nameof(PlatformDetection.Is32BitProcess))]
public static void op_Addition(float left, float right)
{
NFloat result = new NFloat(left) + new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left + right, result.Value);
}
else
{
Assert.Equal(left + right, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65557", typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid), nameof(PlatformDetection.Is32BitProcess))]
public static void op_Subtraction(float left, float right)
{
NFloat result = new NFloat(left) - new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left - right, result.Value);
}
else
{
Assert.Equal(left - right, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65557", typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid), nameof(PlatformDetection.Is32BitProcess))]
public static void op_Multiply(float left, float right)
{
NFloat result = new NFloat(left) * new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left * right, result.Value);
}
else
{
Assert.Equal(left * right, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/65557", typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid), nameof(PlatformDetection.Is32BitProcess))]
public static void op_Division(float left, float right)
{
NFloat result = new NFloat(left) / new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left / right, result.Value);
}
else
{
Assert.Equal(left / right, result.Value);
}
}
[Theory]
[InlineData(-4567.0f, 3.14f)]
[InlineData(-4567.89101f, 3.14569f)]
[InlineData(0.0f, 3.14f)]
[InlineData(4567.0f, -3.14f)]
[InlineData(4567.89101f, -3.14569f)]
public static void op_Modulus(float left, float right)
{
NFloat result = new NFloat(left) % new NFloat(right);
if (Environment.Is64BitProcess)
{
Assert.Equal((double)left % right, result.Value);
}
else
{
Assert.Equal(left % right, result.Value);
}
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_Equality(float left, float right)
{
bool result = new NFloat(left) == new NFloat(right);
Assert.Equal(left == right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_Inequality(float left, float right)
{
bool result = new NFloat(left) != new NFloat(right);
Assert.Equal(left != right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_GreaterThan(float left, float right)
{
bool result = new NFloat(left) > new NFloat(right);
Assert.Equal(left > right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_GreaterThanOrEqual(float left, float right)
{
bool result = new NFloat(left) >= new NFloat(right);
Assert.Equal(left >= right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_LessThan(float left, float right)
{
bool result = new NFloat(left) < new NFloat(right);
Assert.Equal(left < right, result);
}
[Theory]
[InlineData(789.0f, 789.0f)]
[InlineData(789.0f, -789.0f)]
[InlineData(789.0f, 0.0f)]
[InlineData(789.0f, 1000.0f)]
public void op_LessThanOrEqual(float left, float right)
{
bool result = new NFloat(left) <= new NFloat(right);
Assert.Equal(left <= right, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void DoubleToNFloat(float value)
{
NFloat result = (NFloat)(double)value;
if (Environment.Is64BitProcess)
{
Assert.Equal(value, result.Value);
}
else
{
Assert.Equal((float)value, result.Value);
}
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToByte(float value)
{
byte result = (byte)new NFloat(value);
Assert.Equal((byte)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToChar(float value)
{
char result = (char)new NFloat(value);
Assert.Equal((char)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToDecimal(float value)
{
decimal result = (decimal)new NFloat(value);
if (Environment.Is64BitProcess)
{
Assert.Equal((decimal)(double)value, result);
}
else
{
Assert.Equal((decimal)value, result);
}
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToInt16(float value)
{
short result = (short)new NFloat(value);
Assert.Equal((short)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToInt32(float value)
{
int result = (int)new NFloat(value);
Assert.Equal((int)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToInt64(float value)
{
long result = (long)new NFloat(value);
Assert.Equal((long)value, result);
}
[Theory]
[InlineData(-4567.0f, Skip = "https://github.com/dotnet/runtime/issues/64386")]
[InlineData(-4567.89101f, Skip = "https://github.com/dotnet/runtime/issues/64386")]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToIntPtr(float value)
{
nint result = (nint)new NFloat(value);
Assert.Equal((nint)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToSByte(float value)
{
sbyte result = (sbyte)new NFloat(value);
Assert.Equal((sbyte)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToSingle(float value)
{
float result = (float)new NFloat(value);
Assert.Equal(value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToUInt16(float value)
{
ushort result = (ushort)new NFloat(value);
Assert.Equal((ushort)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToUInt32(float value)
{
uint result = (uint)new NFloat(value);
Assert.Equal((uint)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToUInt64(float value)
{
ulong result = (ulong)new NFloat(value);
Assert.Equal((ulong)value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToUIntPtr(float value)
{
nuint result = (nuint)new NFloat(value);
Assert.Equal((nuint)value, result);
}
[Theory]
[InlineData((byte)0)]
[InlineData((byte)5)]
[InlineData((byte)42)]
[InlineData((byte)127)]
[InlineData((byte)255)]
public void ByteToNFloat(byte value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData('A')]
[InlineData('B')]
[InlineData('C')]
[InlineData('D')]
[InlineData('E')]
public void CharToNFloat(char value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((short)-255)]
[InlineData((short)-127)]
[InlineData((short)0)]
[InlineData((short)127)]
[InlineData((short)255)]
public void Int16ToNFloat(short value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData(-255)]
[InlineData(-127)]
[InlineData(0)]
[InlineData(127)]
[InlineData(255)]
public void Int32ToNFloat(int value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((long)-255)]
[InlineData((long)-127)]
[InlineData((long)0)]
[InlineData((long)127)]
[InlineData((long)255)]
public void Int64ToNFloat(long value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((int)-255)]
[InlineData((int)-127)]
[InlineData((int)0)]
[InlineData((int)127)]
[InlineData((int)255)]
public void IntPtrToNFloat(int value)
{
NFloat result = (nint)value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((sbyte)-127)]
[InlineData((sbyte)-63)]
[InlineData((sbyte)0)]
[InlineData((sbyte)63)]
[InlineData((sbyte)127)]
public void SByteToNFloat(sbyte value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void SingleToNFloat(float value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((ushort)0)]
[InlineData((ushort)5)]
[InlineData((ushort)42)]
[InlineData((ushort)127)]
[InlineData((ushort)255)]
public void UInt16ToNFloat(ushort value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((uint)0)]
[InlineData((uint)5)]
[InlineData((uint)42)]
[InlineData((uint)127)]
[InlineData((uint)255)]
public void UInt32ToNFloat(uint value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((ulong)0)]
[InlineData((ulong)5)]
[InlineData((ulong)42)]
[InlineData((ulong)127)]
[InlineData((ulong)255)]
public void UInt64ToNFloat(ulong value)
{
NFloat result = value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData((uint)0)]
[InlineData((uint)5)]
[InlineData((uint)42)]
[InlineData((uint)127)]
[InlineData((uint)255)]
public void UIntPtrToNFloat(uint value)
{
NFloat result = (nuint)value;
Assert.Equal(value, result.Value);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
public void NFloatToDouble(float value)
{
double result = new NFloat(value);
Assert.Equal(value, result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsFinite(float value)
{
bool result = NFloat.IsFinite(value);
Assert.Equal(float.IsFinite(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsInfinity(float value)
{
bool result = NFloat.IsInfinity(value);
Assert.Equal(float.IsInfinity(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsNaN(float value)
{
bool result = NFloat.IsNaN(value);
Assert.Equal(float.IsNaN(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsNegative(float value)
{
bool result = NFloat.IsNegative(value);
Assert.Equal(float.IsNegative(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsNegativeInfinity(float value)
{
bool result = NFloat.IsNegativeInfinity(value);
Assert.Equal(float.IsNegativeInfinity(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsNormal(float value)
{
bool result = NFloat.IsNormal(value);
if (Environment.Is64BitProcess)
{
Assert.Equal(double.IsNormal(value), result);
}
else
{
Assert.Equal(float.IsNormal(value), result);
}
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsPositiveInfinity(float value)
{
bool result = NFloat.IsPositiveInfinity(value);
Assert.Equal(float.IsPositiveInfinity(value), result);
}
[Theory]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.Epsilon)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
[InlineData(float.NaN)]
public void IsSubnormal(float value)
{
bool result = NFloat.IsSubnormal(value);
if (Environment.Is64BitProcess)
{
Assert.Equal(double.IsSubnormal(value), result);
}
else
{
Assert.Equal(float.IsSubnormal(value), result);
}
}
public static IEnumerable<object[]> EqualsData()
{
yield return new object[] { new NFloat(789.0f), new NFloat(789.0f), true };
yield return new object[] { new NFloat(789.0f), new NFloat(-789.0f), false };
yield return new object[] { new NFloat(789.0f), new NFloat(0.0f), false };
yield return new object[] { new NFloat(789.0f), 789.0f, false };
yield return new object[] { new NFloat(789.0f), "789.0", false };
}
[Theory]
[MemberData(nameof(EqualsData))]
public void EqualsTest(NFloat f1, object obj, bool expected)
{
if (obj is NFloat f2)
{
Assert.Equal(expected, f1.Equals((object)f2));
Assert.Equal(expected, f1.Equals(f2));
Assert.Equal(expected, f1.GetHashCode().Equals(f2.GetHashCode()));
}
Assert.Equal(expected, f1.Equals(obj));
}
[Fact]
public void NaNEqualsTest()
{
NFloat f1 = new NFloat(float.NaN);
NFloat f2 = new NFloat(float.NaN);
Assert.Equal(f1.Value.Equals(f2.Value), f1.Equals(f2));
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.NaN)]
public static void ToStringTest64(float value)
{
NFloat nfloat = new NFloat(value);
Assert.Equal(((double)value).ToString(), nfloat.ToString());
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is32BitProcess))]
[InlineData(-4567.0f)]
[InlineData(-4567.89101f)]
[InlineData(0.0f)]
[InlineData(4567.0f)]
[InlineData(4567.89101f)]
[InlineData(float.NaN)]
public static void ToStringTest32(float value)
{
NFloat nfloat = new NFloat(value);
Assert.Equal(value.ToString(), nfloat.ToString());
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteVisitor.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 Microsoft.Extensions.DependencyInjection.ServiceLookup
{
internal abstract class CallSiteVisitor<TArgument, TResult>
{
private readonly StackGuard _stackGuard;
protected CallSiteVisitor()
{
_stackGuard = new StackGuard();
}
protected virtual TResult VisitCallSite(ServiceCallSite callSite, TArgument argument)
{
if (!_stackGuard.TryEnterOnCurrentStack())
{
return _stackGuard.RunOnEmptyStack((c, a) => VisitCallSite(c, a), callSite, argument);
}
switch (callSite.Cache.Location)
{
case CallSiteResultCacheLocation.Root:
return VisitRootCache(callSite, argument);
case CallSiteResultCacheLocation.Scope:
return VisitScopeCache(callSite, argument);
case CallSiteResultCacheLocation.Dispose:
return VisitDisposeCache(callSite, argument);
case CallSiteResultCacheLocation.None:
return VisitNoCache(callSite, argument);
default:
throw new ArgumentOutOfRangeException();
}
}
protected virtual TResult VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
{
switch (callSite.Kind)
{
case CallSiteKind.Factory:
return VisitFactory((FactoryCallSite)callSite, argument);
case CallSiteKind.IEnumerable:
return VisitIEnumerable((IEnumerableCallSite)callSite, argument);
case CallSiteKind.Constructor:
return VisitConstructor((ConstructorCallSite)callSite, argument);
case CallSiteKind.Constant:
return VisitConstant((ConstantCallSite)callSite, argument);
case CallSiteKind.ServiceProvider:
return VisitServiceProvider((ServiceProviderCallSite)callSite, argument);
default:
throw new NotSupportedException(SR.Format(SR.CallSiteTypeNotSupported, callSite.GetType()));
}
}
protected virtual TResult VisitNoCache(ServiceCallSite callSite, TArgument argument)
{
return VisitCallSiteMain(callSite, argument);
}
protected virtual TResult VisitDisposeCache(ServiceCallSite callSite, TArgument argument)
{
return VisitCallSiteMain(callSite, argument);
}
protected virtual TResult VisitRootCache(ServiceCallSite callSite, TArgument argument)
{
return VisitCallSiteMain(callSite, argument);
}
protected virtual TResult VisitScopeCache(ServiceCallSite callSite, TArgument argument)
{
return VisitCallSiteMain(callSite, argument);
}
protected abstract TResult VisitConstructor(ConstructorCallSite constructorCallSite, TArgument argument);
protected abstract TResult VisitConstant(ConstantCallSite constantCallSite, TArgument argument);
protected abstract TResult VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, TArgument argument);
protected abstract TResult VisitIEnumerable(IEnumerableCallSite enumerableCallSite, TArgument argument);
protected abstract TResult VisitFactory(FactoryCallSite factoryCallSite, TArgument argument);
}
}
| // 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 Microsoft.Extensions.DependencyInjection.ServiceLookup
{
internal abstract class CallSiteVisitor<TArgument, TResult>
{
private readonly StackGuard _stackGuard;
protected CallSiteVisitor()
{
_stackGuard = new StackGuard();
}
protected virtual TResult VisitCallSite(ServiceCallSite callSite, TArgument argument)
{
if (!_stackGuard.TryEnterOnCurrentStack())
{
return _stackGuard.RunOnEmptyStack((c, a) => VisitCallSite(c, a), callSite, argument);
}
switch (callSite.Cache.Location)
{
case CallSiteResultCacheLocation.Root:
return VisitRootCache(callSite, argument);
case CallSiteResultCacheLocation.Scope:
return VisitScopeCache(callSite, argument);
case CallSiteResultCacheLocation.Dispose:
return VisitDisposeCache(callSite, argument);
case CallSiteResultCacheLocation.None:
return VisitNoCache(callSite, argument);
default:
throw new ArgumentOutOfRangeException();
}
}
protected virtual TResult VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
{
switch (callSite.Kind)
{
case CallSiteKind.Factory:
return VisitFactory((FactoryCallSite)callSite, argument);
case CallSiteKind.IEnumerable:
return VisitIEnumerable((IEnumerableCallSite)callSite, argument);
case CallSiteKind.Constructor:
return VisitConstructor((ConstructorCallSite)callSite, argument);
case CallSiteKind.Constant:
return VisitConstant((ConstantCallSite)callSite, argument);
case CallSiteKind.ServiceProvider:
return VisitServiceProvider((ServiceProviderCallSite)callSite, argument);
default:
throw new NotSupportedException(SR.Format(SR.CallSiteTypeNotSupported, callSite.GetType()));
}
}
protected virtual TResult VisitNoCache(ServiceCallSite callSite, TArgument argument)
{
return VisitCallSiteMain(callSite, argument);
}
protected virtual TResult VisitDisposeCache(ServiceCallSite callSite, TArgument argument)
{
return VisitCallSiteMain(callSite, argument);
}
protected virtual TResult VisitRootCache(ServiceCallSite callSite, TArgument argument)
{
return VisitCallSiteMain(callSite, argument);
}
protected virtual TResult VisitScopeCache(ServiceCallSite callSite, TArgument argument)
{
return VisitCallSiteMain(callSite, argument);
}
protected abstract TResult VisitConstructor(ConstructorCallSite constructorCallSite, TArgument argument);
protected abstract TResult VisitConstant(ConstantCallSite constantCallSite, TArgument argument);
protected abstract TResult VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, TArgument argument);
protected abstract TResult VisitIEnumerable(IEnumerableCallSite enumerableCallSite, TArgument argument);
protected abstract TResult VisitFactory(FactoryCallSite factoryCallSite, TArgument argument);
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/GC/Performance/Tests/MidLife.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.Text;
public class AppendTest
{
public static string[] _strings=null;
public static int _numStrings = 10000000;
public static Random rand = new Random(1);
const int NumIterations = 5000;
public static string CreateString(int num)
{
int length = rand.Next(1, 20);
char[] ch = new char[length];
for(int i = 0; i<length; i++)
{
ch[i] = (char) rand.Next(32, 127);
}
_strings[num] = new String(ch);
return _strings[num];
}
public static void CreateTable()
{
// Creates an array of character arrays, and an array of strings
// corresponding to those char arrays.
_strings = new String[_numStrings];
for(int i=0; i<_numStrings; i++)
{
string str = CreateString(i);
}
}
public static void AppendString(long iterations)
{
for (long i=0; i<iterations; i++)
{
StringBuilder sb = new StringBuilder();
for (int j=0; j<10; j++)
{
sb.Append(_strings[(i+j)%_numStrings]);
}
}
}
public static void Main(string [] real_args)
{
CreateTable();
// warmup
AppendString(100);
AppendString(NumIterations);
}
}
| // 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.Text;
public class AppendTest
{
public static string[] _strings=null;
public static int _numStrings = 10000000;
public static Random rand = new Random(1);
const int NumIterations = 5000;
public static string CreateString(int num)
{
int length = rand.Next(1, 20);
char[] ch = new char[length];
for(int i = 0; i<length; i++)
{
ch[i] = (char) rand.Next(32, 127);
}
_strings[num] = new String(ch);
return _strings[num];
}
public static void CreateTable()
{
// Creates an array of character arrays, and an array of strings
// corresponding to those char arrays.
_strings = new String[_numStrings];
for(int i=0; i<_numStrings; i++)
{
string str = CreateString(i);
}
}
public static void AppendString(long iterations)
{
for (long i=0; i<iterations; i++)
{
StringBuilder sb = new StringBuilder();
for (int j=0; j<10; j++)
{
sb.Append(_strings[(i+j)%_numStrings]);
}
}
}
public static void Main(string [] real_args)
{
CreateTable();
// warmup
AppendString(100);
AppendString(NumIterations);
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Browser.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.Cryptography
{
internal static partial class CapiHelper
{
// Return PROV_RSA_AES, in case any compat case pops up.
internal const int DefaultRsaProviderType = 24;
}
}
| // 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.Cryptography
{
internal static partial class CapiHelper
{
// Return PROV_RSA_AES, in case any compat case pops up.
internal const int DefaultRsaProviderType = 24;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/null/box-unbox-null044.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System;
internal class NullableTest
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((WithOnlyFXTypeStruct?)o) == null;
}
private static int Main()
{
WithOnlyFXTypeStruct? s = null;
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System;
internal class NullableTest
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((WithOnlyFXTypeStruct?)o) == null;
}
private static int Main()
{
WithOnlyFXTypeStruct? s = null;
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/General/Vector64/Subtract.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 SubtractInt64()
{
var test = new VectorBinaryOpTest__SubtractInt64();
// 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__SubtractInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public Vector64<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__SubtractInt64 testClass)
{
var result = Vector64.Subtract(_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<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = 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 VectorBinaryOpTest__SubtractInt64()
{
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 VectorBinaryOpTest__SubtractInt64()
{
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, new Int64[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Subtract(
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Subtract), new Type[] {
typeof(Vector64<Int64>),
typeof(Vector64<Int64>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Subtract), 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)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Subtract(
_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<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr);
var result = Vector64.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__SubtractInt64();
var result = Vector64.Subtract(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.Subtract(_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.Subtract(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<Int64> op1, Vector64<Int64> op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (long)(left[0] - right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (long)(left[i] - right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Subtract)}<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: ({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 SubtractInt64()
{
var test = new VectorBinaryOpTest__SubtractInt64();
// 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__SubtractInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public Vector64<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__SubtractInt64 testClass)
{
var result = Vector64.Subtract(_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<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = 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 VectorBinaryOpTest__SubtractInt64()
{
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 VectorBinaryOpTest__SubtractInt64()
{
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, new Int64[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Subtract(
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Subtract), new Type[] {
typeof(Vector64<Int64>),
typeof(Vector64<Int64>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Subtract), 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)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Subtract(
_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<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr);
var result = Vector64.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__SubtractInt64();
var result = Vector64.Subtract(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.Subtract(_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.Subtract(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<Int64> op1, Vector64<Int64> op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (long)(left[0] - right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (long)(left[i] - right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Subtract)}<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: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_Equality.UInt16.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_EqualityUInt16()
{
var test = new VectorBooleanBinaryOpTest__op_EqualityUInt16();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBooleanBinaryOpTest__op_EqualityUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public 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(VectorBooleanBinaryOpTest__op_EqualityUInt16 testClass)
{
var result = _fld1 == _fld2;
testClass.ValidateResult(_fld1, _fld2, result);
}
}
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 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 VectorBooleanBinaryOpTest__op_EqualityUInt16()
{
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 VectorBooleanBinaryOpTest__op_EqualityUInt16()
{
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, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr) == Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector256<UInt16>).GetMethod("op_Equality", new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 == _clsVar2;
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = op1 == op2;
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__op_EqualityUInt16();
var result = test._fld1 == test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 == _fld2;
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 == test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= (left[i] == right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Equality<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: ({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_EqualityUInt16()
{
var test = new VectorBooleanBinaryOpTest__op_EqualityUInt16();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBooleanBinaryOpTest__op_EqualityUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public 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(VectorBooleanBinaryOpTest__op_EqualityUInt16 testClass)
{
var result = _fld1 == _fld2;
testClass.ValidateResult(_fld1, _fld2, result);
}
}
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 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 VectorBooleanBinaryOpTest__op_EqualityUInt16()
{
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 VectorBooleanBinaryOpTest__op_EqualityUInt16()
{
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, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr) == Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector256<UInt16>).GetMethod("op_Equality", new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 == _clsVar2;
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = op1 == op2;
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__op_EqualityUInt16();
var result = test._fld1 == test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 == _fld2;
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 == test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= (left[i] == right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Equality<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: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.CoreLib/src/System/Security/Principal/IIdentity.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// All identities will implement this interface
//
namespace System.Security.Principal
{
public interface IIdentity
{
// Access to the name string
string? Name { get; }
// Access to Authentication 'type' info
string? AuthenticationType { get; }
// Determine if this represents the unauthenticated identity
bool IsAuthenticated { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// All identities will implement this interface
//
namespace System.Security.Principal
{
public interface IIdentity
{
// Access to the name string
string? Name { get; }
// Access to Authentication 'type' info
string? AuthenticationType { get; }
// Determine if this represents the unauthenticated identity
bool IsAuthenticated { get; }
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalPropertiesPal.Windows.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.NetworkInformation
{
internal static class IPGlobalPropertiesPal
{
public static IPGlobalProperties GetIPGlobalProperties()
{
return new SystemIPGlobalProperties();
}
}
}
| // 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.NetworkInformation
{
internal static class IPGlobalPropertiesPal
{
public static IPGlobalProperties GetIPGlobalProperties()
{
return new SystemIPGlobalProperties();
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/MultiplyDoublingScalarBySelectedScalarSaturateHigh.Vector64.Int32.Vector64.Int32.1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1()
{
var test = new ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_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(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector64<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1 testClass)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1 testClass)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly byte Imm = 1;
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector64<Int32> _clsVar2;
private Vector64<Int32> _fld1;
private Vector64<Int32> _fld2;
private DataTable _dataTable;
static ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(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.MultiplyDoublingScalarBySelectedScalarSaturateHigh), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1();
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int32> firstOp, Vector64<Int32> secondOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.MultiplyDoublingSaturateHigh(firstOp[0], secondOp[Imm]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh)}<Int32>(Vector64<Int32>, Vector64<Int32>, 1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1()
{
var test = new ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_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(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector64<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1 testClass)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1 testClass)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly byte Imm = 1;
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector64<Int32> _clsVar2;
private Vector64<Int32> _fld1;
private Vector64<Int32> _fld2;
private DataTable _dataTable;
static ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1()
{
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.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(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.MultiplyDoublingScalarBySelectedScalarSaturateHigh), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1();
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmBinaryOpTest__MultiplyDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int32_Vector64_Int32_1();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh(
AdvSimd.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int32> firstOp, Vector64<Int32> secondOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.MultiplyDoublingSaturateHigh(firstOp[0], secondOp[Imm]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.MultiplyDoublingScalarBySelectedScalarSaturateHigh)}<Int32>(Vector64<Int32>, Vector64<Int32>, 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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Insert.Vector64.UInt16.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 Insert_Vector64_UInt16_1()
{
var test = new InsertTest__Insert_Vector64_UInt16_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 InsertTest__Insert_Vector64_UInt16_1
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
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<UInt16, 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<UInt16> _fld1;
public UInt16 _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
testStruct._fld3 = TestLibrary.Generator.GetUInt16();
return testStruct;
}
public void RunStructFldScenario(InsertTest__Insert_Vector64_UInt16_1 testClass)
{
var result = AdvSimd.Insert(_fld1, ElementIndex, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(InsertTest__Insert_Vector64_UInt16_1 testClass)
{
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (UInt16* pFld3 = &_fld3)
{
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)pFld1),
ElementIndex,
*pFld3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly byte ElementIndex = 1;
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static Vector64<UInt16> _clsVar1;
private static UInt16 _clsVar3;
private Vector64<UInt16> _fld1;
private UInt16 _fld3;
private DataTable _dataTable;
static InsertTest__Insert_Vector64_UInt16_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
_clsVar3 = TestLibrary.Generator.GetUInt16();
}
public InsertTest__Insert_Vector64_UInt16_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
_fld3 = TestLibrary.Generator.GetUInt16();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Insert(
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
ElementIndex,
_fld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _fld3, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
ElementIndex,
_fld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _fld3, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
UInt16 op3 = TestLibrary.Generator.GetUInt16();
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Insert), new Type[] { typeof(Vector64<UInt16>), typeof(byte), typeof(UInt16) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
ElementIndex,
op3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, op3, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
UInt16 op3 = TestLibrary.Generator.GetUInt16();
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Insert), new Type[] { typeof(Vector64<UInt16>), typeof(byte), typeof(UInt16) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
ElementIndex,
op3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, op3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Insert(
_clsVar1,
ElementIndex,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1)
fixed (UInt16* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)pClsVar1),
ElementIndex,
*pClsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr);
var op3 = TestLibrary.Generator.GetUInt16();
var result = AdvSimd.Insert(op1, ElementIndex, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr));
var op3 = TestLibrary.Generator.GetUInt16();
var result = AdvSimd.Insert(op1, ElementIndex, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertTest__Insert_Vector64_UInt16_1();
var result = AdvSimd.Insert(test._fld1, ElementIndex, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new InsertTest__Insert_Vector64_UInt16_1();
fixed (Vector64<UInt16>* pFld1 = &test._fld1)
fixed (UInt16* pFld3 = &test._fld3)
{
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)pFld1),
ElementIndex,
*pFld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Insert(_fld1, ElementIndex, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (UInt16* pFld3 = &_fld3)
{
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)pFld1),
ElementIndex,
*pFld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Insert(test._fld1, ElementIndex, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)(&test._fld1)),
ElementIndex,
test._fld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt16> op1, UInt16 op3, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, op3, outArray, method);
}
private void ValidateResult(void* op1, UInt16 op3, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, op3, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16 thirdOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Insert(firstOp, ElementIndex, thirdOp, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Insert)}<UInt16>(Vector64<UInt16>, 1, UInt16): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: {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 Insert_Vector64_UInt16_1()
{
var test = new InsertTest__Insert_Vector64_UInt16_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 InsertTest__Insert_Vector64_UInt16_1
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
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<UInt16, 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<UInt16> _fld1;
public UInt16 _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
testStruct._fld3 = TestLibrary.Generator.GetUInt16();
return testStruct;
}
public void RunStructFldScenario(InsertTest__Insert_Vector64_UInt16_1 testClass)
{
var result = AdvSimd.Insert(_fld1, ElementIndex, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(InsertTest__Insert_Vector64_UInt16_1 testClass)
{
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (UInt16* pFld3 = &_fld3)
{
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)pFld1),
ElementIndex,
*pFld3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly byte ElementIndex = 1;
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static Vector64<UInt16> _clsVar1;
private static UInt16 _clsVar3;
private Vector64<UInt16> _fld1;
private UInt16 _fld3;
private DataTable _dataTable;
static InsertTest__Insert_Vector64_UInt16_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
_clsVar3 = TestLibrary.Generator.GetUInt16();
}
public InsertTest__Insert_Vector64_UInt16_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
_fld3 = TestLibrary.Generator.GetUInt16();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Insert(
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
ElementIndex,
_fld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _fld3, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
ElementIndex,
_fld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _fld3, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
UInt16 op3 = TestLibrary.Generator.GetUInt16();
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Insert), new Type[] { typeof(Vector64<UInt16>), typeof(byte), typeof(UInt16) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
ElementIndex,
op3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, op3, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
UInt16 op3 = TestLibrary.Generator.GetUInt16();
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Insert), new Type[] { typeof(Vector64<UInt16>), typeof(byte), typeof(UInt16) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
ElementIndex,
op3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, op3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Insert(
_clsVar1,
ElementIndex,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1)
fixed (UInt16* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)pClsVar1),
ElementIndex,
*pClsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr);
var op3 = TestLibrary.Generator.GetUInt16();
var result = AdvSimd.Insert(op1, ElementIndex, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr));
var op3 = TestLibrary.Generator.GetUInt16();
var result = AdvSimd.Insert(op1, ElementIndex, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertTest__Insert_Vector64_UInt16_1();
var result = AdvSimd.Insert(test._fld1, ElementIndex, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new InsertTest__Insert_Vector64_UInt16_1();
fixed (Vector64<UInt16>* pFld1 = &test._fld1)
fixed (UInt16* pFld3 = &test._fld3)
{
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)pFld1),
ElementIndex,
*pFld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Insert(_fld1, ElementIndex, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (UInt16* pFld3 = &_fld3)
{
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)pFld1),
ElementIndex,
*pFld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Insert(test._fld1, ElementIndex, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Insert(
AdvSimd.LoadVector64((UInt16*)(&test._fld1)),
ElementIndex,
test._fld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt16> op1, UInt16 op3, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, op3, outArray, method);
}
private void ValidateResult(void* op1, UInt16 op3, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, op3, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16 thirdOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Insert(firstOp, ElementIndex, thirdOp, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Insert)}<UInt16>(Vector64<UInt16>, 1, UInt16): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: {thirdOp}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Private.CoreLib/src/System/SpanDebugView.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
namespace System
{
internal sealed class SpanDebugView<T>
{
private readonly T[] _array;
public SpanDebugView(Span<T> span)
{
_array = span.ToArray();
}
public SpanDebugView(ReadOnlySpan<T> span)
{
_array = span.ToArray();
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Items => _array;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
namespace System
{
internal sealed class SpanDebugView<T>
{
private readonly T[] _array;
public SpanDebugView(Span<T> span)
{
_array = span.ToArray();
}
public SpanDebugView(ReadOnlySpan<T> span)
{
_array = span.ToArray();
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Items => _array;
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Reflection.Emit/tests/MethodBuilder/MethodBuilderToString.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class MethodBuilderToString
{
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_AllFieldsSet()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract);
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ret);
GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T");
GenericTypeParameterBuilder returnType = typeParameters[0];
method.SetSignature(returnType.AsType(), null, null, null, null, null);
Assert.Contains(ExpectedToStrin(method), method.ToString());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_NameAndAttributeSet()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract);
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public);
Assert.Contains(ExpectedToStrin(method), method.ToString());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_NameAttributeAndSignatureSetSet()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract);
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public);
method.SetSignature(typeof(void), null, null, null, null, null);
Assert.Contains(ExpectedToStrin(method), method.ToString());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_NonGenericMethod()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("method1", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[0]);
string toString = method.ToString();
Assert.True(toString.LastIndexOf("Name: method1") != -1 &&
toString.LastIndexOf("Attributes: 22") != -1 &&
toString.LastIndexOf("Method Signature: Length: 3") != -1 &&
toString.LastIndexOf("Arguments: 0") != -1 &&
toString.LastIndexOf("Signature:") != -1 &&
toString.LastIndexOf("0 0 8 0") != -1);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_GenericMethod()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("method1", MethodAttributes.Public, typeof(int), new Type[0]);
method.DefineGenericParameters("T", "U", "V");
method.MakeGenericMethod(typeof(string), typeof(int), typeof(object));
string toString = method.ToString();
Assert.True(toString.LastIndexOf("Name: method1") != -1 &&
toString.LastIndexOf("Attributes: 6") != -1 &&
toString.LastIndexOf("Method Signature: Length: 4") != -1 &&
toString.LastIndexOf("Arguments: 0") != -1 &&
toString.LastIndexOf("Signature:") != -1 &&
toString.LastIndexOf("48 3 0 8 0") != -1);
}
private static string ExpectedToStrin(MethodBuilder method)
{
return "Name: " + method.Name + " " + Environment.NewLine +
"Attributes: " + ((int)method.Attributes).ToString() + Environment.NewLine +
"Method Signature: ";
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class MethodBuilderToString
{
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_AllFieldsSet()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract);
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ret);
GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T");
GenericTypeParameterBuilder returnType = typeParameters[0];
method.SetSignature(returnType.AsType(), null, null, null, null, null);
Assert.Contains(ExpectedToStrin(method), method.ToString());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_NameAndAttributeSet()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract);
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public);
Assert.Contains(ExpectedToStrin(method), method.ToString());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_NameAttributeAndSignatureSetSet()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract);
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public);
method.SetSignature(typeof(void), null, null, null, null, null);
Assert.Contains(ExpectedToStrin(method), method.ToString());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_NonGenericMethod()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("method1", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[0]);
string toString = method.ToString();
Assert.True(toString.LastIndexOf("Name: method1") != -1 &&
toString.LastIndexOf("Attributes: 22") != -1 &&
toString.LastIndexOf("Method Signature: Length: 3") != -1 &&
toString.LastIndexOf("Arguments: 0") != -1 &&
toString.LastIndexOf("Signature:") != -1 &&
toString.LastIndexOf("0 0 8 0") != -1);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_GenericMethod()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("method1", MethodAttributes.Public, typeof(int), new Type[0]);
method.DefineGenericParameters("T", "U", "V");
method.MakeGenericMethod(typeof(string), typeof(int), typeof(object));
string toString = method.ToString();
Assert.True(toString.LastIndexOf("Name: method1") != -1 &&
toString.LastIndexOf("Attributes: 6") != -1 &&
toString.LastIndexOf("Method Signature: Length: 4") != -1 &&
toString.LastIndexOf("Arguments: 0") != -1 &&
toString.LastIndexOf("Signature:") != -1 &&
toString.LastIndexOf("48 3 0 8 0") != -1);
}
private static string ExpectedToStrin(MethodBuilder method)
{
return "Name: " + method.Name + " " + Environment.NewLine +
"Attributes: " + ((int)method.Attributes).ToString() + Environment.NewLine +
"Method Signature: ";
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DesImplementation.Android.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Internal.Cryptography;
namespace System.Security.Cryptography
{
internal sealed partial class DesImplementation
{
private static UniversalCryptoTransform CreateTransformCore(
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
byte[]? iv,
int blockSize,
int feedbackSize,
int paddingSize,
bool encrypting)
{
// The algorithm pointer is a static pointer, so not having any cleanup code is correct.
IntPtr algorithm = GetAlgorithm(cipherMode, feedbackSize);
BasicSymmetricCipher cipher = new OpenSslCipher(algorithm, cipherMode, blockSize, paddingSize, key, iv, encrypting);
return UniversalCryptoTransform.Create(paddingMode, cipher, encrypting);
}
private static ILiteSymmetricCipher CreateLiteCipher(
CipherMode cipherMode,
PaddingMode paddingMode,
ReadOnlySpan<byte> key,
ReadOnlySpan<byte> iv,
int blockSize,
int feedbackSize,
int paddingSize,
bool encrypting)
{
// The algorithm pointer is a static pointer, so not having any cleanup code is correct.
IntPtr algorithm = GetAlgorithm(cipherMode, feedbackSize);
return new OpenSslCipherLite(algorithm, cipherMode, blockSize, paddingSize, key, iv, encrypting);
}
private static IntPtr GetAlgorithm(CipherMode cipherMode, int feedbackSize)
{
return cipherMode switch
{
CipherMode.CBC => Interop.Crypto.EvpDesCbc(),
CipherMode.ECB => Interop.Crypto.EvpDesEcb(),
CipherMode.CFB when feedbackSize == 1 => Interop.Crypto.EvpDesCfb8(),
_ => throw new NotSupportedException(),
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Internal.Cryptography;
namespace System.Security.Cryptography
{
internal sealed partial class DesImplementation
{
private static UniversalCryptoTransform CreateTransformCore(
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
byte[]? iv,
int blockSize,
int feedbackSize,
int paddingSize,
bool encrypting)
{
// The algorithm pointer is a static pointer, so not having any cleanup code is correct.
IntPtr algorithm = GetAlgorithm(cipherMode, feedbackSize);
BasicSymmetricCipher cipher = new OpenSslCipher(algorithm, cipherMode, blockSize, paddingSize, key, iv, encrypting);
return UniversalCryptoTransform.Create(paddingMode, cipher, encrypting);
}
private static ILiteSymmetricCipher CreateLiteCipher(
CipherMode cipherMode,
PaddingMode paddingMode,
ReadOnlySpan<byte> key,
ReadOnlySpan<byte> iv,
int blockSize,
int feedbackSize,
int paddingSize,
bool encrypting)
{
// The algorithm pointer is a static pointer, so not having any cleanup code is correct.
IntPtr algorithm = GetAlgorithm(cipherMode, feedbackSize);
return new OpenSslCipherLite(algorithm, cipherMode, blockSize, paddingSize, key, iv, encrypting);
}
private static IntPtr GetAlgorithm(CipherMode cipherMode, int feedbackSize)
{
return cipherMode switch
{
CipherMode.CBC => Interop.Crypto.EvpDesCbc(),
CipherMode.ECB => Interop.Crypto.EvpDesEcb(),
CipherMode.CFB when feedbackSize == 1 => Interop.Crypto.EvpDesCfb8(),
_ => throw new NotSupportedException(),
};
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Drawing.Common/tests/mono/System.Drawing.Imaging/GifCodecTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// GIF Codec class testing unit
//
// Authors:
// Jordi Mas i Hern?ndez ([email protected])
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2006, 2007 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.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Xunit;
namespace MonoTests.System.Drawing.Imaging
{
public class GifCodecTest
{
/* Checks bitmap features on a known 1bbp bitmap */
private void Bitmap8bitsFeatures(string filename)
{
using (Bitmap bmp = new Bitmap(filename))
{
GraphicsUnit unit = GraphicsUnit.World;
RectangleF rect = bmp.GetBounds(ref unit);
Assert.Equal(PixelFormat.Format8bppIndexed, bmp.PixelFormat);
Assert.Equal(110, bmp.Width);
Assert.Equal(100, bmp.Height);
Assert.Equal(0, rect.X);
Assert.Equal(0, rect.Y);
Assert.Equal(110, rect.Width);
Assert.Equal(100, rect.Height);
Assert.Equal(110, bmp.Size.Width);
Assert.Equal(100, bmp.Size.Height);
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap8bitsFeatures_Gif89()
{
Bitmap8bitsFeatures(Helpers.GetTestBitmapPath("nature24bits.gif"));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap8bitsFeatures_Gif87()
{
Bitmap8bitsFeatures(Helpers.GetTestBitmapPath("nature24bits87.gif"));
}
private void Bitmap8bitsPixels(string filename)
{
using (Bitmap bmp = new Bitmap(filename))
{
// sampling values from a well known bitmap
Assert.Equal(-10644802, bmp.GetPixel(0, 0).ToArgb());
Assert.Equal(-12630705, bmp.GetPixel(0, 32).ToArgb());
Assert.Equal(-14537409, bmp.GetPixel(0, 64).ToArgb());
Assert.Equal(-14672099, bmp.GetPixel(0, 96).ToArgb());
Assert.Equal(-526863, bmp.GetPixel(32, 0).ToArgb());
Assert.Equal(-10263970, bmp.GetPixel(32, 32).ToArgb());
Assert.Equal(-10461317, bmp.GetPixel(32, 64).ToArgb());
Assert.Equal(-9722415, bmp.GetPixel(32, 96).ToArgb());
Assert.Equal(-131076, bmp.GetPixel(64, 0).ToArgb());
Assert.Equal(-2702435, bmp.GetPixel(64, 32).ToArgb());
Assert.Equal(-6325922, bmp.GetPixel(64, 64).ToArgb());
Assert.Equal(-12411924, bmp.GetPixel(64, 96).ToArgb());
Assert.Equal(-131076, bmp.GetPixel(96, 0).ToArgb());
Assert.Equal(-7766649, bmp.GetPixel(96, 32).ToArgb());
Assert.Equal(-11512986, bmp.GetPixel(96, 64).ToArgb());
Assert.Equal(-12616230, bmp.GetPixel(96, 96).ToArgb());
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap8bitsPixels_Gif89()
{
Bitmap8bitsPixels(Helpers.GetTestBitmapPath("nature24bits.gif"));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap8bitsPixels_Gif87()
{
Bitmap8bitsPixels(Helpers.GetTestBitmapPath("nature24bits87.gif"));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsDrawingSupported), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue("https://github.com/dotnet/runtime/issues/28859")]
public void Bitmap8bitsData()
{
string sInFile = Helpers.GetTestBitmapPath("nature24bits.gif");
using (Bitmap bmp = new Bitmap(sInFile))
{
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
try
{
Assert.Equal(bmp.Height, data.Height);
Assert.Equal(bmp.Width, data.Width);
Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
Assert.Equal(332, data.Stride);
Assert.Equal(100, data.Height);
unsafe
{
byte* scan = (byte*)data.Scan0;
// sampling values from a well known bitmap
Assert.Equal(190, *(scan + 0));
Assert.Equal(217, *(scan + 1009));
Assert.Equal(120, *(scan + 2018));
Assert.Equal(253, *(scan + 3027));
Assert.Equal(233, *(scan + 4036));
Assert.Equal(176, *(scan + 5045));
Assert.Equal(151, *(scan + 6054));
Assert.Equal(220, *(scan + 7063));
Assert.Equal(139, *(scan + 8072));
Assert.Equal(121, *(scan + 9081));
Assert.Equal(160, *(scan + 10090));
Assert.Equal(92, *(scan + 11099));
Assert.Equal(96, *(scan + 12108));
Assert.Equal(64, *(scan + 13117));
Assert.Equal(156, *(scan + 14126));
Assert.Equal(68, *(scan + 15135));
Assert.Equal(156, *(scan + 16144));
Assert.Equal(84, *(scan + 17153));
Assert.Equal(55, *(scan + 18162));
Assert.Equal(68, *(scan + 19171));
Assert.Equal(116, *(scan + 20180));
Assert.Equal(61, *(scan + 21189));
Assert.Equal(69, *(scan + 22198));
Assert.Equal(75, *(scan + 23207));
Assert.Equal(61, *(scan + 24216));
Assert.Equal(66, *(scan + 25225));
Assert.Equal(40, *(scan + 26234));
Assert.Equal(55, *(scan + 27243));
Assert.Equal(53, *(scan + 28252));
Assert.Equal(215, *(scan + 29261));
Assert.Equal(99, *(scan + 30270));
Assert.Equal(67, *(scan + 31279));
Assert.Equal(142, *(scan + 32288));
}
}
finally
{
bmp.UnlockBits(data);
}
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Interlaced()
{
string sInFile = Helpers.GetTestBitmapPath("81773-interlaced.gif");
using (Bitmap bmp = new Bitmap(sInFile))
{
for (int i = 0; i < 255; i++)
{
Color c = bmp.GetPixel(0, i);
Assert.Equal(255, c.A);
Assert.Equal(i, c.R);
Assert.Equal(i, c.G);
Assert.Equal(i, c.B);
}
}
}
private void Save(PixelFormat original, PixelFormat expected, bool exactColorCheck)
{
string sOutFile = $"linerect-{expected}.gif";
// Save
Bitmap bmp = new Bitmap(100, 100, original);
Graphics gr = Graphics.FromImage(bmp);
using (Pen p = new Pen(Color.Red, 2))
{
gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
}
try
{
bmp.Save(sOutFile, ImageFormat.Gif);
// Load
using (Bitmap bmpLoad = new Bitmap(sOutFile))
{
Assert.Equal(expected, bmpLoad.PixelFormat);
Color color = bmpLoad.GetPixel(10, 10);
if (exactColorCheck)
{
Assert.Equal(Color.FromArgb(255, 255, 0, 0), color);
}
else
{
// FIXME: we don't save a pure red (F8 instead of FF) into the file so the color-check assert will fail
// this is due to libgif's QuantizeBuffer. An alternative would be to make our own that checks if less than 256 colors
// are used in the bitmap (or else use QuantizeBuffer).
Assert.Equal(255, color.A);
Assert.True(color.R >= 248);
Assert.Equal(0, color.G);
Assert.Equal(0, color.B);
}
}
}
finally
{
gr.Dispose();
bmp.Dispose();
try
{
File.Delete(sOutFile);
}
catch
{
}
}
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_24bppRgb()
{
Save(PixelFormat.Format24bppRgb, PixelFormat.Format8bppIndexed, false);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppRgb()
{
Save(PixelFormat.Format32bppRgb, PixelFormat.Format8bppIndexed, false);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppArgb()
{
Save(PixelFormat.Format32bppArgb, PixelFormat.Format8bppIndexed, false);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppPArgb()
{
Save(PixelFormat.Format32bppPArgb, PixelFormat.Format8bppIndexed, false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// GIF Codec class testing unit
//
// Authors:
// Jordi Mas i Hern?ndez ([email protected])
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2006, 2007 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.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Xunit;
namespace MonoTests.System.Drawing.Imaging
{
public class GifCodecTest
{
/* Checks bitmap features on a known 1bbp bitmap */
private void Bitmap8bitsFeatures(string filename)
{
using (Bitmap bmp = new Bitmap(filename))
{
GraphicsUnit unit = GraphicsUnit.World;
RectangleF rect = bmp.GetBounds(ref unit);
Assert.Equal(PixelFormat.Format8bppIndexed, bmp.PixelFormat);
Assert.Equal(110, bmp.Width);
Assert.Equal(100, bmp.Height);
Assert.Equal(0, rect.X);
Assert.Equal(0, rect.Y);
Assert.Equal(110, rect.Width);
Assert.Equal(100, rect.Height);
Assert.Equal(110, bmp.Size.Width);
Assert.Equal(100, bmp.Size.Height);
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap8bitsFeatures_Gif89()
{
Bitmap8bitsFeatures(Helpers.GetTestBitmapPath("nature24bits.gif"));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap8bitsFeatures_Gif87()
{
Bitmap8bitsFeatures(Helpers.GetTestBitmapPath("nature24bits87.gif"));
}
private void Bitmap8bitsPixels(string filename)
{
using (Bitmap bmp = new Bitmap(filename))
{
// sampling values from a well known bitmap
Assert.Equal(-10644802, bmp.GetPixel(0, 0).ToArgb());
Assert.Equal(-12630705, bmp.GetPixel(0, 32).ToArgb());
Assert.Equal(-14537409, bmp.GetPixel(0, 64).ToArgb());
Assert.Equal(-14672099, bmp.GetPixel(0, 96).ToArgb());
Assert.Equal(-526863, bmp.GetPixel(32, 0).ToArgb());
Assert.Equal(-10263970, bmp.GetPixel(32, 32).ToArgb());
Assert.Equal(-10461317, bmp.GetPixel(32, 64).ToArgb());
Assert.Equal(-9722415, bmp.GetPixel(32, 96).ToArgb());
Assert.Equal(-131076, bmp.GetPixel(64, 0).ToArgb());
Assert.Equal(-2702435, bmp.GetPixel(64, 32).ToArgb());
Assert.Equal(-6325922, bmp.GetPixel(64, 64).ToArgb());
Assert.Equal(-12411924, bmp.GetPixel(64, 96).ToArgb());
Assert.Equal(-131076, bmp.GetPixel(96, 0).ToArgb());
Assert.Equal(-7766649, bmp.GetPixel(96, 32).ToArgb());
Assert.Equal(-11512986, bmp.GetPixel(96, 64).ToArgb());
Assert.Equal(-12616230, bmp.GetPixel(96, 96).ToArgb());
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap8bitsPixels_Gif89()
{
Bitmap8bitsPixels(Helpers.GetTestBitmapPath("nature24bits.gif"));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap8bitsPixels_Gif87()
{
Bitmap8bitsPixels(Helpers.GetTestBitmapPath("nature24bits87.gif"));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsDrawingSupported), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue("https://github.com/dotnet/runtime/issues/28859")]
public void Bitmap8bitsData()
{
string sInFile = Helpers.GetTestBitmapPath("nature24bits.gif");
using (Bitmap bmp = new Bitmap(sInFile))
{
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
try
{
Assert.Equal(bmp.Height, data.Height);
Assert.Equal(bmp.Width, data.Width);
Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
Assert.Equal(332, data.Stride);
Assert.Equal(100, data.Height);
unsafe
{
byte* scan = (byte*)data.Scan0;
// sampling values from a well known bitmap
Assert.Equal(190, *(scan + 0));
Assert.Equal(217, *(scan + 1009));
Assert.Equal(120, *(scan + 2018));
Assert.Equal(253, *(scan + 3027));
Assert.Equal(233, *(scan + 4036));
Assert.Equal(176, *(scan + 5045));
Assert.Equal(151, *(scan + 6054));
Assert.Equal(220, *(scan + 7063));
Assert.Equal(139, *(scan + 8072));
Assert.Equal(121, *(scan + 9081));
Assert.Equal(160, *(scan + 10090));
Assert.Equal(92, *(scan + 11099));
Assert.Equal(96, *(scan + 12108));
Assert.Equal(64, *(scan + 13117));
Assert.Equal(156, *(scan + 14126));
Assert.Equal(68, *(scan + 15135));
Assert.Equal(156, *(scan + 16144));
Assert.Equal(84, *(scan + 17153));
Assert.Equal(55, *(scan + 18162));
Assert.Equal(68, *(scan + 19171));
Assert.Equal(116, *(scan + 20180));
Assert.Equal(61, *(scan + 21189));
Assert.Equal(69, *(scan + 22198));
Assert.Equal(75, *(scan + 23207));
Assert.Equal(61, *(scan + 24216));
Assert.Equal(66, *(scan + 25225));
Assert.Equal(40, *(scan + 26234));
Assert.Equal(55, *(scan + 27243));
Assert.Equal(53, *(scan + 28252));
Assert.Equal(215, *(scan + 29261));
Assert.Equal(99, *(scan + 30270));
Assert.Equal(67, *(scan + 31279));
Assert.Equal(142, *(scan + 32288));
}
}
finally
{
bmp.UnlockBits(data);
}
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Interlaced()
{
string sInFile = Helpers.GetTestBitmapPath("81773-interlaced.gif");
using (Bitmap bmp = new Bitmap(sInFile))
{
for (int i = 0; i < 255; i++)
{
Color c = bmp.GetPixel(0, i);
Assert.Equal(255, c.A);
Assert.Equal(i, c.R);
Assert.Equal(i, c.G);
Assert.Equal(i, c.B);
}
}
}
private void Save(PixelFormat original, PixelFormat expected, bool exactColorCheck)
{
string sOutFile = $"linerect-{expected}.gif";
// Save
Bitmap bmp = new Bitmap(100, 100, original);
Graphics gr = Graphics.FromImage(bmp);
using (Pen p = new Pen(Color.Red, 2))
{
gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
}
try
{
bmp.Save(sOutFile, ImageFormat.Gif);
// Load
using (Bitmap bmpLoad = new Bitmap(sOutFile))
{
Assert.Equal(expected, bmpLoad.PixelFormat);
Color color = bmpLoad.GetPixel(10, 10);
if (exactColorCheck)
{
Assert.Equal(Color.FromArgb(255, 255, 0, 0), color);
}
else
{
// FIXME: we don't save a pure red (F8 instead of FF) into the file so the color-check assert will fail
// this is due to libgif's QuantizeBuffer. An alternative would be to make our own that checks if less than 256 colors
// are used in the bitmap (or else use QuantizeBuffer).
Assert.Equal(255, color.A);
Assert.True(color.R >= 248);
Assert.Equal(0, color.G);
Assert.Equal(0, color.B);
}
}
}
finally
{
gr.Dispose();
bmp.Dispose();
try
{
File.Delete(sOutFile);
}
catch
{
}
}
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_24bppRgb()
{
Save(PixelFormat.Format24bppRgb, PixelFormat.Format8bppIndexed, false);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppRgb()
{
Save(PixelFormat.Format32bppRgb, PixelFormat.Format8bppIndexed, false);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppArgb()
{
Save(PixelFormat.Format32bppArgb, PixelFormat.Format8bppIndexed, false);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppPArgb()
{
Save(PixelFormat.Format32bppPArgb, PixelFormat.Format8bppIndexed, false);
}
}
}
| -1 |
dotnet/runtime | 66,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyBySelectedScalar.Vector64.UInt16.Vector64.UInt16.1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1()
{
var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_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(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<UInt16> _fld1;
public Vector64<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1 testClass)
{
var result = AdvSimd.MultiplyBySelectedScalar(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1 testClass)
{
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (Vector64<UInt16>* pFld2 = &_fld2)
{
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector64((UInt16*)(pFld2)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly byte Imm = 1;
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector64<UInt16> _clsVar1;
private static Vector64<UInt16> _clsVar2;
private Vector64<UInt16> _fld1;
private Vector64<UInt16> _fld2;
private DataTable _dataTable;
static ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
}
public ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.MultiplyBySelectedScalar(
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalar), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalar), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyBySelectedScalar(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(pClsVar1)),
AdvSimd.LoadVector64((UInt16*)(pClsVar2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr);
var result = AdvSimd.MultiplyBySelectedScalar(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr));
var result = AdvSimd.MultiplyBySelectedScalar(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1();
var result = AdvSimd.MultiplyBySelectedScalar(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1();
fixed (Vector64<UInt16>* pFld1 = &test._fld1)
fixed (Vector64<UInt16>* pFld2 = &test._fld2)
{
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector64((UInt16*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyBySelectedScalar(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (Vector64<UInt16>* pFld2 = &_fld2)
{
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector64((UInt16*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyBySelectedScalar(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(&test._fld1)),
AdvSimd.LoadVector64((UInt16*)(&test._fld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt16> firstOp, Vector64<UInt16> secondOp, 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]), firstOp);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), secondOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, 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>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] secondOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Multiply(firstOp[i], secondOp[Imm]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalar)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>, 1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1()
{
var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_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(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<UInt16> _fld1;
public Vector64<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1 testClass)
{
var result = AdvSimd.MultiplyBySelectedScalar(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1 testClass)
{
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (Vector64<UInt16>* pFld2 = &_fld2)
{
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector64((UInt16*)(pFld2)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly byte Imm = 1;
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector64<UInt16> _clsVar1;
private static Vector64<UInt16> _clsVar2;
private Vector64<UInt16> _fld1;
private Vector64<UInt16> _fld2;
private DataTable _dataTable;
static ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
}
public ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.MultiplyBySelectedScalar(
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalar), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalar), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyBySelectedScalar(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(pClsVar1)),
AdvSimd.LoadVector64((UInt16*)(pClsVar2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr);
var result = AdvSimd.MultiplyBySelectedScalar(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr));
var result = AdvSimd.MultiplyBySelectedScalar(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1();
var result = AdvSimd.MultiplyBySelectedScalar(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt16_Vector64_UInt16_1();
fixed (Vector64<UInt16>* pFld1 = &test._fld1)
fixed (Vector64<UInt16>* pFld2 = &test._fld2)
{
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector64((UInt16*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyBySelectedScalar(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (Vector64<UInt16>* pFld2 = &_fld2)
{
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector64((UInt16*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyBySelectedScalar(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyBySelectedScalar(
AdvSimd.LoadVector64((UInt16*)(&test._fld1)),
AdvSimd.LoadVector64((UInt16*)(&test._fld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt16> firstOp, Vector64<UInt16> secondOp, 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]), firstOp);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), secondOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, 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>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] secondOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Multiply(firstOp[i], secondOp[Imm]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalar)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>, 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,235 | Revert "Fix issues related to JsonSerializerOptions mutation and caching." | Reverts dotnet/runtime#65863
Fixes #66232 | jkotas | 2022-03-05T06:23:45Z | 2022-03-05T14:08:07Z | 17662fc30cfd4cc6e7dbba978a3fb512380c0b70 | 3ede8095da51d5d27a890020b61376155e9a61c2 | Revert "Fix issues related to JsonSerializerOptions mutation and caching.". Reverts dotnet/runtime#65863
Fixes #66232 | ./src/libraries/System.Data.Common/tests/System/Data/SqlTypes/SqlXmlTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// 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.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Xml;
using Xunit;
namespace System.Data.Tests.SqlTypes
{
public class SqlXmlTest
{
// Test constructor
[Fact] // .ctor (Stream)
//[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
public void Constructor2_Stream_Unicode()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(xmlStr));
SqlXml xmlSql = new SqlXml(stream);
Assert.False(xmlSql.IsNull);
Assert.Equal(xmlStr, xmlSql.Value);
}
[Fact] // .ctor (Stream)
public void Constructor2_Stream_Empty()
{
MemoryStream ms = new MemoryStream();
SqlXml xmlSql = new SqlXml(ms);
Assert.False(xmlSql.IsNull);
Assert.Equal(string.Empty, xmlSql.Value);
}
[Fact]
public void Constructor2_Stream_Null()
{
SqlXml xmlSql = new SqlXml((Stream)null);
Assert.True(xmlSql.IsNull);
Assert.Throws<SqlNullValueException>(() => xmlSql.Value);
}
[Fact] // .ctor (XmlReader)
public void Constructor3()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
XmlReader xrdr = new XmlTextReader(new StringReader(xmlStr));
SqlXml xmlSql = new SqlXml(xrdr);
Assert.False(xmlSql.IsNull);
Assert.Equal(xmlStr, xmlSql.Value);
}
[Fact] // .ctor (XmlReader)
public void Constructor3_XmlReader_Empty()
{
XmlReaderSettings xs = new XmlReaderSettings();
xs.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader xrdr = XmlReader.Create(new StringReader(string.Empty), xs);
SqlXml xmlSql = new SqlXml(xrdr);
Assert.False(xmlSql.IsNull);
Assert.Equal(string.Empty, xmlSql.Value);
}
[Fact]
public void Constructor3_XmlReader_Null()
{
SqlXml xmlSql = new SqlXml((XmlReader)null);
Assert.True(xmlSql.IsNull);
Assert.Throws<SqlNullValueException>(() => xmlSql.Value);
}
[Fact]
//[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
public void CreateReader_Stream_Unicode()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(xmlStr));
SqlXml xmlSql = new SqlXml(stream);
XmlReader xrdr = xmlSql.CreateReader();
xrdr.MoveToContent();
Assert.Equal(xmlStr, xrdr.ReadOuterXml());
}
[Fact]
public void SqlXml_fromXmlReader_CreateReaderTest()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
XmlReader rdr = new XmlTextReader(new StringReader(xmlStr));
SqlXml xmlSql = new SqlXml(rdr);
XmlReader xrdr = xmlSql.CreateReader();
xrdr.MoveToContent();
Assert.Equal(xmlStr, xrdr.ReadOuterXml());
}
[Fact]
public void SqlXml_fromZeroLengthStream_CreateReaderTest()
{
MemoryStream stream = new MemoryStream();
SqlXml xmlSql = new SqlXml(stream);
XmlReader xrdr = xmlSql.CreateReader();
Assert.False(xrdr.Read());
}
[Fact]
public void SqlXml_fromZeroLengthXmlReader_CreateReaderTest_withFragment()
{
XmlReaderSettings xs = new XmlReaderSettings();
xs.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader rdr = XmlReader.Create(new StringReader(string.Empty), xs);
SqlXml xmlSql = new SqlXml(rdr);
XmlReader xrdr = xmlSql.CreateReader();
Assert.False(xrdr.Read());
}
[Fact]
public void SqlXml_fromZeroLengthXmlReader_CreateReaderTest()
{
XmlReader rdr = new XmlTextReader(new StringReader(string.Empty));
Assert.Throws<XmlException>(() => new SqlXml(rdr));
}
[Fact]
public void CreateReader_Stream_Null()
{
SqlXml xmlSql = new SqlXml((Stream)null);
Assert.Throws<SqlNullValueException>(() => xmlSql.CreateReader());
}
[Fact]
public void CreateReader_XmlReader_Null()
{
SqlXml xmlSql = new SqlXml((XmlReader)null);
Assert.Throws<SqlNullValueException>(() => xmlSql.CreateReader());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// 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.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Xml;
using Xunit;
namespace System.Data.Tests.SqlTypes
{
public class SqlXmlTest
{
// Test constructor
[Fact] // .ctor (Stream)
//[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
public void Constructor2_Stream_Unicode()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(xmlStr));
SqlXml xmlSql = new SqlXml(stream);
Assert.False(xmlSql.IsNull);
Assert.Equal(xmlStr, xmlSql.Value);
}
[Fact] // .ctor (Stream)
public void Constructor2_Stream_Empty()
{
MemoryStream ms = new MemoryStream();
SqlXml xmlSql = new SqlXml(ms);
Assert.False(xmlSql.IsNull);
Assert.Equal(string.Empty, xmlSql.Value);
}
[Fact]
public void Constructor2_Stream_Null()
{
SqlXml xmlSql = new SqlXml((Stream)null);
Assert.True(xmlSql.IsNull);
Assert.Throws<SqlNullValueException>(() => xmlSql.Value);
}
[Fact] // .ctor (XmlReader)
public void Constructor3()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
XmlReader xrdr = new XmlTextReader(new StringReader(xmlStr));
SqlXml xmlSql = new SqlXml(xrdr);
Assert.False(xmlSql.IsNull);
Assert.Equal(xmlStr, xmlSql.Value);
}
[Fact] // .ctor (XmlReader)
public void Constructor3_XmlReader_Empty()
{
XmlReaderSettings xs = new XmlReaderSettings();
xs.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader xrdr = XmlReader.Create(new StringReader(string.Empty), xs);
SqlXml xmlSql = new SqlXml(xrdr);
Assert.False(xmlSql.IsNull);
Assert.Equal(string.Empty, xmlSql.Value);
}
[Fact]
public void Constructor3_XmlReader_Null()
{
SqlXml xmlSql = new SqlXml((XmlReader)null);
Assert.True(xmlSql.IsNull);
Assert.Throws<SqlNullValueException>(() => xmlSql.Value);
}
[Fact]
//[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
public void CreateReader_Stream_Unicode()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(xmlStr));
SqlXml xmlSql = new SqlXml(stream);
XmlReader xrdr = xmlSql.CreateReader();
xrdr.MoveToContent();
Assert.Equal(xmlStr, xrdr.ReadOuterXml());
}
[Fact]
public void SqlXml_fromXmlReader_CreateReaderTest()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
XmlReader rdr = new XmlTextReader(new StringReader(xmlStr));
SqlXml xmlSql = new SqlXml(rdr);
XmlReader xrdr = xmlSql.CreateReader();
xrdr.MoveToContent();
Assert.Equal(xmlStr, xrdr.ReadOuterXml());
}
[Fact]
public void SqlXml_fromZeroLengthStream_CreateReaderTest()
{
MemoryStream stream = new MemoryStream();
SqlXml xmlSql = new SqlXml(stream);
XmlReader xrdr = xmlSql.CreateReader();
Assert.False(xrdr.Read());
}
[Fact]
public void SqlXml_fromZeroLengthXmlReader_CreateReaderTest_withFragment()
{
XmlReaderSettings xs = new XmlReaderSettings();
xs.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader rdr = XmlReader.Create(new StringReader(string.Empty), xs);
SqlXml xmlSql = new SqlXml(rdr);
XmlReader xrdr = xmlSql.CreateReader();
Assert.False(xrdr.Read());
}
[Fact]
public void SqlXml_fromZeroLengthXmlReader_CreateReaderTest()
{
XmlReader rdr = new XmlTextReader(new StringReader(string.Empty));
Assert.Throws<XmlException>(() => new SqlXml(rdr));
}
[Fact]
public void CreateReader_Stream_Null()
{
SqlXml xmlSql = new SqlXml((Stream)null);
Assert.Throws<SqlNullValueException>(() => xmlSql.CreateReader());
}
[Fact]
public void CreateReader_XmlReader_Null()
{
SqlXml xmlSql = new SqlXml((XmlReader)null);
Assert.Throws<SqlNullValueException>(() => xmlSql.CreateReader());
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.