| | | 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.Collections.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Text.Json.Serialization; |
| | | 7 | | |
| | | 8 | | namespace System.Text.Json.Nodes |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// A JsonValue encapsulating a primitive value using a built-in converter for the type. |
| | | 12 | | /// </summary> |
| | | 13 | | internal sealed class JsonValuePrimitive<TValue> : JsonValue<TValue> |
| | | 14 | | { |
| | | 15 | | private readonly JsonConverter<TValue> _converter; |
| | | 16 | | private readonly JsonValueKind _valueKind; |
| | | 17 | | |
| | 0 | 18 | | public JsonValuePrimitive(TValue value, JsonConverter<TValue> converter, JsonNodeOptions? options) : base(value, |
| | 0 | 19 | | { |
| | 0 | 20 | | Debug.Assert(TypeIsSupportedPrimitive, $"The type {typeof(TValue)} is not a supported primitive."); |
| | 0 | 21 | | Debug.Assert(converter is { IsInternalConverter: true, ConverterStrategy: ConverterStrategy.Value }); |
| | | 22 | | |
| | 0 | 23 | | _converter = converter; |
| | 0 | 24 | | _valueKind = DetermineValueKind(value); |
| | 0 | 25 | | } |
| | | 26 | | |
| | 0 | 27 | | private protected override JsonValueKind GetValueKindCore() => _valueKind; |
| | 0 | 28 | | internal override JsonNode DeepCloneCore() => new JsonValuePrimitive<TValue>(Value, _converter, Options); |
| | | 29 | | |
| | | 30 | | internal override bool DeepEqualsCore(JsonNode otherNode) |
| | 0 | 31 | | { |
| | 0 | 32 | | if (otherNode is JsonValue otherValue && otherValue.TryGetValue(out TValue? v)) |
| | 0 | 33 | | { |
| | | 34 | | // Because TValue is equatable and otherNode returns a matching |
| | | 35 | | // type we can short circuit the comparison in this case. |
| | 0 | 36 | | return EqualityComparer<TValue>.Default.Equals(Value, v); |
| | | 37 | | } |
| | | 38 | | |
| | 0 | 39 | | return base.DeepEqualsCore(otherNode); |
| | 0 | 40 | | } |
| | | 41 | | |
| | | 42 | | public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) |
| | 0 | 43 | | { |
| | 0 | 44 | | ArgumentNullException.ThrowIfNull(writer); |
| | | 45 | | |
| | 0 | 46 | | JsonConverter<TValue> converter = _converter; |
| | 0 | 47 | | options ??= s_defaultOptions; |
| | | 48 | | |
| | 0 | 49 | | if (converter.IsInternalConverterForNumberType) |
| | 0 | 50 | | { |
| | 0 | 51 | | converter.WriteNumberWithCustomHandling(writer, Value, options.NumberHandling); |
| | 0 | 52 | | } |
| | | 53 | | else |
| | 0 | 54 | | { |
| | 0 | 55 | | converter.Write(writer, Value, options); |
| | 0 | 56 | | } |
| | 0 | 57 | | } |
| | | 58 | | } |
| | | 59 | | } |