From 839c642c3abebe5ba7fcd18b5b03dee50dc1b76e Mon Sep 17 00:00:00 2001 From: martincostello Date: Wed, 10 Apr 2024 19:34:18 +0100 Subject: [PATCH 1/8] Add new line to be specified for JSON formatting Allow the new line string to use for indented JSON to be specified through options. Resolves #84117. --- .../JsonSourceGenerationOptionsAttribute.cs | 5 ++ .../gen/JsonSourceGenerator.Emitter.cs | 3 + .../gen/JsonSourceGenerator.Parser.cs | 6 ++ .../gen/Model/SourceGenerationOptionsSpec.cs | 2 + .../System.Text.Json/ref/System.Text.Json.cs | 3 + .../src/Resources/Strings.resx | 3 + .../src/System/Text/Json/JsonConstants.cs | 3 + .../Serialization/JsonSerializerOptions.cs | 27 ++++++ .../src/System/Text/Json/ThrowHelper.cs | 6 ++ .../Text/Json/Writer/JsonWriterHelper.cs | 7 ++ .../Text/Json/Writer/JsonWriterOptions.cs | 32 ++++++- .../Utf8JsonWriter.WriteProperties.Bytes.cs | 8 +- ...Utf8JsonWriter.WriteProperties.DateTime.cs | 8 +- ...onWriter.WriteProperties.DateTimeOffset.cs | 8 +- .../Utf8JsonWriter.WriteProperties.Decimal.cs | 8 +- .../Utf8JsonWriter.WriteProperties.Double.cs | 8 +- .../Utf8JsonWriter.WriteProperties.Float.cs | 8 +- .../Utf8JsonWriter.WriteProperties.Guid.cs | 8 +- .../Utf8JsonWriter.WriteProperties.Helpers.cs | 8 +- .../Utf8JsonWriter.WriteProperties.Literal.cs | 8 +- ...JsonWriter.WriteProperties.SignedNumber.cs | 8 +- .../Utf8JsonWriter.WriteProperties.String.cs | 24 +++--- ...onWriter.WriteProperties.UnsignedNumber.cs | 8 +- .../Utf8JsonWriter.WriteValues.Bytes.cs | 2 +- .../Utf8JsonWriter.WriteValues.Comment.cs | 8 +- .../Utf8JsonWriter.WriteValues.DateTime.cs | 2 +- ...f8JsonWriter.WriteValues.DateTimeOffset.cs | 2 +- .../Utf8JsonWriter.WriteValues.Decimal.cs | 2 +- .../Utf8JsonWriter.WriteValues.Double.cs | 2 +- .../Utf8JsonWriter.WriteValues.Float.cs | 2 +- ...8JsonWriter.WriteValues.FormattedNumber.cs | 4 +- .../Writer/Utf8JsonWriter.WriteValues.Guid.cs | 2 +- .../Utf8JsonWriter.WriteValues.Literal.cs | 2 +- ...Utf8JsonWriter.WriteValues.SignedNumber.cs | 2 +- .../Utf8JsonWriter.WriteValues.String.cs | 8 +- ...f8JsonWriter.WriteValues.UnsignedNumber.cs | 2 +- .../System/Text/Json/Writer/Utf8JsonWriter.cs | 6 +- .../JsonSourceGenerationOptionsTests.cs | 2 + .../JsonWriterOptionsTests.cs | 43 +++++++--- .../Serialization/CacheTests.cs | 1 + .../Serialization/OptionsTests.cs | 9 +- .../Utf8JsonWriterTests.cs | 84 ++++++++++--------- 42 files changed, 260 insertions(+), 134 deletions(-) diff --git a/src/libraries/System.Text.Json/Common/JsonSourceGenerationOptionsAttribute.cs b/src/libraries/System.Text.Json/Common/JsonSourceGenerationOptionsAttribute.cs index d3c7d0dfc1e62c..f1c76e7674f07a 100644 --- a/src/libraries/System.Text.Json/Common/JsonSourceGenerationOptionsAttribute.cs +++ b/src/libraries/System.Text.Json/Common/JsonSourceGenerationOptionsAttribute.cs @@ -150,5 +150,10 @@ public JsonSourceGenerationOptionsAttribute(JsonSerializerDefaults defaults) /// instead of numeric serialization for all enum types encountered in its type graph. /// public bool UseStringEnumConverter { get; set; } + + /// + /// Specifies the default value of when set. + /// + public string? NewLine { get; set; } } } diff --git a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs index 7dbc4de3a57f59..12173a0e917de9 100644 --- a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs +++ b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs @@ -1147,6 +1147,9 @@ private static void GetLogicForDefaultSerializerOptionsInit(SourceGenerationOpti if (optionsSpec.MaxDepth is int maxDepth) writer.WriteLine($"MaxDepth = {maxDepth},"); + if (optionsSpec.NewLine is string newLine) + writer.WriteLine($"NewLine = {FormatStringLiteral(newLine)},"); + if (optionsSpec.NumberHandling is JsonNumberHandling numberHandling) writer.WriteLine($"NumberHandling = {FormatNumberHandling(numberHandling)},"); diff --git a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs index 9ae7ea968178dd..5d94f860cd785f 100644 --- a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs +++ b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs @@ -272,6 +272,7 @@ private SourceGenerationOptionsSpec ParseJsonSourceGenerationOptionsAttribute(IN bool? ignoreReadOnlyProperties = null; bool? includeFields = null; int? maxDepth = null; + string? newLine = null; JsonNumberHandling? numberHandling = null; JsonObjectCreationHandling? preferredObjectCreationHandling = null; bool? propertyNameCaseInsensitive = null; @@ -344,6 +345,10 @@ private SourceGenerationOptionsSpec ParseJsonSourceGenerationOptionsAttribute(IN maxDepth = (int)namedArg.Value.Value!; break; + case nameof(JsonSourceGenerationOptionsAttribute.NewLine): + newLine = (string)namedArg.Value.Value!; + break; + case nameof(JsonSourceGenerationOptionsAttribute.NumberHandling): numberHandling = (JsonNumberHandling)namedArg.Value.Value!; break; @@ -411,6 +416,7 @@ private SourceGenerationOptionsSpec ParseJsonSourceGenerationOptionsAttribute(IN IgnoreReadOnlyProperties = ignoreReadOnlyProperties, IncludeFields = includeFields, MaxDepth = maxDepth, + NewLine = newLine, NumberHandling = numberHandling, PreferredObjectCreationHandling = preferredObjectCreationHandling, PropertyNameCaseInsensitive = propertyNameCaseInsensitive, diff --git a/src/libraries/System.Text.Json/gen/Model/SourceGenerationOptionsSpec.cs b/src/libraries/System.Text.Json/gen/Model/SourceGenerationOptionsSpec.cs index 82ad9ff711af14..e16bebb6ceb49e 100644 --- a/src/libraries/System.Text.Json/gen/Model/SourceGenerationOptionsSpec.cs +++ b/src/libraries/System.Text.Json/gen/Model/SourceGenerationOptionsSpec.cs @@ -36,6 +36,8 @@ public sealed record SourceGenerationOptionsSpec public required int? MaxDepth { get; init; } + public required string? NewLine { get; init; } + public required JsonNumberHandling? NumberHandling { get; init; } public required JsonObjectCreationHandling? PreferredObjectCreationHandling { get; init; } diff --git a/src/libraries/System.Text.Json/ref/System.Text.Json.cs b/src/libraries/System.Text.Json/ref/System.Text.Json.cs index c0f23522b137d2..0ff5bdc90a66ee 100644 --- a/src/libraries/System.Text.Json/ref/System.Text.Json.cs +++ b/src/libraries/System.Text.Json/ref/System.Text.Json.cs @@ -385,6 +385,7 @@ public JsonSerializerOptions(System.Text.Json.JsonSerializerOptions options) { } public bool IncludeFields { get { throw null; } set { } } public bool IsReadOnly { get { throw null; } } public int MaxDepth { get { throw null; } set { } } + public string NewLine { get { throw null; } set { } } public System.Text.Json.Serialization.JsonNumberHandling NumberHandling { get { throw null; } set { } } public System.Text.Json.Serialization.JsonObjectCreationHandling PreferredObjectCreationHandling { get { throw null; } set { } } public bool PropertyNameCaseInsensitive { get { throw null; } set { } } @@ -445,6 +446,7 @@ public partial struct JsonWriterOptions public bool Indented { get { throw null; } set { } } public char IndentCharacter { get { throw null; } set { } } public int IndentSize { get { throw null; } set { } } + public string NewLine { get { throw null; } set { } } public int MaxDepth { readonly get { throw null; } set { } } public bool SkipValidation { get { throw null; } set { } } } @@ -1072,6 +1074,7 @@ public JsonSourceGenerationOptionsAttribute(System.Text.Json.JsonSerializerDefau public bool IgnoreReadOnlyProperties { get { throw null; } set { } } public bool IncludeFields { get { throw null; } set { } } public int MaxDepth { get { throw null; } set { } } + public string? NewLine { get { throw null; } set { } } public System.Text.Json.Serialization.JsonNumberHandling NumberHandling { get { throw null; } set { } } public System.Text.Json.Serialization.JsonObjectCreationHandling PreferredObjectCreationHandling { get { throw null; } set { } } public bool PropertyNameCaseInsensitive { get { throw null; } set { } } diff --git a/src/libraries/System.Text.Json/src/Resources/Strings.resx b/src/libraries/System.Text.Json/src/Resources/Strings.resx index 54d82b5f057850..ba1c414d63f865 100644 --- a/src/libraries/System.Text.Json/src/Resources/Strings.resx +++ b/src/libraries/System.Text.Json/src/Resources/Strings.resx @@ -717,4 +717,7 @@ Indentation size must be between {0} and {1}. + + Only the strings '\n' or '\r\n' are permitted. + diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs index 078a6a4b83777e..7fe47499c1aa85 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs @@ -28,6 +28,9 @@ internal static partial class JsonConstants public const byte UtcOffsetToken = (byte)'Z'; public const byte TimePrefix = (byte)'T'; + public const string NewLineLineFeed = "\n"; + public const string NewLineCarriageReturnLineFeed = "\r\n"; + // \u2028 and \u2029 are considered respectively line and paragraph separators // UTF-8 representation for them is E2, 80, A8/A9 public const byte StartingByteOfNonStandardSeparator = 0xE2; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs index 246d3ab303fcea..dc289eeaaf5419 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs @@ -89,6 +89,7 @@ public static JsonSerializerOptions Web private bool _ignoreReadOnlyProperties; private bool _ignoreReadonlyFields; private bool _includeFields; + private string _newLine = Environment.NewLine; private bool _propertyNameCaseInsensitive; private bool _writeIndented; private char _indentCharacter = JsonConstants.DefaultIndentCharacter; @@ -141,6 +142,7 @@ public JsonSerializerOptions(JsonSerializerOptions options) _ignoreReadOnlyProperties = options._ignoreReadOnlyProperties; _ignoreReadonlyFields = options._ignoreReadonlyFields; _includeFields = options._includeFields; + _newLine = options._newLine; _propertyNameCaseInsensitive = options._propertyNameCaseInsensitive; _writeIndented = options._writeIndented; _indentCharacter = options._indentCharacter; @@ -750,6 +752,30 @@ public ReferenceHandler? ReferenceHandler } } + /// + /// Gets or sets the new line string to use when is . + /// The default is the value of . + /// + /// + /// Thrown when the new line string is not \n or \r\n. + /// + /// + /// Thrown if this property is set after serialization or deserialization has occurred. + /// + public string NewLine + { + get + { + return _newLine; + } + set + { + JsonWriterHelper.ValidateNewLine(value); + VerifyMutable(); + _newLine = value; + } + } + /// /// Returns true if options uses compatible built-in resolvers or a combination of compatible built-in resolvers. /// @@ -970,6 +996,7 @@ internal JsonWriterOptions GetWriterOptions() IndentCharacter = IndentCharacter, IndentSize = IndentSize, MaxDepth = EffectiveMaxDepth, + NewLine = NewLine, #if !DEBUG SkipValidation = true #endif diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs index 58bd0a71724911..6976d42b967bc9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs @@ -12,6 +12,12 @@ internal static partial class ThrowHelper // If the exception source is this value, the serializer will re-throw as JsonException. public const string ExceptionSourceValueToRethrowAsJsonException = "System.Text.Json.Rethrowable"; + [DoesNotReturn] + public static void ThrowArgumentOutOfRangeException_NewLine(string parameterName) + { + throw GetArgumentOutOfRangeException(parameterName, SR.InvalidNewLine); + } + [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_IndentCharacter(string parameterName) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs index c34c8cd3d672f9..05a163f6c4913d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs @@ -36,6 +36,13 @@ public static void WriteIndentation(Span buffer, int indent, byte indentBy } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateNewLine(string value) + { + if (value is not JsonConstants.NewLineLineFeed and not JsonConstants.NewLineCarriageReturnLineFeed) + ThrowHelper.ThrowArgumentOutOfRangeException_NewLine(nameof(value)); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateIndentCharacter(char value) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs index 1d89e5d6aa1499..79e0d9ab2424cb 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs @@ -13,6 +13,8 @@ namespace System.Text.Json /// public struct JsonWriterOptions { + private static readonly string s_alternateNewLine = Environment.NewLine.Length == 2 ? JsonConstants.NewLineLineFeed : JsonConstants.NewLineCarriageReturnLineFeed; + internal const int DefaultMaxDepth = 1000; private int _maxDepth; @@ -68,11 +70,11 @@ public char IndentCharacter /// is out of the allowed range. public int IndentSize { - readonly get => EncodeIndentSize((_optionsMask & IndentSizeMask) >> 3); + readonly get => EncodeIndentSize((_optionsMask & IndentSizeMask) >> OptionsBitCount); set { JsonWriterHelper.ValidateIndentSize(value); - _optionsMask = (_optionsMask & ~IndentSizeMask) | (EncodeIndentSize(value) << 3); + _optionsMask = (_optionsMask & ~IndentSizeMask) | (EncodeIndentSize(value) << OptionsBitCount); } } @@ -135,11 +137,33 @@ public bool SkipValidation } } + /// + /// Gets or sets the new line string to use when is . + /// The default is the value of . + /// + /// + /// Thrown when the new line string is not \n or \r\n. + /// + public string NewLine + { + get => (_optionsMask & NewLineBit) != 0 ? s_alternateNewLine : Environment.NewLine; + set + { + JsonWriterHelper.ValidateNewLine(value); + if (value != Environment.NewLine) + _optionsMask |= NewLineBit; + else + _optionsMask &= ~NewLineBit; + } + } + internal bool IndentedOrNotSkipValidation => (_optionsMask & (IndentBit | SkipValidationBit)) != SkipValidationBit; // Equivalent to: Indented || !SkipValidation; + private const int OptionsBitCount = 4; private const int IndentBit = 1; private const int SkipValidationBit = 2; - private const int IndentCharacterBit = 4; - private const int IndentSizeMask = JsonConstants.MaximumIndentSize << 3; + private const int NewLineBit = 4; + private const int IndentCharacterBit = 8; + private const int IndentSizeMask = JsonConstants.MaximumIndentSize << OptionsBitCount; } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs index 1a1b3edb2ca805..c97d1cb1546211 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs @@ -284,11 +284,11 @@ private void WriteBase64Indented(ReadOnlySpan escapedPropertyName, ReadOnl int encodedLength = Base64.GetMaxEncodedToUtf8Length(bytes.Length); - Debug.Assert(escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding < int.MaxValue - indent - encodedLength - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding < int.MaxValue - indent - encodedLength - 7 - _newLineLength); // All ASCII, 2 quotes for property name, 2 quotes to surround the base-64 encoded string value, 1 colon, and 1 space => indent + escapedPropertyName.Length + encodedLength + 6 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding. - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + encodedLength + 7 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + encodedLength + 7 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -334,11 +334,11 @@ private void WriteBase64Indented(ReadOnlySpan escapedPropertyName, ReadOnl int encodedLength = Base64.GetMaxEncodedToUtf8Length(bytes.Length); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - encodedLength - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - encodedLength - 7 - _newLineLength); // 2 quotes for property name, 2 quotes to surround the base-64 encoded string value, 1 colon, and 1 space => indent + escapedPropertyName.Length + encodedLength + 6 // Optionally, 1 list separator, and 1-2 bytes for new line. - int maxRequired = indent + escapedPropertyName.Length + encodedLength + 7 + s_newLineLength; + int maxRequired = indent + escapedPropertyName.Length + encodedLength + 7 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs index 392facd7d85ee2..9e1f07e25e019a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs @@ -286,11 +286,11 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTim int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatDateTimeOffsetLength - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatDateTimeOffsetLength - 7 - _newLineLength); // All ASCII, 2 quotes for property name, 2 quotes for date, 1 colon, and 1 space => escapedPropertyName.Length + JsonConstants.MaximumFormatDateTimeOffsetLength + 6 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatDateTimeOffsetLength + 7 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatDateTimeOffsetLength + 7 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -335,10 +335,10 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTim int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatDateTimeOffsetLength - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatDateTimeOffsetLength - 7 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatDateTimeOffsetLength + 6; // 2 quotes for property name, 2 quotes for date, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs index 313693b3b7665f..38809447b91b09 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs @@ -285,11 +285,11 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTim int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatDateTimeOffsetLength - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatDateTimeOffsetLength - 7 - _newLineLength); // All ASCII, 2 quotes for property name, 2 quotes for date, 1 colon, and 1 space => escapedPropertyName.Length + JsonConstants.MaximumFormatDateTimeOffsetLength + 6 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatDateTimeOffsetLength + 7 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatDateTimeOffsetLength + 7 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -334,10 +334,10 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTim int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatDateTimeOffsetLength - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatDateTimeOffsetLength - 7 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatDateTimeOffsetLength + 6; // 2 quotes for property name, 2 quotes for date, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs index 3f1af56067cd9b..aadc70a39b5f04 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs @@ -279,11 +279,11 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, decimal int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatDecimalLength - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatDecimalLength - 5 - _newLineLength); // All ASCII, 2 quotes for property name, 1 colon, and 1 space => escapedPropertyName.Length + JsonConstants.MaximumFormatDecimalLength + 4 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatDecimalLength + 5 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatDecimalLength + 5 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -325,10 +325,10 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, decimal int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatDecimalLength - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatDecimalLength - 5 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatDecimalLength + 4; // 2 quotes for property name, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs index eee0535903cfa1..4a58e3057ac6cb 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs @@ -283,11 +283,11 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, double int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatDoubleLength - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatDoubleLength - 5 - _newLineLength); // All ASCII, 2 quotes for property name, 1 colon, and 1 space => escapedPropertyName.Length + JsonConstants.MaximumFormatDoubleLength + 4 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatDoubleLength + 5 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatDoubleLength + 5 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -329,10 +329,10 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, double int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatDoubleLength - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatDoubleLength - 5 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatDoubleLength + 4; // 2 quotes for property name, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs index 133c95ece5d865..f3b6b4847f2ddd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs @@ -283,11 +283,11 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, float v int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatSingleLength - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatSingleLength - 5 - _newLineLength); // All ASCII, 2 quotes for property name, 1 colon, and 1 space => escapedPropertyName.Length + JsonConstants.MaximumFormatSingleLength + 4 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatSingleLength + 5 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatSingleLength + 5 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -329,10 +329,10 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, float v int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatSingleLength - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatSingleLength - 5 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatSingleLength + 4; // 2 quotes for property name, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs index 1ded7b8f3f6a15..004a0d228eea8a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs @@ -287,11 +287,11 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, Guid va int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatGuidLength - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatGuidLength - 7 - _newLineLength); // All ASCII, 2 quotes for property name, 2 quotes for date, 1 colon, and 1 space => escapedPropertyName.Length + JsonConstants.MaximumFormatGuidLength + 6 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatGuidLength + 7 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatGuidLength + 7 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -337,10 +337,10 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, Guid va int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatGuidLength - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatGuidLength - 7 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatGuidLength + 6; // 2 quotes for property name, 2 quotes for date, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Helpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Helpers.cs index c09aaa40c8a23e..95a0a67451641c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Helpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Helpers.cs @@ -91,10 +91,10 @@ private void WritePropertyNameIndented(ReadOnlySpan escapedPropertyName, b int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - 6 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - 6 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + 5; // 2 quotes, 1 colon, 1 space, and 1 start token - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { @@ -163,11 +163,11 @@ private void WritePropertyNameIndented(ReadOnlySpan escapedPropertyName, b int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - 6 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - 6 - _newLineLength); // All ASCII, 2 quotes, 1 colon, 1 space, and 1 start token => indent + escapedPropertyName.Length + 5 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 6 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 6 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs index aff0da471b1a3f..bf41ed2e526482 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs @@ -430,11 +430,11 @@ private void WriteLiteralIndented(ReadOnlySpan escapedPropertyName, ReadOn Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(value.Length <= JsonConstants.MaxUnescapedTokenSize); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - value.Length - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - value.Length - 5 - _newLineLength); // All ASCII, 2 quotes for property name, 1 colon, and 1 space => escapedPropertyName.Length + value.Length + 4 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + value.Length + 5 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + value.Length + 5 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -476,10 +476,10 @@ private void WriteLiteralIndented(ReadOnlySpan escapedPropertyName, ReadOn Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(value.Length <= JsonConstants.MaxUnescapedTokenSize); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - value.Length - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - value.Length - 5 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + value.Length + 4; // 2 quotes for property name, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs index 82694f738cc76c..633d0e1c86aaee 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs @@ -355,11 +355,11 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, long va int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatInt64Length - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatInt64Length - 5 - _newLineLength); // All ASCII, 2 quotes for property name, 1 colon, and 1 space => escapedPropertyName.Length + JsonConstants.MaximumFormatInt64Length + 4 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatInt64Length + 5 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatInt64Length + 5 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -401,10 +401,10 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, long va int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatInt64Length - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatInt64Length - 5 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatInt64Length + 4; // 2 quotes for property name, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs index 16629ea424f4cf..3c4179d5906ebd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs @@ -190,11 +190,11 @@ private void WriteStringIndentedPropertyName(ReadOnlySpan escapedPropertyN Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(escapedPropertyName.Length <= JsonConstants.MaxEscapedTokenSize); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue - 5 - indent - s_newLineLength) / JsonConstants.MaxExpansionFactorWhileTranscoding); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue - 5 - indent - _newLineLength) / JsonConstants.MaxExpansionFactorWhileTranscoding); // All ASCII, 2 quotes for property name, 1 colon, and 1 space => escapedPropertyName.Length + 4 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 5 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 5 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -378,10 +378,10 @@ private void WriteStringIndentedPropertyName(ReadOnlySpan escapedPropertyN Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(escapedPropertyName.Length <= JsonConstants.MaxEscapedTokenSize); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - 5 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + 4; // 2 quotes for property name, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { @@ -1516,11 +1516,11 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnl Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(escapedValue.Length <= JsonConstants.MaxEscapedTokenSize); - Debug.Assert(escapedPropertyName.Length < ((int.MaxValue - 7 - indent - s_newLineLength) / JsonConstants.MaxExpansionFactorWhileTranscoding) - escapedValue.Length); + Debug.Assert(escapedPropertyName.Length < ((int.MaxValue - 7 - indent - _newLineLength) / JsonConstants.MaxExpansionFactorWhileTranscoding) - escapedValue.Length); // All ASCII, 2 quotes for property name, 2 quotes for value, 1 colon, and 1 space => escapedPropertyName.Length + escapedValue.Length + 6 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + ((escapedPropertyName.Length + escapedValue.Length) * JsonConstants.MaxExpansionFactorWhileTranscoding) + 7 + s_newLineLength; + int maxRequired = indent + ((escapedPropertyName.Length + escapedValue.Length) * JsonConstants.MaxExpansionFactorWhileTranscoding) + 7 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -1566,10 +1566,10 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnl Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(escapedValue.Length <= JsonConstants.MaxEscapedTokenSize); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - escapedValue.Length - 7 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - escapedValue.Length - 7 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + escapedValue.Length + 6; // 2 quotes for property name, 2 quotes for value, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { @@ -1617,11 +1617,11 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnl Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(escapedValue.Length <= JsonConstants.MaxEscapedTokenSize); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - escapedValue.Length - 7 - indent - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - escapedValue.Length - 7 - indent - _newLineLength); // All ASCII, 2 quotes for property name, 2 quotes for value, 1 colon, and 1 space => escapedPropertyName.Length + escapedValue.Length + 6 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + escapedValue.Length + 7 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + escapedValue.Length + 7 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -1668,11 +1668,11 @@ private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnl Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(escapedValue.Length <= JsonConstants.MaxEscapedTokenSize); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - escapedValue.Length - 7 - indent - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - escapedValue.Length - 7 - indent - _newLineLength); // All ASCII, 2 quotes for property name, 2 quotes for value, 1 colon, and 1 space => escapedPropertyName.Length + escapedValue.Length + 6 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedValue.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + escapedPropertyName.Length + 7 + s_newLineLength; + int maxRequired = indent + (escapedValue.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + escapedPropertyName.Length + 7 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs index 37aad462665995..68536e35cc5d66 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs @@ -364,11 +364,11 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, ulong v int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatUInt64Length - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - JsonConstants.MaximumFormatUInt64Length - 5 - _newLineLength); // All ASCII, 2 quotes for property name, 1 colon, and 1 space => escapedPropertyName.Length + JsonConstants.MaximumFormatUInt64Length + 4 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatUInt64Length + 5 + s_newLineLength; + int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + JsonConstants.MaximumFormatUInt64Length + 5 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -410,10 +410,10 @@ private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, ulong v int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatUInt64Length - 5 - s_newLineLength); + Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatUInt64Length - 5 - _newLineLength); int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatUInt64Length + 4; // 2 quotes for property name, 1 colon, and 1 space - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Bytes.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Bytes.cs index e4b4a877bbd561..a425049e9c28a5 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Bytes.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Bytes.cs @@ -94,7 +94,7 @@ private void WriteBase64Indented(ReadOnlySpan bytes) // as a length longer than that would overflow int.MaxValue when Base64 encoded. However, we // also need the indentation + 2 quotes, and optionally a list separate and 1-2 bytes for a new line. // Validate the encoded bytes length won't overflow with all of the length. - int extraSpaceRequired = indent + 3 + s_newLineLength; + int extraSpaceRequired = indent + 3 + _newLineLength; int maxLengthAllowed = int.MaxValue / 4 * 3 - extraSpaceRequired; if (bytes.Length > maxLengthAllowed) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs index 93f11451f454d7..aa62396df6c876 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs @@ -107,11 +107,11 @@ private void WriteCommentIndented(ReadOnlySpan value) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(value.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - 4 - s_newLineLength); + Debug.Assert(value.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - 4 - _newLineLength); // All ASCII, /*...*/ => escapedValue.Length + 4 // Optionally, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (value.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 4 + s_newLineLength; + int maxRequired = indent + (value.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 4 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -214,10 +214,10 @@ private void WriteCommentIndented(ReadOnlySpan utf8Value) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(utf8Value.Length < int.MaxValue - indent - 4 - s_newLineLength); + Debug.Assert(utf8Value.Length < int.MaxValue - indent - 4 - _newLineLength); int minRequired = indent + utf8Value.Length + 4; // /*...*/ - int maxRequired = minRequired + s_newLineLength; // Optionally, 1-2 bytes for new line + int maxRequired = minRequired + _newLineLength; // Optionally, 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.DateTime.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.DateTime.cs index ad8a887cdf55a0..5366496ca74ec7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.DateTime.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.DateTime.cs @@ -69,7 +69,7 @@ private void WriteStringValueIndented(DateTime value) Debug.Assert(indent <= _indentLength * _options.MaxDepth); // 2 quotes, and optionally, 1 list separator and 1-2 bytes for new line - int maxRequired = indent + JsonConstants.MaximumFormatDateTimeOffsetLength + 3 + s_newLineLength; + int maxRequired = indent + JsonConstants.MaximumFormatDateTimeOffsetLength + 3 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.DateTimeOffset.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.DateTimeOffset.cs index 1ee48004f21fd8..0fa10649ac2412 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.DateTimeOffset.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.DateTimeOffset.cs @@ -70,7 +70,7 @@ private void WriteStringValueIndented(DateTimeOffset value) Debug.Assert(indent <= _indentLength * _options.MaxDepth); // 2 quotes, and optionally, 1 list separator and 1-2 bytes for new line - int maxRequired = indent + JsonConstants.MaximumFormatDateTimeOffsetLength + 3 + s_newLineLength; + int maxRequired = indent + JsonConstants.MaximumFormatDateTimeOffsetLength + 3 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Decimal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Decimal.cs index 35089030c2d454..65bfff3b6c6e1d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Decimal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Decimal.cs @@ -65,7 +65,7 @@ private void WriteNumberValueIndented(decimal value) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - int maxRequired = indent + JsonConstants.MaximumFormatDecimalLength + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = indent + JsonConstants.MaximumFormatDecimalLength + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Double.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Double.cs index b638931ce12293..03fab27688d0dc 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Double.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Double.cs @@ -69,7 +69,7 @@ private void WriteNumberValueIndented(double value) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - int maxRequired = indent + JsonConstants.MaximumFormatDoubleLength + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = indent + JsonConstants.MaximumFormatDoubleLength + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Float.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Float.cs index c1755c7c4dc5d3..7342704d3479ae 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Float.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Float.cs @@ -69,7 +69,7 @@ private void WriteNumberValueIndented(float value) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - int maxRequired = indent + JsonConstants.MaximumFormatSingleLength + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = indent + JsonConstants.MaximumFormatSingleLength + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.FormattedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.FormattedNumber.cs index f4c902e184af4c..c2f8bb8ff82aad 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.FormattedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.FormattedNumber.cs @@ -69,9 +69,9 @@ private void WriteNumberValueIndented(ReadOnlySpan utf8Value) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(utf8Value.Length < int.MaxValue - indent - 1 - s_newLineLength); + Debug.Assert(utf8Value.Length < int.MaxValue - indent - 1 - _newLineLength); - int maxRequired = indent + utf8Value.Length + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = indent + utf8Value.Length + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Guid.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Guid.cs index 695cc83e03680b..fedbc0959f34c9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Guid.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Guid.cs @@ -70,7 +70,7 @@ private void WriteStringValueIndented(Guid value) Debug.Assert(indent <= _indentLength * _options.MaxDepth); // 2 quotes, and optionally, 1 list separator and 1-2 bytes for new line - int maxRequired = indent + JsonConstants.MaximumFormatGuidLength + 3 + s_newLineLength; + int maxRequired = indent + JsonConstants.MaximumFormatGuidLength + 3 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Literal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Literal.cs index 8c0dee44e785e4..fdda2ce6837e12 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Literal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Literal.cs @@ -89,7 +89,7 @@ private void WriteLiteralIndented(ReadOnlySpan utf8Value) Debug.Assert(indent <= _indentLength * _options.MaxDepth); Debug.Assert(utf8Value.Length <= 5); - int maxRequired = indent + utf8Value.Length + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = indent + utf8Value.Length + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.SignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.SignedNumber.cs index b2126de77fb2f1..85d37a858b9c39 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.SignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.SignedNumber.cs @@ -78,7 +78,7 @@ private void WriteNumberValueIndented(long value) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - int maxRequired = indent + JsonConstants.MaximumFormatInt64Length + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = indent + JsonConstants.MaximumFormatInt64Length + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.String.cs index 4ede0fc9bce938..5ff4064d2b59bd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.String.cs @@ -145,11 +145,11 @@ private void WriteStringIndented(ReadOnlySpan escapedValue) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedValue.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - 3 - s_newLineLength); + Debug.Assert(escapedValue.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - 3 - _newLineLength); // All ASCII, 2 quotes => indent + escapedValue.Length + 2 // Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding - int maxRequired = indent + (escapedValue.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 3 + s_newLineLength; + int maxRequired = indent + (escapedValue.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 3 + _newLineLength; if (_memory.Length - BytesPending < maxRequired) { @@ -292,10 +292,10 @@ private void WriteStringIndented(ReadOnlySpan escapedValue) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - Debug.Assert(escapedValue.Length < int.MaxValue - indent - 3 - s_newLineLength); + Debug.Assert(escapedValue.Length < int.MaxValue - indent - 3 - _newLineLength); int minRequired = indent + escapedValue.Length + 2; // 2 quotes - int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.UnsignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.UnsignedNumber.cs index 82ec4677b2224e..eaabba59a7a2ab 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.UnsignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.UnsignedNumber.cs @@ -80,7 +80,7 @@ private void WriteNumberValueIndented(ulong value) int indent = Indentation; Debug.Assert(indent <= _indentLength * _options.MaxDepth); - int maxRequired = indent + JsonConstants.MaximumFormatUInt64Length + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line + int maxRequired = indent + JsonConstants.MaximumFormatUInt64Length + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line if (_memory.Length - BytesPending < maxRequired) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs index 315b7a30b8e207..f83b7d11ae2159 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs @@ -35,7 +35,7 @@ namespace System.Text.Json public sealed partial class Utf8JsonWriter : IDisposable, IAsyncDisposable { // Depending on OS, either '\r\n' OR '\n' - private static readonly int s_newLineLength = Environment.NewLine.Length; + private static readonly int s_defaultNewLineLength = Environment.NewLine.Length; private const int DefaultGrowthSize = 4096; private const int InitialGrowthSize = 256; @@ -61,6 +61,7 @@ public sealed partial class Utf8JsonWriter : IDisposable, IAsyncDisposable // Cache indentation settings from JsonWriterOptions to avoid recomputing them in the hot path. private byte _indentByte; private int _indentLength; + private int _newLineLength = s_defaultNewLineLength; /// /// Returns the amount of bytes written by the so far @@ -150,6 +151,7 @@ private void SetOptions(JsonWriterOptions options) _options = options; _indentByte = (byte)_options.IndentCharacter; _indentLength = options.IndentSize; + _newLineLength = options.NewLine.Length; if (_options.MaxDepth == 0) { @@ -1024,7 +1026,7 @@ private void WriteEndIndented(byte token) private void WriteNewLine(Span output) { // Write '\r\n' OR '\n', depending on OS - if (s_newLineLength == 2) + if (_newLineLength == 2) { output[BytesPending++] = JsonConstants.CarriageReturn; } diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSourceGenerationOptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSourceGenerationOptionsTests.cs index 0b24bf6ef67672..74aee9393a2f23 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSourceGenerationOptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSourceGenerationOptionsTests.cs @@ -71,6 +71,7 @@ public static void ContextWithAllOptionsSet_GeneratesExpectedOptions() IgnoreReadOnlyProperties = true, IncludeFields = true, MaxDepth = 1024, + NewLine = "\n", NumberHandling = JsonNumberHandling.WriteAsString, PreferredObjectCreationHandling = JsonObjectCreationHandling.Replace, PropertyNameCaseInsensitive = true, @@ -101,6 +102,7 @@ public static void ContextWithAllOptionsSet_GeneratesExpectedOptions() IgnoreReadOnlyProperties = true, IncludeFields = true, MaxDepth = 1024, + NewLine = "\n", NumberHandling = JsonNumberHandling.WriteAsString, PreferredObjectCreationHandling = JsonObjectCreationHandling.Replace, PropertyNameCaseInsensitive = true, diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs index 127ca9601150db..cde68d536bd81b 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs @@ -19,6 +19,7 @@ public static void JsonWriterOptionsDefaultCtor() IndentSize = 2, SkipValidation = false, MaxDepth = 0, + NewLine = Environment.NewLine, }; Assert.Equal(expectedOption, options); } @@ -35,16 +36,17 @@ public static void JsonWriterOptionsCtor() IndentSize = 2, SkipValidation = false, MaxDepth = 0, + NewLine = Environment.NewLine, }; Assert.Equal(expectedOption, options); } [Theory] - [InlineData(true, '\t', 1, true, 0)] - [InlineData(true, ' ', 127, false, 1)] - [InlineData(false, ' ', 0, true, 1024)] - [InlineData(false, ' ', 4, false, 1024 * 1024)] - public static void JsonWriterOptions(bool indented, char indentCharacter, int indentSize, bool skipValidation, int maxDepth) + [InlineData(true, '\t', 1, true, 0, "\n")] + [InlineData(true, ' ', 127, false, 1, "\r\n")] + [InlineData(false, ' ', 0, true, 1024, "\n")] + [InlineData(false, ' ', 4, false, 1024 * 1024, "\r\n")] + public static void JsonWriterOptions(bool indented, char indentCharacter, int indentSize, bool skipValidation, int maxDepth, string newLine) { var options = new JsonWriterOptions(); options.Indented = indented; @@ -52,6 +54,7 @@ public static void JsonWriterOptions(bool indented, char indentCharacter, int in options.IndentSize = indentSize; options.SkipValidation = skipValidation; options.MaxDepth = maxDepth; + options.NewLine = newLine; var expectedOption = new JsonWriterOptions { @@ -60,16 +63,17 @@ public static void JsonWriterOptions(bool indented, char indentCharacter, int in IndentSize = indentSize, SkipValidation = skipValidation, MaxDepth = maxDepth, + NewLine = newLine, }; Assert.Equal(expectedOption, options); } [Theory] - [InlineData(true, '\t', 1, true, 0)] - [InlineData(true, ' ', 127, false, 1)] - [InlineData(false, ' ', 0, true, 1024)] - [InlineData(false, ' ', 4, false, 1024 * 1024)] - public static void JsonWriterOptions_Properties(bool indented, char indentCharacter, int indentSize, bool skipValidation, int maxDepth) + [InlineData(true, '\t', 1, true, 0, "\n")] + [InlineData(true, ' ', 127, false, 1, "\r\n")] + [InlineData(false, ' ', 0, true, 1024, "\n")] + [InlineData(false, ' ', 4, false, 1024 * 1024, "\r\n")] + public static void JsonWriterOptions_Properties(bool indented, char indentCharacter, int indentSize, bool skipValidation, int maxDepth, string newLine) { var options = new JsonWriterOptions(); options.Indented = indented; @@ -77,12 +81,14 @@ public static void JsonWriterOptions_Properties(bool indented, char indentCharac options.IndentSize = indentSize; options.SkipValidation = skipValidation; options.MaxDepth = maxDepth; + options.NewLine = newLine; Assert.Equal(indented, options.Indented); Assert.Equal(indentCharacter, options.IndentCharacter); Assert.Equal(indentSize, options.IndentSize); Assert.Equal(skipValidation, options.SkipValidation); Assert.Equal(maxDepth, options.MaxDepth); + Assert.Equal(newLine, options.NewLine); } [Fact] @@ -95,6 +101,7 @@ public static void JsonWriterOptions_DefaultValues() Assert.Equal(2, options.IndentSize); Assert.False(options.SkipValidation); Assert.Equal(0, options.MaxDepth); + Assert.Equal(Environment.NewLine, options.NewLine); } [Fact] @@ -123,6 +130,10 @@ public static void JsonWriterOptions_MultipleValues() options.MaxDepth = defaultOptions.MaxDepth; Assert.Equal(defaultOptions.MaxDepth, options.MaxDepth); + options.NewLine = Environment.NewLine.Length == 1 ? "\r\n" : "\n"; + options.NewLine = defaultOptions.NewLine; + Assert.Equal(defaultOptions.NewLine, options.NewLine); + Assert.Equal(defaultOptions, options); } @@ -157,5 +168,17 @@ public static void JsonWriterOptions_IndentSize_OutOfRange(int size) var options = new JsonWriterOptions(); Assert.Throws(() => options.IndentSize = size); } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("\r")] + [InlineData("\n\n")] + [InlineData("\r\n\r\n")] + public static void JsonWriterOptions_NewLine_InvalidNewLine(string value) + { + var options = new JsonWriterOptions(); + Assert.Throws(() => options.NewLine = value); + } } } diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs index 877c44d183a120..da3f46614f212c 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs @@ -367,6 +367,7 @@ public static void JsonSerializerOptions_EqualityComparer_ChangingAnySettingShou 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.NewLine)), Environment.NewLine); yield return (GetProp(nameof(JsonSerializerOptions.PropertyNamingPolicy)), JsonNamingPolicy.CamelCase); yield return (GetProp(nameof(JsonSerializerOptions.PropertyNameCaseInsensitive)), true); yield return (GetProp(nameof(JsonSerializerOptions.ReadCommentHandling)), JsonCommentHandling.Skip); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs index 0cca85c6cc033c..67ddd390d8c82b 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs @@ -1416,7 +1416,14 @@ and not nameof(JsonSerializerOptions.IsReadOnly)) // Property is not structural } else if (propertyType == typeof(string)) { - property.SetValue(options, "\t"); + if (property.Name is "NewLine") + { + property.SetValue(options, "\n"); + } + else + { + property.SetValue(options, "\t"); + } } else if (propertyType == typeof(IList)) { diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs index 643762183c713e..bb258556cde71d 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs @@ -1442,7 +1442,7 @@ private static string GetExpectedLargeString(JsonWriterOptions options) json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } [Theory] @@ -2683,12 +2683,12 @@ public void InvalidJsonContinueShouldSucceed(bool formatted) for (int i = 0; i < 100; i++) { if (options.Indented) - sb.Append(Environment.NewLine); + sb.Append(options.NewLine); sb.Append("]"); } sb.Append(","); if (options.Indented) - sb.Append(Environment.NewLine); + sb.Append(options.NewLine); sb.Append("[]"); JsonTestHelper.AssertContents(sb.ToString(), output); @@ -2722,7 +2722,7 @@ public void WriteSeparateProperties(JsonWriterOptions options) json.Flush(); - string expectedStr = HandleIndent(stringWriter.ToString(), options); + string expectedStr = HandleFormatting(stringWriter.ToString(), options); using var jsonUtf8 = new Utf8JsonWriter(output, options); jsonUtf8.WriteStartObject(); @@ -3082,7 +3082,7 @@ public void Writing3MBBase64Bytes(JsonWriterOptions options) Base64.EncodeToUtf8(value, base64StringUtf8, out _, out int bytesWritten); string expectedValue = Encoding.UTF8.GetString(base64StringUtf8.AsSpan(0, bytesWritten).ToArray()); - string expectedJson = options.Indented ? $"{{{Environment.NewLine}{GetIndentText(options)}\"foo\": \"{expectedValue}\"{Environment.NewLine}}}" : $"{{\"foo\":\"{expectedValue}\"}}"; + string expectedJson = options.Indented ? $"{{{options.NewLine}{GetIndentText(options)}\"foo\": \"{expectedValue}\"{options.NewLine}}}" : $"{{\"foo\":\"{expectedValue}\"}}"; var output = new ArrayBufferWriter(1024); @@ -3558,14 +3558,14 @@ public void WritePartialHelloWorld(JsonWriterOptions options) Assert.Equal(0, jsonUtf8.BytesCommitted); if (options.Indented) - Assert.Equal(26 + options.IndentSize + Environment.NewLine.Length + 1, jsonUtf8.BytesPending); // new lines, indentation, white space + Assert.Equal(26 + options.IndentSize + options.NewLine.Length + 1, jsonUtf8.BytesPending); // new lines, indentation, white space else Assert.Equal(26, jsonUtf8.BytesPending); jsonUtf8.Flush(); if (options.Indented) - Assert.Equal(26 + options.IndentSize + Environment.NewLine.Length + 1, jsonUtf8.BytesCommitted); // new lines, indentation, white space + Assert.Equal(26 + options.IndentSize + options.NewLine.Length + 1, jsonUtf8.BytesCommitted); // new lines, indentation, white space else Assert.Equal(26, jsonUtf8.BytesCommitted); @@ -3575,19 +3575,19 @@ public void WritePartialHelloWorld(JsonWriterOptions options) jsonUtf8.WriteEndObject(); if (options.Indented) - Assert.Equal(26 + options.IndentSize + Environment.NewLine.Length + 1, jsonUtf8.BytesCommitted); + Assert.Equal(26 + options.IndentSize + options.NewLine.Length + 1, jsonUtf8.BytesCommitted); else Assert.Equal(26, jsonUtf8.BytesCommitted); if (options.Indented) - Assert.Equal(27 + options.IndentSize + (2 * Environment.NewLine.Length) + 1, jsonUtf8.BytesPending); // new lines, indentation, white space + Assert.Equal(27 + options.IndentSize + (2 * options.NewLine.Length) + 1, jsonUtf8.BytesPending); // new lines, indentation, white space else Assert.Equal(27, jsonUtf8.BytesPending); jsonUtf8.Flush(); if (options.Indented) - Assert.Equal(53 + (2 * options.IndentSize) + (3 * Environment.NewLine.Length) + (1 * 2), jsonUtf8.BytesCommitted); // new lines, indentation, white space + Assert.Equal(53 + (2 * options.IndentSize) + (3 * options.NewLine.Length) + (1 * 2), jsonUtf8.BytesCommitted); // new lines, indentation, white space else Assert.Equal(53, jsonUtf8.BytesCommitted); @@ -3675,14 +3675,14 @@ public void WritePartialBase64String(JsonWriterOptions options) Assert.Equal(0, jsonUtf8.BytesCommitted); if (options.Indented) - Assert.Equal(17 + options.IndentSize + Environment.NewLine.Length + 1, jsonUtf8.BytesPending); // new lines, indentation, white space + Assert.Equal(17 + options.IndentSize + options.NewLine.Length + 1, jsonUtf8.BytesPending); // new lines, indentation, white space else Assert.Equal(17, jsonUtf8.BytesPending); jsonUtf8.Flush(); if (options.Indented) - Assert.Equal(17 + options.IndentSize + Environment.NewLine.Length + 1, jsonUtf8.BytesCommitted); // new lines, indentation, white space + Assert.Equal(17 + options.IndentSize + options.NewLine.Length + 1, jsonUtf8.BytesCommitted); // new lines, indentation, white space else Assert.Equal(17, jsonUtf8.BytesCommitted); @@ -3692,19 +3692,19 @@ public void WritePartialBase64String(JsonWriterOptions options) jsonUtf8.WriteEndObject(); if (options.Indented) - Assert.Equal(17 + options.IndentSize + Environment.NewLine.Length + 1, jsonUtf8.BytesCommitted); + Assert.Equal(17 + options.IndentSize + options.NewLine.Length + 1, jsonUtf8.BytesCommitted); else Assert.Equal(17, jsonUtf8.BytesCommitted); if (options.Indented) - Assert.Equal(18 + options.IndentSize + (2 * Environment.NewLine.Length) + 1, jsonUtf8.BytesPending); // new lines, indentation, white space + Assert.Equal(18 + options.IndentSize + (2 * options.NewLine.Length) + 1, jsonUtf8.BytesPending); // new lines, indentation, white space else Assert.Equal(18, jsonUtf8.BytesPending); jsonUtf8.Flush(); if (options.Indented) - Assert.Equal(35 + (2 * options.IndentSize) + (3 * Environment.NewLine.Length) + (1 * 2), jsonUtf8.BytesCommitted); // new lines, indentation, white space + Assert.Equal(35 + (2 * options.IndentSize) + (3 * options.NewLine.Length) + (1 * 2), jsonUtf8.BytesCommitted); // new lines, indentation, white space else Assert.Equal(35, jsonUtf8.BytesCommitted); @@ -4078,7 +4078,7 @@ private static string GetCommentExpectedString(JsonWriterOptions options) json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } [Theory] @@ -6970,7 +6970,7 @@ private static string GetHelloWorldExpectedString(JsonWriterOptions options, str json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetBase64ExpectedString(JsonWriterOptions options, string propertyName, byte[] value) @@ -6998,7 +6998,7 @@ private static string GetBase64ExpectedString(JsonWriterOptions options, string json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetCommentInArrayExpectedString(JsonWriterOptions options, string comment) @@ -7032,7 +7032,7 @@ private static string GetCommentInArrayExpectedString(JsonWriterOptions options, json.WriteComment(comment); json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetCommentInObjectExpectedString(JsonWriterOptions options, string comment) @@ -7098,7 +7098,7 @@ private static string GetCommentInObjectExpectedString(JsonWriterOptions options json.WriteComment(comment); json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetStringsExpectedString(JsonWriterOptions options, string value) @@ -7118,7 +7118,7 @@ private static string GetStringsExpectedString(JsonWriterOptions options, string json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetEscapedExpectedString(JsonWriterOptions options, string propertyName, string value, StringEscapeHandling escaping, bool escape = true) @@ -7136,7 +7136,7 @@ private static string GetEscapedExpectedString(JsonWriterOptions options, string json.WriteEnd(); json.Flush(); - return HandleIndent(stringWriter.ToString(), options); + return HandleFormatting(stringWriter.ToString(), options); } } @@ -7160,7 +7160,7 @@ private static string GetCustomExpectedString(JsonWriterOptions options) json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetStartEndExpectedString(JsonWriterOptions options) @@ -7180,7 +7180,7 @@ private static string GetStartEndExpectedString(JsonWriterOptions options) json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetStartEndWithPropertyArrayExpectedString(JsonWriterOptions options) @@ -7201,7 +7201,7 @@ private static string GetStartEndWithPropertyArrayExpectedString(JsonWriterOptio json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetStartEndWithPropertyArrayExpectedString(string key, JsonWriterOptions options, bool escape = false) @@ -7223,7 +7223,7 @@ private static string GetStartEndWithPropertyArrayExpectedString(string key, Jso json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetStartEndWithPropertyObjectExpectedString(JsonWriterOptions options) @@ -7244,7 +7244,7 @@ private static string GetStartEndWithPropertyObjectExpectedString(JsonWriterOpti json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetStartEndWithPropertyObjectExpectedString(string key, JsonWriterOptions options, bool escape = false) @@ -7266,7 +7266,7 @@ private static string GetStartEndWithPropertyObjectExpectedString(string key, Js json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetArrayWithPropertyExpectedString(JsonWriterOptions options) @@ -7286,7 +7286,7 @@ private static string GetArrayWithPropertyExpectedString(JsonWriterOptions optio json.WriteEndObject(); json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetBooleanExpectedString(JsonWriterOptions options, string keyString, bool value, bool escape = false) @@ -7316,7 +7316,7 @@ private static string GetBooleanExpectedString(JsonWriterOptions options, string json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetNullExpectedString(JsonWriterOptions options, string keyString, bool escape = false) @@ -7346,7 +7346,7 @@ private static string GetNullExpectedString(JsonWriterOptions options, string ke json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetPropertyExpectedString(JsonWriterOptions options, T value) @@ -7366,7 +7366,7 @@ private static string GetPropertyExpectedString(JsonWriterOptions options, T json.Flush(); - return HandleIndent(sb.ToString(), options); + return HandleFormatting(sb.ToString(), options); } private static string GetNumbersExpectedString(JsonWriterOptions options, string keyString, int[] ints, uint[] uints, long[] longs, ulong[] ulongs, float[] floats, double[] doubles, decimal[] decimals, bool escape = false) @@ -7432,7 +7432,7 @@ private static string GetNumbersExpectedString(JsonWriterOptions options, string json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetExpectedString_RelaxedEscaping(bool prettyPrint, string keyString) @@ -7492,7 +7492,7 @@ private static string GetGuidsExpectedString(JsonWriterOptions options, string k json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetNumbersExpectedString(JsonWriterOptions options, int numberOfElements, T value) @@ -7514,7 +7514,7 @@ private static string GetNumbersExpectedString(JsonWriterOptions options, int json.Flush(); - return HandleIndent(sb.ToString(), options); + return HandleFormatting(sb.ToString(), options); } private static string GetDatesExpectedString(JsonWriterOptions options, string keyString, DateTime[] dates, bool escape = false) @@ -7546,7 +7546,7 @@ private static string GetDatesExpectedString(JsonWriterOptions options, string k json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static string GetDatesExpectedString(JsonWriterOptions options, string keyString, DateTimeOffset[] dates, bool escape = false) @@ -7578,7 +7578,7 @@ private static string GetDatesExpectedString(JsonWriterOptions options, string k json.Flush(); - return HandleIndent(Encoding.UTF8.GetString(ms.ToArray()), options); + return HandleFormatting(Encoding.UTF8.GetString(ms.ToArray()), options); } private static void CompensateWhitespaces(bool prettyPrint, JsonTextWriter json, TextWriter streamWriter, int whitespaceCount = 1) @@ -7599,9 +7599,9 @@ private static void CompensateNewLine(bool prettyPrint, JsonTextWriter json, Tex } } - private static string HandleIndent(string text, JsonWriterOptions options) + private static string HandleFormatting(string text, JsonWriterOptions options) { - return text.Replace(" ", GetIndentText(options)); + return text.Replace(" ", GetIndentText(options)).Replace(Environment.NewLine, options.NewLine); } private static string GetIndentText(JsonWriterOptions options) => new(options.IndentCharacter, options.IndentSize); @@ -7628,13 +7628,15 @@ private static IEnumerable JsonOptions() from skipValidation in new[] { true, false } from indentCharacter in indented ? new char?[] { null, ' ', '\t' } : [] from indentSize in indented ? new int?[] { null, 0, 1, 2, 127 } : [] - select CreateOptions(indented, indentCharacter, indentSize, skipValidation); + from newLine in indented ? new string?[] { null, "\n", "\r\n" } : [] + select CreateOptions(indented, indentCharacter, indentSize, skipValidation, newLine); - static JsonWriterOptions CreateOptions(bool indented, char? indentCharacter, int? indentSize, bool skipValidation) + static JsonWriterOptions CreateOptions(bool indented, char? indentCharacter, int? indentSize, bool skipValidation, string? newLine) { var options = new JsonWriterOptions { Indented = indented, SkipValidation = skipValidation }; if (indentCharacter is not null) options.IndentCharacter = (char)indentCharacter; if (indentSize is not null) options.IndentSize = (int)indentSize; + if (newLine is not null) options.NewLine = newLine; return options; } } From ae46fd6b24396c75c163fa1667d950f6a0dfd79e Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 11 Apr 2024 10:12:59 +0100 Subject: [PATCH 2/8] Address review feedback - Cater for `_newLine` in JsonSerializerOptions caching. - Lazily initialize field. - Allow null to reset to default. - Add assertions. - Add/update comments. - Use `nameof()`. - Remove redundant field. - Extend tests. --- .../JsonSerializerOptions.Caching.cs | 4 +- .../Serialization/JsonSerializerOptions.cs | 4 +- .../Text/Json/Writer/JsonWriterHelper.cs | 2 +- .../Text/Json/Writer/JsonWriterOptions.cs | 2 +- .../System/Text/Json/Writer/Utf8JsonWriter.cs | 12 ++-- .../JsonWriterOptionsTests.cs | 17 ++++++ .../Serialization/CacheTests.cs | 2 +- .../Serialization/OptionsTests.cs | 56 ++++++++++++++++++- 8 files changed, 87 insertions(+), 12 deletions(-) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs index ad529fa034fb9f..17e68810972582 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs @@ -504,6 +504,7 @@ public bool Equals(JsonSerializerOptions? left, JsonSerializerOptions? right) left._unmappedMemberHandling == right._unmappedMemberHandling && left._defaultBufferSize == right._defaultBufferSize && left._maxDepth == right._maxDepth && + left._newLine == right._newLine && left._allowOutOfOrderMetadataProperties == right._allowOutOfOrderMetadataProperties && left._allowTrailingCommas == right._allowTrailingCommas && left._ignoreNullValues == right._ignoreNullValues && @@ -561,6 +562,7 @@ public int GetHashCode(JsonSerializerOptions options) AddHashCode(ref hc, options._unmappedMemberHandling); AddHashCode(ref hc, options._defaultBufferSize); AddHashCode(ref hc, options._maxDepth); + AddHashCode(ref hc, options._newLine ?? Environment.NewLine); // Null is equivalent to the default AddHashCode(ref hc, options._allowOutOfOrderMetadataProperties); AddHashCode(ref hc, options._allowTrailingCommas); AddHashCode(ref hc, options._ignoreNullValues); @@ -591,7 +593,7 @@ static void AddListHashCode(ref HashCode hc, ConfigurationList? static void AddHashCode(ref HashCode hc, TValue? value) { - if (typeof(TValue).IsValueType) + if (typeof(TValue).IsValueType || typeof(TValue) == typeof(string)) { hc.Add(value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs index dc289eeaaf5419..616220b2204f9c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs @@ -89,7 +89,7 @@ public static JsonSerializerOptions Web private bool _ignoreReadOnlyProperties; private bool _ignoreReadonlyFields; private bool _includeFields; - private string _newLine = Environment.NewLine; + private string? _newLine; private bool _propertyNameCaseInsensitive; private bool _writeIndented; private char _indentCharacter = JsonConstants.DefaultIndentCharacter; @@ -766,7 +766,7 @@ public string NewLine { get { - return _newLine; + return _newLine ??= Environment.NewLine; } set { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs index 05a163f6c4913d..e47cffa1273ff8 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs @@ -39,7 +39,7 @@ public static void WriteIndentation(Span buffer, int indent, byte indentBy [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateNewLine(string value) { - if (value is not JsonConstants.NewLineLineFeed and not JsonConstants.NewLineCarriageReturnLineFeed) + if (value is not null && value is not JsonConstants.NewLineLineFeed and not JsonConstants.NewLineCarriageReturnLineFeed) ThrowHelper.ThrowArgumentOutOfRangeException_NewLine(nameof(value)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs index 79e0d9ab2424cb..ec9452eb4fb938 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs @@ -150,7 +150,7 @@ public string NewLine set { JsonWriterHelper.ValidateNewLine(value); - if (value != Environment.NewLine) + if (value is not null && value != Environment.NewLine) _optionsMask |= NewLineBit; else _optionsMask &= ~NewLineBit; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs index f83b7d11ae2159..fcf3ab2d4c2547 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs @@ -34,9 +34,6 @@ namespace System.Text.Json [DebuggerDisplay("{DebuggerDisplay,nq}")] public sealed partial class Utf8JsonWriter : IDisposable, IAsyncDisposable { - // Depending on OS, either '\r\n' OR '\n' - private static readonly int s_defaultNewLineLength = Environment.NewLine.Length; - private const int DefaultGrowthSize = 4096; private const int InitialGrowthSize = 256; @@ -61,7 +58,9 @@ public sealed partial class Utf8JsonWriter : IDisposable, IAsyncDisposable // Cache indentation settings from JsonWriterOptions to avoid recomputing them in the hot path. private byte _indentByte; private int _indentLength; - private int _newLineLength = s_defaultNewLineLength; + + // A length of 1 will emit LF for indented writes, a length of 2 will emit CRLF. Other values are invalid. + private int _newLineLength; /// /// Returns the amount of bytes written by the so far @@ -151,6 +150,8 @@ private void SetOptions(JsonWriterOptions options) _options = options; _indentByte = (byte)_options.IndentCharacter; _indentLength = options.IndentSize; + + Debug.Assert(options.NewLine is "\n" or "\r\n", "Invalid NewLine string."); _newLineLength = options.NewLine.Length; if (_options.MaxDepth == 0) @@ -1025,7 +1026,8 @@ private void WriteEndIndented(byte token) [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteNewLine(Span output) { - // Write '\r\n' OR '\n', depending on OS + // Write '\r\n' OR '\n', depending on the configured new line string + Debug.Assert(_newLineLength is 1 or 2, "Invalid new line length."); if (_newLineLength == 2) { output[BytesPending++] = JsonConstants.CarriageReturn; diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs index cde68d536bd81b..c6a35147a0c74f 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs @@ -175,10 +175,27 @@ public static void JsonWriterOptions_IndentSize_OutOfRange(int size) [InlineData("\r")] [InlineData("\n\n")] [InlineData("\r\n\r\n")] + [InlineData("0")] + [InlineData("a")] + [InlineData("foo")] + [InlineData("$")] + [InlineData(".")] + [InlineData("\u03b1")] public static void JsonWriterOptions_NewLine_InvalidNewLine(string value) { var options = new JsonWriterOptions(); Assert.Throws(() => options.NewLine = value); } + + [Fact] + public static void JsonWriterOptions_NewLine_Null_Resets_To_Default() + { + var options = new JsonWriterOptions(); + + options.NewLine = "\n"; + options.NewLine = null!; + + Assert.Equal(Environment.NewLine, options.NewLine); + } } } diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs index da3f46614f212c..64d96934ed7804 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs @@ -367,7 +367,7 @@ public static void JsonSerializerOptions_EqualityComparer_ChangingAnySettingShou 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.NewLine)), Environment.NewLine); + yield return (GetProp(nameof(JsonSerializerOptions.NewLine)), Environment.NewLine.Length is 1 ? "\r\n" : "\n"); yield return (GetProp(nameof(JsonSerializerOptions.PropertyNamingPolicy)), JsonNamingPolicy.CamelCase); yield return (GetProp(nameof(JsonSerializerOptions.PropertyNameCaseInsensitive)), true); yield return (GetProp(nameof(JsonSerializerOptions.ReadCommentHandling)), JsonCommentHandling.Skip); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs index 67ddd390d8c82b..2358bce944935c 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs @@ -516,6 +516,60 @@ public static void MaxDepthRead() Assert.Throws(() => JsonSerializer.Deserialize(BasicCompany.s_data, options)); } + [Theory] + [InlineData(new char[] { '\n' }, '\r')] + [InlineData(new char[] { '\r', '\n' }, null)] + public static void NewLine(char[] newLineChars, char? notExpectedNewLineChars) + { + var obj = new BasicCompany(); + obj.Initialize(); + + var newLine = new string(newLineChars); + var options = new JsonSerializerOptions(); + var json = JsonSerializer.Serialize(obj, options); + Assert.DoesNotContain(newLine, json); + + // Set custom newLine with indentation enabled + options = new JsonSerializerOptions(); + options.WriteIndented = true; + options.NewLine = newLine; + json = JsonSerializer.Serialize(obj, options); + Assert.Contains(newLine, json); + + if (notExpectedNewLineChars is { } notExpected) + { + Assert.DoesNotContain(notExpected, json); + } + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("\r")] + [InlineData("\n\n")] + [InlineData("\r\n\r\n")] + [InlineData("0")] + [InlineData("a")] + [InlineData("foo")] + [InlineData("$")] + [InlineData(".")] + [InlineData("\u03b1")] + public static void TestNewLineInvalid(string value) + { + var options = new JsonSerializerOptions(); + Assert.Throws("value", () => options.NewLine = value); + } + + [Fact] + public static void TestNewLineNullResetsToDefault() + { + var options = new JsonSerializerOptions(); + options.NewLine = "\n"; + options.NewLine = null!; + + Assert.Equal(Environment.NewLine, options.NewLine); + } + private class TestClassForEncoding { public string MyString { get; set; } @@ -1416,7 +1470,7 @@ and not nameof(JsonSerializerOptions.IsReadOnly)) // Property is not structural } else if (propertyType == typeof(string)) { - if (property.Name is "NewLine") + if (property.Name is nameof(JsonSerializerOptions.NewLine)) { property.SetValue(options, "\n"); } From 0e7f6f71eab169947fb8bd6a1e0b2a460457b7f5 Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 11 Apr 2024 10:32:21 +0100 Subject: [PATCH 3/8] Update Logging.Console tests - Update property count to fix assertion. - Update test to validate `NewLine` can be set/bound. --- .../ConsoleLoggerConfigureOptions.cs | 2 +- .../ConsoleLoggerExtensionsTests.cs | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerConfigureOptions.cs b/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerConfigureOptions.cs index 3b725f1cb59e03..663b766ba4c92a 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerConfigureOptions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerConfigureOptions.cs @@ -25,7 +25,7 @@ public void EnsureConsoleLoggerOptions_ConfigureOptions_SupportsAllProperties() Assert.Equal(3, typeof(ConsoleFormatterOptions).GetProperties(flags).Length); Assert.Equal(5, typeof(SimpleConsoleFormatterOptions).GetProperties(flags).Length); Assert.Equal(4, typeof(JsonConsoleFormatterOptions).GetProperties(flags).Length); - Assert.Equal(6, typeof(JsonWriterOptions).GetProperties(flags).Length); + Assert.Equal(7, typeof(JsonWriterOptions).GetProperties(flags).Length); } [Theory] diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerExtensionsTests.cs b/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerExtensionsTests.cs index fec2d737c8d2c8..60188dc2ce4f02 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerExtensionsTests.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerExtensionsTests.cs @@ -273,11 +273,13 @@ public void AddSystemdConsole_OutsideConfig_TakesProperty() [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddJsonConsole_ChangeProperties_IsReadFromLoggingConfiguration() { + var newLine = Environment.NewLine.Length is 2 ? "\n" : "\r\n"; var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair("Console:FormatterOptions:IncludeScopes", "true"), new KeyValuePair("Console:FormatterOptions:JsonWriterOptions:Indented", "true"), + new KeyValuePair("Console:FormatterOptions:JsonWriterOptions:NewLine", newLine), }).Build(); var loggerProvider = new ServiceCollection() @@ -296,11 +298,13 @@ public void AddJsonConsole_ChangeProperties_IsReadFromLoggingConfiguration() Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); Assert.True(formatter.FormatterOptions.JsonWriterOptions.Indented); + Assert.Equal(newLine, formatter.FormatterOptions.JsonWriterOptions.NewLine); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddJsonConsole_OutsideConfig_TakesProperty() { + var newLine = Environment.NewLine.Length is 2 ? "\n" : "\r\n"; var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair("Console:FormatterOptions:UseUtcTimestamp", "true"), @@ -314,7 +318,8 @@ public void AddJsonConsole_OutsideConfig_TakesProperty() o.JsonWriterOptions = new JsonWriterOptions() { Indented = false, - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + NewLine = newLine }; }) ) @@ -329,6 +334,7 @@ public void AddJsonConsole_OutsideConfig_TakesProperty() Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); Assert.False(formatter.FormatterOptions.JsonWriterOptions.Indented); + Assert.Equal(newLine, formatter.FormatterOptions.JsonWriterOptions.NewLine); Assert.Equal(JavaScriptEncoder.UnsafeRelaxedJsonEscaping, formatter.FormatterOptions.JsonWriterOptions.Encoder); } From aa4fb3df41afa1500cfef8168e4a6fded39d9ff2 Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 11 Apr 2024 12:21:04 +0100 Subject: [PATCH 4/8] Only normalize line endings if needed Only normalize the line endings if the `JsonWriterOptions` are not using the defaults. --- .../tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs index bb258556cde71d..7ccda56d737a2a 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs @@ -7601,7 +7601,14 @@ private static void CompensateNewLine(bool prettyPrint, JsonTextWriter json, Tex private static string HandleFormatting(string text, JsonWriterOptions options) { - return text.Replace(" ", GetIndentText(options)).Replace(Environment.NewLine, options.NewLine); + var normalized = text.Replace(" ", GetIndentText(options)); + + if (options.NewLine != Environment.NewLine) + { + normalized = normalized.Replace(Environment.NewLine, options.NewLine); + } + + return normalized; } private static string GetIndentText(JsonWriterOptions options) => new(options.IndentCharacter, options.IndentSize); From ad4701310f10ea3f7ea203700c2cde76f606cb31 Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 11 Apr 2024 14:19:52 +0100 Subject: [PATCH 5/8] Address feedback - Access lazily initialized field through property. - Update hash code assertion. --- .../Json/Serialization/JsonSerializerOptions.Caching.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs index 17e68810972582..2ef809c75879c9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs @@ -504,7 +504,7 @@ public bool Equals(JsonSerializerOptions? left, JsonSerializerOptions? right) left._unmappedMemberHandling == right._unmappedMemberHandling && left._defaultBufferSize == right._defaultBufferSize && left._maxDepth == right._maxDepth && - left._newLine == right._newLine && + left.NewLine == right.NewLine && // Read through property due to lazy initialization of the backing field left._allowOutOfOrderMetadataProperties == right._allowOutOfOrderMetadataProperties && left._allowTrailingCommas == right._allowTrailingCommas && left._ignoreNullValues == right._ignoreNullValues && @@ -562,7 +562,7 @@ public int GetHashCode(JsonSerializerOptions options) AddHashCode(ref hc, options._unmappedMemberHandling); AddHashCode(ref hc, options._defaultBufferSize); AddHashCode(ref hc, options._maxDepth); - AddHashCode(ref hc, options._newLine ?? Environment.NewLine); // Null is equivalent to the default + AddHashCode(ref hc, options.NewLine); // Read through property due to lazy initialization of the backing field AddHashCode(ref hc, options._allowOutOfOrderMetadataProperties); AddHashCode(ref hc, options._allowTrailingCommas); AddHashCode(ref hc, options._ignoreNullValues); @@ -593,13 +593,13 @@ static void AddListHashCode(ref HashCode hc, ConfigurationList? static void AddHashCode(ref HashCode hc, TValue? value) { - if (typeof(TValue).IsValueType || typeof(TValue) == typeof(string)) + if (typeof(TValue).IsValueType || !typeof(TValue).IsSealed) { hc.Add(value); } else { - Debug.Assert(!typeof(TValue).IsSealed, "Sealed reference types like string should not use this method."); + // Unsealed types do not use this branch to avoid user-defined equality from being used. hc.Add(RuntimeHelpers.GetHashCode(value)); } } From d96ea1f342e904c7b9fe58b4879e71e1bad2cec6 Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 11 Apr 2024 16:28:03 +0100 Subject: [PATCH 6/8] Update exception message Use similar format string to `Format_InvalidGuidFormatSpecification`/ --- src/libraries/System.Text.Json/src/Resources/Strings.resx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libraries/System.Text.Json/src/Resources/Strings.resx b/src/libraries/System.Text.Json/src/Resources/Strings.resx index ba1c414d63f865..3654ae7dbd3807 100644 --- a/src/libraries/System.Text.Json/src/Resources/Strings.resx +++ b/src/libraries/System.Text.Json/src/Resources/Strings.resx @@ -718,6 +718,6 @@ Indentation size must be between {0} and {1}. - Only the strings '\n' or '\r\n' are permitted. + New line can be only "\n" or "\r\n". From a5e9200ec04b34f5f1a1ee312e9316d74e57765e Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 11 Apr 2024 17:07:53 +0100 Subject: [PATCH 7/8] Address feedback Reword comment as suggested. --- .../Text/Json/Serialization/JsonSerializerOptions.Caching.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs index 2ef809c75879c9..276150ea8ffcc8 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs @@ -599,7 +599,7 @@ static void AddHashCode(ref HashCode hc, TValue? value) } else { - // Unsealed types do not use this branch to avoid user-defined equality from being used. + // Use the built-in hashcode for types that could be overriding GetHashCode(). hc.Add(RuntimeHelpers.GetHashCode(value)); } } From b141671921a4aa43746b93d497d51f7ccb3940f7 Mon Sep 17 00:00:00 2001 From: martincostello Date: Fri, 12 Apr 2024 14:56:36 +0100 Subject: [PATCH 8/8] Address feedback - Simplify condition. - Disallow null for `string NewLine` properties. --- .../Json/Serialization/JsonSerializerOptions.Caching.cs | 2 +- .../Text/Json/Serialization/JsonSerializerOptions.cs | 3 +++ .../src/System/Text/Json/Writer/JsonWriterHelper.cs | 5 ++++- .../src/System/Text/Json/Writer/JsonWriterOptions.cs | 5 ++++- .../System.Text.Json.Tests/JsonWriterOptionsTests.cs | 8 ++------ .../System.Text.Json.Tests/Serialization/OptionsTests.cs | 7 ++----- 6 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs index 276150ea8ffcc8..c8fd040736dbb9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs @@ -593,7 +593,7 @@ static void AddListHashCode(ref HashCode hc, ConfigurationList? static void AddHashCode(ref HashCode hc, TValue? value) { - if (typeof(TValue).IsValueType || !typeof(TValue).IsSealed) + if (typeof(TValue).IsSealed) { hc.Add(value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs index 616220b2204f9c..e7123e3a4431e2 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs @@ -756,6 +756,9 @@ public ReferenceHandler? ReferenceHandler /// Gets or sets the new line string to use when is . /// The default is the value of . /// + /// + /// Thrown when the new line string is . + /// /// /// Thrown when the new line string is not \n or \r\n. /// diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs index e47cffa1273ff8..b5dccf9423be6d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs @@ -39,7 +39,10 @@ public static void WriteIndentation(Span buffer, int indent, byte indentBy [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateNewLine(string value) { - if (value is not null && value is not JsonConstants.NewLineLineFeed and not JsonConstants.NewLineCarriageReturnLineFeed) + if (value is null) + ThrowHelper.ThrowArgumentNullException(nameof(value)); + + if (value is not JsonConstants.NewLineLineFeed and not JsonConstants.NewLineCarriageReturnLineFeed) ThrowHelper.ThrowArgumentOutOfRangeException_NewLine(nameof(value)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs index ec9452eb4fb938..2a96d748ad54ae 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterOptions.cs @@ -141,6 +141,9 @@ public bool SkipValidation /// Gets or sets the new line string to use when is . /// The default is the value of . /// + /// + /// Thrown when the new line string is . + /// /// /// Thrown when the new line string is not \n or \r\n. /// @@ -150,7 +153,7 @@ public string NewLine set { JsonWriterHelper.ValidateNewLine(value); - if (value is not null && value != Environment.NewLine) + if (value != Environment.NewLine) _optionsMask |= NewLineBit; else _optionsMask &= ~NewLineBit; diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs index c6a35147a0c74f..5c742d6294b689 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonWriterOptionsTests.cs @@ -188,14 +188,10 @@ public static void JsonWriterOptions_NewLine_InvalidNewLine(string value) } [Fact] - public static void JsonWriterOptions_NewLine_Null_Resets_To_Default() + public static void JsonWriterOptions_NewLine_Null_Throws() { var options = new JsonWriterOptions(); - - options.NewLine = "\n"; - options.NewLine = null!; - - Assert.Equal(Environment.NewLine, options.NewLine); + Assert.Throws(() => options.NewLine = null); } } } diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs index 2358bce944935c..b0c8e41f7179d0 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs @@ -561,13 +561,10 @@ public static void TestNewLineInvalid(string value) } [Fact] - public static void TestNewLineNullResetsToDefault() + public static void TestNewLineNullThrows() { var options = new JsonSerializerOptions(); - options.NewLine = "\n"; - options.NewLine = null!; - - Assert.Equal(Environment.NewLine, options.NewLine); + Assert.Throws("value", () => options.NewLine = null); } private class TestClassForEncoding