|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Buffers; |
| 5 | +using System.Diagnostics; |
| 6 | + |
| 7 | +namespace System.Text.Json |
| 8 | +{ |
| 9 | + public sealed partial class Utf8JsonWriter |
| 10 | + { |
| 11 | + /// <summary> |
| 12 | + /// Writes the input as JSON content. It is expected that the input content is a single complete JSON value. |
| 13 | + /// </summary> |
| 14 | + /// <param name="json">The raw JSON content to write.</param> |
| 15 | + /// <param name="skipInputValidation">Whether to validate if the input is an RFC 8259-compliant JSON payload.</param> |
| 16 | + /// <exception cref="ArgumentNullException">Thrown if <paramref name="json"/> is <see langword="null"/>.</exception> |
| 17 | + /// <exception cref="ArgumentException">Thrown if the length of the input is zero or greater than 715,827,882 (<see cref="int.MaxValue"/> / 3).</exception> |
| 18 | + /// <exception cref="JsonException"> |
| 19 | + /// Thrown if <paramref name="skipInputValidation"/> is <see langword="false"/>, and the input |
| 20 | + /// is not a valid, complete, single JSON value according to the JSON RFC (https://tools.ietf.org/html/rfc8259) |
| 21 | + /// or the input JSON exceeds a recursive depth of 64. |
| 22 | + /// </exception> |
| 23 | + /// <remarks> |
| 24 | + /// When writing untrused JSON values, do not set <paramref name="skipInputValidation"/> to <see langword="true"/> as this can result in invalid JSON |
| 25 | + /// being written, and/or the overall payload being written to the writer instance being invalid. |
| 26 | + /// |
| 27 | + /// When using this method, the input content will be written to the writer destination as-is, unless validation fails (when it is enabled). |
| 28 | + /// |
| 29 | + /// The <see cref="JsonWriterOptions.SkipValidation"/> value for the writer instance is honored when using this method. |
| 30 | + /// |
| 31 | + /// The <see cref="JsonWriterOptions.Indented"/> and <see cref="JsonWriterOptions.Encoder"/> values for the writer instance are not applied when using this method. |
| 32 | + /// </remarks> |
| 33 | + public void WriteRawValue(string json, bool skipInputValidation = false) |
| 34 | + { |
| 35 | + if (!_options.SkipValidation) |
| 36 | + { |
| 37 | + ValidateWritingValue(); |
| 38 | + } |
| 39 | + |
| 40 | + if (json == null) |
| 41 | + { |
| 42 | + throw new ArgumentNullException(nameof(json)); |
| 43 | + } |
| 44 | + |
| 45 | + TranscodeAndWriteRawValue(json.AsSpan(), skipInputValidation); |
| 46 | + } |
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// Writes the input as JSON content. It is expected that the input content is a single complete JSON value. |
| 50 | + /// </summary> |
| 51 | + /// <param name="json">The raw JSON content to write.</param> |
| 52 | + /// <param name="skipInputValidation">Whether to validate if the input is an RFC 8259-compliant JSON payload.</param> |
| 53 | + /// <exception cref="ArgumentException">Thrown if the length of the input is zero or greater than 715,827,882 (<see cref="int.MaxValue"/> / 3).</exception> |
| 54 | + /// <exception cref="JsonException"> |
| 55 | + /// Thrown if <paramref name="skipInputValidation"/> is <see langword="false"/>, and the input |
| 56 | + /// is not a valid, complete, single JSON value according to the JSON RFC (https://tools.ietf.org/html/rfc8259) |
| 57 | + /// or the input JSON exceeds a recursive depth of 64. |
| 58 | + /// </exception> |
| 59 | + /// <remarks> |
| 60 | + /// When writing untrused JSON values, do not set <paramref name="skipInputValidation"/> to <see langword="true"/> as this can result in invalid JSON |
| 61 | + /// being written, and/or the overall payload being written to the writer instance being invalid. |
| 62 | + /// |
| 63 | + /// When using this method, the input content will be written to the writer destination as-is, unless validation fails (when it is enabled). |
| 64 | + /// |
| 65 | + /// The <see cref="JsonWriterOptions.SkipValidation"/> value for the writer instance is honored when using this method. |
| 66 | + /// |
| 67 | + /// The <see cref="JsonWriterOptions.Indented"/> and <see cref="JsonWriterOptions.Encoder"/> values for the writer instance are not applied when using this method. |
| 68 | + /// </remarks> |
| 69 | + public void WriteRawValue(ReadOnlySpan<char> json, bool skipInputValidation = false) |
| 70 | + { |
| 71 | + if (!_options.SkipValidation) |
| 72 | + { |
| 73 | + ValidateWritingValue(); |
| 74 | + } |
| 75 | + |
| 76 | + TranscodeAndWriteRawValue(json, skipInputValidation); |
| 77 | + } |
| 78 | + |
| 79 | + /// <summary> |
| 80 | + /// Writes the input as JSON content. It is expected that the input content is a single complete JSON value. |
| 81 | + /// </summary> |
| 82 | + /// <param name="utf8Json">The raw JSON content to write.</param> |
| 83 | + /// <param name="skipInputValidation">Whether to validate if the input is an RFC 8259-compliant JSON payload.</param> |
| 84 | + /// <exception cref="ArgumentException">Thrown if the length of the input is zero or equal to <see cref="int.MaxValue"/>.</exception> |
| 85 | + /// <exception cref="JsonException"> |
| 86 | + /// Thrown if <paramref name="skipInputValidation"/> is <see langword="false"/>, and the input |
| 87 | + /// is not a valid, complete, single JSON value according to the JSON RFC (https://tools.ietf.org/html/rfc8259) |
| 88 | + /// or the input JSON exceeds a recursive depth of 64. |
| 89 | + /// </exception> |
| 90 | + /// <remarks> |
| 91 | + /// When writing untrused JSON values, do not set <paramref name="skipInputValidation"/> to <see langword="true"/> as this can result in invalid JSON |
| 92 | + /// being written, and/or the overall payload being written to the writer instance being invalid. |
| 93 | + /// |
| 94 | + /// When using this method, the input content will be written to the writer destination as-is, unless validation fails (when it is enabled). |
| 95 | + /// |
| 96 | + /// The <see cref="JsonWriterOptions.SkipValidation"/> value for the writer instance is honored when using this method. |
| 97 | + /// |
| 98 | + /// The <see cref="JsonWriterOptions.Indented"/> and <see cref="JsonWriterOptions.Encoder"/> values for the writer instance are not applied when using this method. |
| 99 | + /// </remarks> |
| 100 | + public void WriteRawValue(ReadOnlySpan<byte> utf8Json, bool skipInputValidation = false) |
| 101 | + { |
| 102 | + if (!_options.SkipValidation) |
| 103 | + { |
| 104 | + ValidateWritingValue(); |
| 105 | + } |
| 106 | + |
| 107 | + if (utf8Json.Length == int.MaxValue) |
| 108 | + { |
| 109 | + ThrowHelper.ThrowArgumentException_ValueTooLarge(int.MaxValue); |
| 110 | + } |
| 111 | + |
| 112 | + WriteRawValueCore(utf8Json, skipInputValidation); |
| 113 | + } |
| 114 | + |
| 115 | + private void TranscodeAndWriteRawValue(ReadOnlySpan<char> json, bool skipInputValidation) |
| 116 | + { |
| 117 | + if (json.Length > JsonConstants.MaxUtf16RawValueLength) |
| 118 | + { |
| 119 | + ThrowHelper.ThrowArgumentException_ValueTooLarge(json.Length); |
| 120 | + } |
| 121 | + |
| 122 | + byte[]? tempArray = null; |
| 123 | + |
| 124 | + // For performance, avoid obtaining actual byte count unless memory usage is higher than the threshold. |
| 125 | + Span<byte> utf8Json = json.Length <= (JsonConstants.ArrayPoolMaxSizeBeforeUsingNormalAlloc / JsonConstants.MaxExpansionFactorWhileTranscoding) ? |
| 126 | + // Use a pooled alloc. |
| 127 | + tempArray = ArrayPool<byte>.Shared.Rent(json.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) : |
| 128 | + // Use a normal alloc since the pool would create a normal alloc anyway based on the threshold (per current implementation) |
| 129 | + // and by using a normal alloc we can avoid the Clear(). |
| 130 | + new byte[JsonReaderHelper.GetUtf8ByteCount(json)]; |
| 131 | + |
| 132 | + try |
| 133 | + { |
| 134 | + int actualByteCount = JsonReaderHelper.GetUtf8FromText(json, utf8Json); |
| 135 | + utf8Json = utf8Json.Slice(0, actualByteCount); |
| 136 | + WriteRawValueCore(utf8Json, skipInputValidation); |
| 137 | + } |
| 138 | + finally |
| 139 | + { |
| 140 | + if (tempArray != null) |
| 141 | + { |
| 142 | + utf8Json.Clear(); |
| 143 | + ArrayPool<byte>.Shared.Return(tempArray); |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + private void WriteRawValueCore(ReadOnlySpan<byte> utf8Json, bool skipInputValidation) |
| 149 | + { |
| 150 | + int len = utf8Json.Length; |
| 151 | + |
| 152 | + if (len == 0) |
| 153 | + { |
| 154 | + ThrowHelper.ThrowArgumentException(SR.ExpectedJsonTokens); |
| 155 | + } |
| 156 | + |
| 157 | + // In the UTF-16-based entry point methods above, we validate that the payload length <= int.MaxValue /3. |
| 158 | + // The result of this division will be rounded down, so even if every input character needs to be transcoded |
| 159 | + // (with expansion factor of 3), the resulting payload would be less than int.MaxValue, |
| 160 | + // as (int.MaxValue/3) * 3 is less than int.MaxValue. |
| 161 | + Debug.Assert(len < int.MaxValue); |
| 162 | + |
| 163 | + if (skipInputValidation) |
| 164 | + { |
| 165 | + // Treat all unvalidated raw JSON value writes as string. If the payload is valid, this approach does |
| 166 | + // not affect structural validation since a string token is equivalent to a complete object, array, |
| 167 | + // or other complete JSON tokens when considering structural validation on subsequent writer calls. |
| 168 | + // If the payload is not valid, then we make no guarantees about the structural validation of the final payload. |
| 169 | + _tokenType = JsonTokenType.String; |
| 170 | + } |
| 171 | + else |
| 172 | + { |
| 173 | + // Utilize reader validation. |
| 174 | + Utf8JsonReader reader = new(utf8Json); |
| 175 | + while (reader.Read()); |
| 176 | + _tokenType = reader.TokenType; |
| 177 | + } |
| 178 | + |
| 179 | + // TODO (https://github.com/dotnet/runtime/issues/29293): |
| 180 | + // investigate writing this in chunks, rather than requesting one potentially long, contiguous buffer. |
| 181 | + int maxRequired = len + 1; // Optionally, 1 list separator. We've guarded against integer overflow earlier in the call stack. |
| 182 | + |
| 183 | + if (_memory.Length - BytesPending < maxRequired) |
| 184 | + { |
| 185 | + Grow(maxRequired); |
| 186 | + } |
| 187 | + |
| 188 | + Span<byte> output = _memory.Span; |
| 189 | + |
| 190 | + if (_currentDepth < 0) |
| 191 | + { |
| 192 | + output[BytesPending++] = JsonConstants.ListSeparator; |
| 193 | + } |
| 194 | + |
| 195 | + utf8Json.CopyTo(output.Slice(BytesPending)); |
| 196 | + BytesPending += len; |
| 197 | + |
| 198 | + SetFlagToAddListSeparatorBeforeNextItem(); |
| 199 | + } |
| 200 | + } |
| 201 | +} |
0 commit comments