| | | 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 | | using System.Globalization; |
| | | 7 | | using System.Numerics; |
| | | 8 | | using System.Text.Json.Schema; |
| | | 9 | | |
| | | 10 | | namespace System.Text.Json.Serialization.Converters |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Converter for IEEE 754 floating-point types that share the same JSON number representation, |
| | | 14 | | /// such as <see cref="BFloat16"/> and the IEEE 754 decimal types. |
| | | 15 | | /// </summary> |
| | | 16 | | internal sealed class Ieee754FloatingPointConverter<T> : JsonPrimitiveConverter<T> |
| | | 17 | | where T : struct, IFloatingPointIeee754<T> |
| | | 18 | | { |
| | | 19 | | // Values that need more room than this are formatted into a pooled buffer. |
| | | 20 | | // Formatting of the IEEE 754 decimal types only uses scientific notation when it is |
| | | 21 | | // required or more compact, so large-magnitude values expand to many digits. |
| | | 22 | | private const int StackBufferLength = 64; |
| | | 23 | | // This buffer only ever holds one of the named literals "NaN", "Infinity" or "-Infinity", |
| | | 24 | | // so it is sized from their maximum length rather than from any numeric format length. |
| | | 25 | | private const int MaxEscapedNamedLiteralLength = JsonConstants.MaximumFloatingPointConstantLength * JsonConstant |
| | | 26 | | |
| | | 27 | | private readonly NumericType _numericType; |
| | | 28 | | |
| | 4 | 29 | | public Ieee754FloatingPointConverter(NumericType numericType) |
| | 4 | 30 | | { |
| | 4 | 31 | | _numericType = numericType; |
| | 4 | 32 | | IsInternalConverterForNumberType = true; |
| | 4 | 33 | | } |
| | | 34 | | |
| | 0 | 35 | | internal override bool IsIeeeFloatingPointConverter => true; |
| | | 36 | | |
| | | 37 | | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | 0 | 38 | | { |
| | 0 | 39 | | if (options?.NumberHandling is not null and not JsonNumberHandling.Strict) |
| | 0 | 40 | | { |
| | 0 | 41 | | return ReadNumberWithCustomHandling(ref reader, options.NumberHandling, options); |
| | | 42 | | } |
| | | 43 | | |
| | 0 | 44 | | if (reader.TokenType != JsonTokenType.Number) |
| | 0 | 45 | | { |
| | 0 | 46 | | ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(reader.TokenType); |
| | | 47 | | } |
| | | 48 | | |
| | 0 | 49 | | return ReadCore(ref reader, isStringValue: false); |
| | 0 | 50 | | } |
| | | 51 | | |
| | | 52 | | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) |
| | 0 | 53 | | { |
| | 0 | 54 | | if (options?.NumberHandling is not null and not JsonNumberHandling.Strict) |
| | 0 | 55 | | { |
| | 0 | 56 | | WriteNumberWithCustomHandling(writer, value, options.NumberHandling); |
| | 0 | 57 | | return; |
| | | 58 | | } |
| | | 59 | | |
| | 0 | 60 | | WriteCore(writer, value); |
| | 0 | 61 | | } |
| | | 62 | | |
| | | 63 | | internal override T ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions |
| | 0 | 64 | | { |
| | 0 | 65 | | Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); |
| | 0 | 66 | | return ReadCore(ref reader, isStringValue: true); |
| | 0 | 67 | | } |
| | | 68 | | |
| | | 69 | | internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, T value, JsonSerializerOptions options, bo |
| | 0 | 70 | | { |
| | 0 | 71 | | ValidateFinite(value); |
| | | 72 | | |
| | 0 | 73 | | Span<byte> stackBuffer = stackalloc byte[StackBufferLength]; |
| | 0 | 74 | | byte[]? rented = Format(value, stackBuffer, out ReadOnlySpan<byte> formatted); |
| | 0 | 75 | | writer.WritePropertyName(formatted); |
| | 0 | 76 | | Return(rented); |
| | 0 | 77 | | } |
| | | 78 | | |
| | | 79 | | internal override T ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSer |
| | 0 | 80 | | { |
| | 0 | 81 | | if (reader.TokenType == JsonTokenType.String) |
| | 0 | 82 | | { |
| | 0 | 83 | | if ((JsonNumberHandling.AllowReadingFromString & handling) != 0) |
| | 0 | 84 | | { |
| | 0 | 85 | | if (TryGetFloatingPointConstant(ref reader, out T value)) |
| | 0 | 86 | | { |
| | 0 | 87 | | return value; |
| | | 88 | | } |
| | | 89 | | |
| | 0 | 90 | | return ReadCore(ref reader, isStringValue: true); |
| | | 91 | | } |
| | 0 | 92 | | else if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != 0) |
| | 0 | 93 | | { |
| | 0 | 94 | | if (!TryGetFloatingPointConstant(ref reader, out T value)) |
| | 0 | 95 | | { |
| | 0 | 96 | | ThrowHelper.ThrowFormatException(_numericType); |
| | | 97 | | } |
| | | 98 | | |
| | 0 | 99 | | return value; |
| | | 100 | | } |
| | 0 | 101 | | } |
| | | 102 | | |
| | 0 | 103 | | if (reader.TokenType != JsonTokenType.Number) |
| | 0 | 104 | | { |
| | 0 | 105 | | ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(reader.TokenType); |
| | | 106 | | } |
| | | 107 | | |
| | 0 | 108 | | return ReadCore(ref reader, isStringValue: false); |
| | 0 | 109 | | } |
| | | 110 | | |
| | | 111 | | internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, T value, JsonNumberHandling handling |
| | 0 | 112 | | { |
| | 0 | 113 | | if ((JsonNumberHandling.WriteAsString & handling) != 0) |
| | 0 | 114 | | { |
| | 0 | 115 | | Span<byte> stackBuffer = stackalloc byte[StackBufferLength]; |
| | 0 | 116 | | byte[]? rented = Format(value, stackBuffer, out ReadOnlySpan<byte> formatted); |
| | 0 | 117 | | writer.WriteNumberValueAsStringUnescaped(formatted); |
| | 0 | 118 | | Return(rented); |
| | 0 | 119 | | } |
| | 0 | 120 | | else if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != 0) |
| | 0 | 121 | | { |
| | 0 | 122 | | WriteFloatingPointConstant(writer, value); |
| | 0 | 123 | | } |
| | | 124 | | else |
| | 0 | 125 | | { |
| | 0 | 126 | | WriteCore(writer, value); |
| | 0 | 127 | | } |
| | 0 | 128 | | } |
| | | 129 | | |
| | | 130 | | internal override JsonSchema? GetSchema(JsonNumberHandling numberHandling) => |
| | 0 | 131 | | GetSchemaForNumericType(JsonSchemaType.Number, numberHandling, isIeeeFloatingPoint: true); |
| | | 132 | | |
| | | 133 | | internal override JsonValueType GetSupportedJsonValueTypes(JsonNumberHandling numberHandling) => |
| | 0 | 134 | | GetSupportedJsonValueTypesForNumericType(numberHandling); |
| | | 135 | | |
| | | 136 | | // Reads the current token as a number. When the token is a string or property name, |
| | | 137 | | // non-finite results are rejected: the underlying parsers accept named literals such as "naN" |
| | | 138 | | // that are not valid JSON, and a string that overflows to infinity is rejected for consistency |
| | | 139 | | // with float and double. Number tokens are already constrained to the JSON number grammar by |
| | | 140 | | // the reader, so they are permitted to overflow to infinity per IEEE 754. |
| | | 141 | | private T ReadCore(ref Utf8JsonReader reader, bool isStringValue) |
| | 0 | 142 | | { |
| | 0 | 143 | | byte[]? rentedByteBuffer = null; |
| | 0 | 144 | | int bufferLength = reader.ValueLength; |
| | | 145 | | |
| | 0 | 146 | | Span<byte> byteBuffer = bufferLength <= JsonConstants.StackallocByteThreshold |
| | 0 | 147 | | ? stackalloc byte[JsonConstants.StackallocByteThreshold] |
| | 0 | 148 | | : (rentedByteBuffer = ArrayPool<byte>.Shared.Rent(bufferLength)); |
| | | 149 | | |
| | 0 | 150 | | int written = reader.CopyValue(byteBuffer); |
| | 0 | 151 | | byteBuffer = byteBuffer.Slice(0, written); |
| | | 152 | | |
| | 0 | 153 | | bool success = TryParse(byteBuffer, out T result) && (!isStringValue || T.IsFinite(result)); |
| | 0 | 154 | | Return(rentedByteBuffer); |
| | | 155 | | |
| | 0 | 156 | | if (!success) |
| | 0 | 157 | | { |
| | 0 | 158 | | ThrowHelper.ThrowFormatException(_numericType); |
| | | 159 | | } |
| | | 160 | | |
| | 0 | 161 | | return result; |
| | 0 | 162 | | } |
| | | 163 | | |
| | | 164 | | private static void WriteCore(Utf8JsonWriter writer, T value) |
| | 0 | 165 | | { |
| | 0 | 166 | | ValidateFinite(value); |
| | | 167 | | |
| | 0 | 168 | | Span<byte> stackBuffer = stackalloc byte[StackBufferLength]; |
| | 0 | 169 | | byte[]? rented = Format(value, stackBuffer, out ReadOnlySpan<byte> formatted); |
| | 0 | 170 | | writer.WriteRawValue(formatted); |
| | 0 | 171 | | Return(rented); |
| | 0 | 172 | | } |
| | | 173 | | |
| | | 174 | | // NaN and infinity have no representation in the JSON number grammar. Reject them with the |
| | | 175 | | // same error Utf8JsonWriter reports for float and double, which points callers at |
| | | 176 | | // JsonNumberHandling.AllowNamedFloatingPointLiterals. |
| | | 177 | | private static void ValidateFinite(T value) |
| | 0 | 178 | | { |
| | 0 | 179 | | if (!T.IsFinite(value)) |
| | 0 | 180 | | { |
| | 0 | 181 | | ThrowHelper.ThrowArgumentException_ValueNotSupported(); |
| | | 182 | | } |
| | 0 | 183 | | } |
| | | 184 | | |
| | | 185 | | private static void WriteFloatingPointConstant(Utf8JsonWriter writer, T value) |
| | 0 | 186 | | { |
| | 0 | 187 | | if (T.IsNaN(value)) |
| | 0 | 188 | | { |
| | 0 | 189 | | writer.WriteNumberValueAsStringUnescaped(JsonConstants.NaNValue); |
| | 0 | 190 | | } |
| | 0 | 191 | | else if (T.IsPositiveInfinity(value)) |
| | 0 | 192 | | { |
| | 0 | 193 | | writer.WriteNumberValueAsStringUnescaped(JsonConstants.PositiveInfinityValue); |
| | 0 | 194 | | } |
| | 0 | 195 | | else if (T.IsNegativeInfinity(value)) |
| | 0 | 196 | | { |
| | 0 | 197 | | writer.WriteNumberValueAsStringUnescaped(JsonConstants.NegativeInfinityValue); |
| | 0 | 198 | | } |
| | | 199 | | else |
| | 0 | 200 | | { |
| | 0 | 201 | | WriteCore(writer, value); |
| | 0 | 202 | | } |
| | 0 | 203 | | } |
| | | 204 | | |
| | | 205 | | private static bool TryGetFloatingPointConstant(ref Utf8JsonReader reader, out T value) |
| | 0 | 206 | | { |
| | | 207 | | scoped Span<byte> buffer; |
| | | 208 | | |
| | 0 | 209 | | if (reader.ValueIsEscaped) |
| | 0 | 210 | | { |
| | 0 | 211 | | if (reader.ValueLength > MaxEscapedNamedLiteralLength) |
| | 0 | 212 | | { |
| | 0 | 213 | | value = default; |
| | 0 | 214 | | return false; |
| | | 215 | | } |
| | | 216 | | |
| | 0 | 217 | | buffer = stackalloc byte[MaxEscapedNamedLiteralLength]; |
| | 0 | 218 | | } |
| | | 219 | | else |
| | 0 | 220 | | { |
| | 0 | 221 | | if (reader.ValueLength > JsonConstants.MaximumFloatingPointConstantLength) |
| | 0 | 222 | | { |
| | 0 | 223 | | value = default; |
| | 0 | 224 | | return false; |
| | | 225 | | } |
| | | 226 | | |
| | 0 | 227 | | buffer = stackalloc byte[JsonConstants.MaximumFloatingPointConstantLength]; |
| | 0 | 228 | | } |
| | | 229 | | |
| | 0 | 230 | | int written = reader.CopyValue(buffer); |
| | 0 | 231 | | return TryGetFloatingPointConstant(buffer.Slice(0, written), out value); |
| | 0 | 232 | | } |
| | | 233 | | |
| | | 234 | | private static bool TryGetFloatingPointConstant(ReadOnlySpan<byte> span, out T value) |
| | 0 | 235 | | { |
| | 0 | 236 | | if (span.SequenceEqual(JsonConstants.NaNValue)) |
| | 0 | 237 | | { |
| | 0 | 238 | | value = T.NaN; |
| | 0 | 239 | | return true; |
| | | 240 | | } |
| | | 241 | | |
| | 0 | 242 | | if (span.SequenceEqual(JsonConstants.PositiveInfinityValue)) |
| | 0 | 243 | | { |
| | 0 | 244 | | value = T.PositiveInfinity; |
| | 0 | 245 | | return true; |
| | | 246 | | } |
| | | 247 | | |
| | 0 | 248 | | if (span.SequenceEqual(JsonConstants.NegativeInfinityValue)) |
| | 0 | 249 | | { |
| | 0 | 250 | | value = T.NegativeInfinity; |
| | 0 | 251 | | return true; |
| | | 252 | | } |
| | | 253 | | |
| | 0 | 254 | | value = default; |
| | 0 | 255 | | return false; |
| | 0 | 256 | | } |
| | | 257 | | |
| | | 258 | | private static bool TryParse(ReadOnlySpan<byte> buffer, out T result) => |
| | 0 | 259 | | T.TryParse(buffer, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out resul |
| | | 260 | | |
| | | 261 | | // Formats value into initialBuffer, growing into a pooled buffer if necessary. |
| | | 262 | | // Returns the rented array, if any, which the caller must return. |
| | | 263 | | private static byte[]? Format(T value, Span<byte> initialBuffer, out ReadOnlySpan<byte> formatted) |
| | 0 | 264 | | { |
| | 0 | 265 | | byte[]? rented = null; |
| | 0 | 266 | | Span<byte> destination = initialBuffer; |
| | | 267 | | int written; |
| | | 268 | | |
| | 0 | 269 | | while (!value.TryFormat(destination, out written, format: default, provider: CultureInfo.InvariantCulture)) |
| | 0 | 270 | | { |
| | 0 | 271 | | byte[]? toReturn = rented; |
| | 0 | 272 | | rented = ArrayPool<byte>.Shared.Rent(destination.Length * 2); |
| | 0 | 273 | | destination = rented; |
| | 0 | 274 | | Return(toReturn); |
| | 0 | 275 | | } |
| | | 276 | | |
| | 0 | 277 | | formatted = destination.Slice(0, written); |
| | 0 | 278 | | return rented; |
| | 0 | 279 | | } |
| | | 280 | | |
| | | 281 | | private static void Return(byte[]? rented) |
| | 0 | 282 | | { |
| | 0 | 283 | | if (rented is not null) |
| | 0 | 284 | | { |
| | 0 | 285 | | ArrayPool<byte>.Shared.Return(rented); |
| | 0 | 286 | | } |
| | 0 | 287 | | } |
| | | 288 | | } |
| | | 289 | | } |
| | | 290 | | |