< Summary

Information
Class: Chronicler.Serialization.StateJsonConverter<T1, T2>
Assembly: Chronicler
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/Json/StateJsonConverter.cs
Line coverage
100%
Covered lines: 35
Uncovered lines: 0
Coverable lines: 35
Total lines: 104
Line coverage: 100%
Branch coverage
100%
Covered branches: 20
Total branches: 20
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%22100%
Read(...)100%11100%
EnsureStartObject(...)100%22100%
ReadStateProperty(...)100%66100%
ReadStateValue(...)100%44100%
EnsureEndObject(...)100%44100%
Write(...)100%22100%

File(s)

/home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/Json/StateJsonConverter.cs

#LineLine coverage
 1//=======================================================================
 2// StateJsonConverter.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2024-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System;
 9using System.Text.Json;
 10using System.Text.Json.Serialization;
 11
 12namespace Chronicler.Serialization;
 13
 14/// <summary>
 15/// Serializes and deserializes an object through its canonical state value.
 16/// </summary>
 17/// <typeparam name="TRecord">The state-backed record type.</typeparam>
 18/// <typeparam name="TState">The serializable state type.</typeparam>
 19public sealed class StateJsonConverter<TRecord, TState> : JsonConverter<TRecord>
 20    where TRecord : class, IStateBacked<TState>
 21{
 22    private const string StatePropertyName = "State";
 23
 24    private readonly Func<TState, TRecord> _factory;
 25
 26    /// <summary>Creates a converter that reconstructs records from their state.</summary>
 27    /// <param name="factory">The retained callback that reconstructs a record from a deserialized state value.</param>
 28    /// <exception cref="ArgumentNullException"><paramref name="factory"/> is null.</exception>
 1129    public StateJsonConverter(Func<TState, TRecord> factory)
 30    {
 1131        _factory = factory ?? throw new ArgumentNullException(nameof(factory));
 1032    }
 33
 34    /// <summary>Reads a state object and reconstructs the record.</summary>
 35    /// <param name="reader">A reader at the start of the object. On success, it is positioned on the closing object tok
 36    /// <param name="typeToConvert">The requested record type, used in shape errors.</param>
 37    /// <param name="options">The serializer options used to decode the nested state.</param>
 38    /// <returns>The result of invoking the factory with the decoded state.</returns>
 39    /// <exception cref="JsonException">The object does not contain exactly one case-sensitive <c>State</c> property, or
 40    public override TRecord Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
 41    {
 942        EnsureStartObject(reader.TokenType, typeToConvert);
 843        ReadStateProperty(ref reader, typeToConvert);
 544        TState state = ReadStateValue(ref reader, typeToConvert, options);
 345        EnsureEndObject(ref reader, typeToConvert);
 46
 147        return _factory(state);
 48    }
 49
 50    private static void EnsureStartObject(JsonTokenType tokenType, Type typeToConvert)
 51    {
 952        if (tokenType != JsonTokenType.StartObject)
 153            throw new JsonException($"Expected JSON object for state-backed type '{typeToConvert}'.");
 854    }
 55
 56    private static void ReadStateProperty(ref Utf8JsonReader reader, Type typeToConvert)
 57    {
 858        if (!reader.Read())
 159            throw new JsonException($"Expected '{StatePropertyName}' property for state-backed type '{typeToConvert}'.")
 760        if (reader.TokenType != JsonTokenType.PropertyName || !reader.ValueTextEquals(StatePropertyName))
 261            throw new JsonException($"Expected '{StatePropertyName}' property for state-backed type '{typeToConvert}'.")
 562    }
 63
 64    private static TState ReadStateValue(
 65        ref Utf8JsonReader reader,
 66        Type typeToConvert,
 67        JsonSerializerOptions options)
 68    {
 569        if (!reader.Read())
 170            throw new JsonException($"Expected '{StatePropertyName}' value for state-backed type '{typeToConvert}'.");
 71
 472        TState? state = JsonSerializer.Deserialize<TState>(ref reader, options);
 473        if (state == null)
 174            throw new JsonException($"Unable to deserialize '{StatePropertyName}' for state-backed type '{typeToConvert}
 75
 376        return state;
 77    }
 78
 79    private static void EnsureEndObject(ref Utf8JsonReader reader, Type typeToConvert)
 80    {
 381        if (!reader.Read())
 182            throw new JsonException($"Expected end of JSON object for state-backed type '{typeToConvert}'.");
 283        if (reader.TokenType != JsonTokenType.EndObject)
 184            throw new JsonException($"Expected end of JSON object for state-backed type '{typeToConvert}'.");
 185    }
 86
 87    /// <summary>Writes the record as an object with one <c>State</c> property.</summary>
 88    /// <param name="writer">The caller's JSON writer. Appends one value at its current position.</param>
 89    /// <param name="value">The object whose state is written. A null record writes a JSON null.</param>
 90    /// <param name="options">The serializer options used to encode the nested state.</param>
 91    public override void Write(Utf8JsonWriter writer, TRecord value, JsonSerializerOptions options)
 92    {
 293        if (value == null)
 94        {
 195            writer.WriteNullValue();
 196            return;
 97        }
 98
 199        writer.WriteStartObject();
 1100        writer.WritePropertyName(StatePropertyName);
 1101        JsonSerializer.Serialize(writer, value.State, options);
 1102        writer.WriteEndObject();
 1103    }
 104}