| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Diagnostics; |
| | 6 | | using System.Text.Json; |
| | 7 | | using System.Text.Json.Serialization; |
| | 8 | | using Azure.Core; |
| | 9 | |
|
| | 10 | | namespace Azure.Search.Documents |
| | 11 | | { |
| | 12 | | /// <summary> |
| | 13 | | /// Convert doubles to and from JSON. Search allows INF, -INF, and NaN as |
| | 14 | | /// string values. |
| | 15 | | /// </summary> |
| | 16 | | internal class SearchDoubleConverter : JsonConverter<double> |
| | 17 | | { |
| 1 | 18 | | public static SearchDoubleConverter Shared { get; } = |
| 1 | 19 | | new SearchDoubleConverter(); |
| | 20 | |
|
| | 21 | | public override double Read( |
| | 22 | | ref Utf8JsonReader reader, |
| | 23 | | Type typeToConvert, |
| | 24 | | JsonSerializerOptions options) |
| | 25 | | { |
| | 26 | | Debug.Assert(typeToConvert != null); |
| | 27 | | Debug.Assert(options != null); |
| | 28 | |
|
| 82 | 29 | | if (reader.TokenType == JsonTokenType.String) |
| | 30 | | { |
| 6 | 31 | | switch (reader.GetString()) |
| | 32 | | { |
| | 33 | | case Constants.InfValue: |
| 2 | 34 | | return double.PositiveInfinity; |
| | 35 | | case Constants.NegativeInfValue: |
| 2 | 36 | | return double.NegativeInfinity; |
| | 37 | | case Constants.NanValue: |
| 2 | 38 | | return double.NaN; |
| | 39 | | default: |
| 0 | 40 | | throw new JsonException(); |
| | 41 | | } |
| | 42 | | } |
| 76 | 43 | | return reader.GetDouble(); |
| | 44 | | } |
| | 45 | |
|
| | 46 | | public override void Write( |
| | 47 | | Utf8JsonWriter writer, |
| | 48 | | double value, |
| | 49 | | JsonSerializerOptions options) |
| | 50 | | { |
| 70 | 51 | | Argument.AssertNotNull(writer, nameof(writer)); |
| | 52 | | Debug.Assert(options != null); |
| | 53 | |
|
| 70 | 54 | | if (double.IsPositiveInfinity(value)) |
| | 55 | | { |
| 2 | 56 | | writer.WriteStringValue(Constants.InfValue); |
| | 57 | | } |
| 68 | 58 | | else if (double.IsNegativeInfinity(value)) |
| | 59 | | { |
| 2 | 60 | | writer.WriteStringValue(Constants.NegativeInfValue); |
| | 61 | | } |
| 66 | 62 | | else if (double.IsNaN(value)) |
| | 63 | | { |
| 8 | 64 | | writer.WriteStringValue(Constants.NanValue); |
| | 65 | | } |
| | 66 | | else |
| | 67 | | { |
| 58 | 68 | | writer.WriteNumberValue(value); |
| | 69 | | } |
| 58 | 70 | | } |
| | 71 | | } |
| | 72 | | } |