< Summary

Information
Class: Chronicler.Serialization.MemoryPackRecordSerializer
Assembly: Chronicler
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/MemoryPack/MemoryPackRecordSerializer.cs
Line coverage
100%
Covered lines: 140
Uncovered lines: 0
Coverable lines: 140
Total lines: 341
Line coverage: 100%
Branch coverage
100%
Covered branches: 66
Total branches: 66
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
Serialize(...)100%11100%
Serialize(...)100%44100%
Populate(...)100%11100%
Populate(...)100%22100%
Populate(...)100%11100%
Populate(...)100%66100%
.ctor(...)100%11100%
get_Mode()100%11100%
LookValue(...)100%44100%
LookDeep(...)100%22100%
LookDeepStruct(...)100%11100%
LookNullableDeep(...)100%22100%
LookLink(...)100%44100%
ToArray()100%11100%
.ctor(...)100%22100%
get_Mode()100%11100%
LookValue(...)100%66100%
LookDeep(...)100%66100%
LookDeepStruct(...)100%44100%
LookNullableDeep(...)100%44100%
LookLink(...)100%66100%
TryReadLinkId(...)100%44100%
LoadDeferredLink(...)100%44100%
LoadImmediateLink(...)100%44100%
CreateDefaultDeepStruct()100%11100%
FormatSlot(...)100%22100%

File(s)

/home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/MemoryPack/MemoryPackRecordSerializer.cs

#LineLine coverage
 1//=======================================================================
 2// MemoryPackRecordSerializer.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
 8#if !CHRONICLER_DISABLE_MEMORYPACK
 9
 10using System;
 11using System.Collections.Generic;
 12using System.Diagnostics.CodeAnalysis;
 13using MemoryPack;
 14
 15namespace Chronicler.Serialization;
 16
 17/// <summary>
 18/// Saves recorded state as MemoryPack bytes and restores it into host-created objects.
 19/// </summary>
 20/// <remarks>Each call made without a session context creates one with an empty link registry.</remarks>
 21public static class MemoryPackRecordSerializer
 22{
 123    private static readonly byte[] EmptyRecordBytes = MemoryPackSerializer.Serialize(new MemoryPackRecordEnvelope());
 24
 25    /// <inheritdoc cref="Serialize(IRecordable, ChronicleContext)"/>
 26    public static byte[] Serialize(IRecordable target)
 727        => Serialize(target, context: null);
 28
 29    /// <summary>
 30    /// Saves the state declared by a recordable instance.
 31    /// </summary>
 32    /// <param name="target">The source whose schema runs in <see cref="SerializationMode.Saving"/> mode.</param>
 33    /// <param name="context">The session that supplies stable link IDs. Null creates a fresh context.</param>
 34    /// <returns>The recorded payload in a new byte array owned by the caller.</returns>
 35    /// <exception cref="ArgumentNullException"><paramref name="target"/> is null.</exception>
 36    /// <exception cref="InvalidOperationException">A non-null recorded link has no stable ID.</exception>
 37    public static byte[] Serialize(IRecordable target, ChronicleContext? context)
 38    {
 7839        if (target == null)
 140            throw new ArgumentNullException(nameof(target));
 41
 7742        context ??= new ChronicleContext();
 43
 7744        var chronicler = new MemoryPackRecordWriter(context);
 7745        target.RecordData(chronicler);
 7546        return chronicler.ToArray();
 47    }
 48
 49    /// <inheritdoc cref="Populate(IRecordable, byte[], ChronicleContext)"/>
 50    public static void Populate(IRecordable target, byte[] data)
 851        => Populate(target, data, context: null);
 52
 53    /// <inheritdoc cref="Populate(IRecordable, ReadOnlySpan{byte}, ChronicleContext)"
 54    ///     path="/*[not(self::exception[@cref='T:System.ArgumentNullException'])]"/>
 55    /// <exception cref="ArgumentNullException"><paramref name="target"/> or <paramref name="data"/> is null.</exception
 56    public static void Populate(IRecordable target, byte[] data, ChronicleContext? context)
 57    {
 9158        if (data == null)
 159            throw new ArgumentNullException(nameof(data));
 60
 9061        Populate(target, data.AsSpan(), context);
 5062    }
 63
 64    /// <inheritdoc cref="Populate(IRecordable, ReadOnlySpan{byte}, ChronicleContext)"/>
 65    public static void Populate(IRecordable target, ReadOnlySpan<byte> data)
 266        => Populate(target, data, context: null);
 67
 68    /// <summary>
 69    /// Applies a MemoryPack record to an existing instance.
 70    /// </summary>
 71    /// <param name="target">The object to mutate. Initialize owned class instances needed by present deep records.</par
 72    /// <param name="data">The nonempty payload to read. The serializer leaves the caller's buffer intact and retains no
 73    /// <param name="context">The destination session for link resolution. Null creates a fresh context.</param>
 74    /// <remarks>
 75    /// Runs the target schema, then calls <see cref="ChronicleContext.ResolveDeferredLinks"/>.
 76    /// A failure can leave earlier assignments applied. A supplied context retains pending callbacks.
 77    /// </remarks>
 78    /// <exception cref="ArgumentNullException"><paramref name="target"/> is null.</exception>
 79    /// <exception cref="ArgumentException"><paramref name="data"/> is empty.</exception>
 80    /// <exception cref="MemoryPackSerializationException">The MemoryPack decoder rejects the payload or a recorded valu
 81    /// <exception cref="InvalidOperationException">A present deep class lacks an initialized target, or link resolution
 82    public static void Populate(IRecordable target, ReadOnlySpan<byte> data, ChronicleContext? context)
 83    {
 9284        if (target == null)
 185            throw new ArgumentNullException(nameof(target));
 9186        if (data.IsEmpty)
 187            throw new ArgumentException("Serialized bytes must not be empty.", nameof(data));
 88
 9089        context ??= new ChronicleContext();
 90
 9091        var chronicler = new MemoryPackRecordReader(data, context);
 9092        target.RecordData(chronicler);
 5393        context.ResolveDeferredLinks();
 5194    }
 95
 96    private sealed class MemoryPackRecordWriter : IChronicler
 97    {
 18898        private readonly OrderedStringMap<byte[]?> _entries = new(8, StringComparer.Ordinal);
 99
 188100        public MemoryPackRecordWriter(ChronicleContext context)
 101        {
 188102            Context = context;
 188103        }
 104
 105        public ChronicleContext Context { get; }
 106
 21107        public SerializationMode Mode => SerializationMode.Saving;
 108
 109        public void LookValue<T>(ref T value, string name, T? defaultValue = default)
 110        {
 354111            if (value is null || EqualityComparer<T>.Default.Equals(value, defaultValue!))
 105112                return;
 113
 249114            _entries[name] = MemoryPackSerializer.Serialize(value);
 249115        }
 116
 117        public void LookDeep<T>(ref T value, string name) where T : class, IRecordable
 118        {
 12119            if (value == null)
 120            {
 1121                _entries[name] = null;
 1122                return;
 123            }
 124
 11125            var nested = new MemoryPackRecordWriter(Context);
 11126            value.RecordData(nested);
 11127            _entries[name] = nested.ToArray();
 11128        }
 129
 130        public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable
 131        {
 95132            var nested = new MemoryPackRecordWriter(Context);
 95133            value.RecordData(nested);
 95134            _entries[name] = nested.ToArray();
 95135        }
 136
 137        public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable
 138        {
 7139            if (!value.HasValue)
 2140                return;
 141
 5142            T nestedValue = value.Value;
 5143            var nested = new MemoryPackRecordWriter(Context);
 5144            nestedValue.RecordData(nested);
 5145            _entries[name] = nested.ToArray();
 5146        }
 147
 148        public void LookLink<T>(
 149            ref T value,
 150            string name,
 151            string? slot = null,
 152            RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate,
 153            Action<T>? assignLoadedValue = null)
 154        {
 15155            string? id = null;
 15156            if (value is not null
 15157                && !Context.Links.TryGetReferenceId(value, out id, slot))
 158            {
 2159                throw new InvalidOperationException(
 2160                    $"Unable to save link '{name}' of type {typeof(T).Name} because no stable id could be produced{Forma
 161            }
 162
 13163            _entries[name] = MemoryPackSerializer.Serialize(id);
 13164        }
 165
 166        public byte[] ToArray()
 167        {
 186168            return MemoryPackSerializer.Serialize(MemoryPackRecordEnvelope.FromEntries(_entries));
 169        }
 170    }
 171
 172    private sealed class MemoryPackRecordReader : IChronicler
 173    {
 174        private readonly OrderedStringMap<byte[]?> _entries;
 175
 216176        public MemoryPackRecordReader(ReadOnlySpan<byte> data, ChronicleContext context)
 177        {
 216178            MemoryPackRecordEnvelope? envelope = MemoryPackRecordEnvelope.Deserialize(data);
 216179            _entries = envelope == null
 216180                ? new OrderedStringMap<byte[]?>(8, StringComparer.Ordinal)
 216181                : envelope.ToEntryMap();
 216182            Context = context;
 216183        }
 184
 185        public ChronicleContext Context { get; }
 186
 28187        public SerializationMode Mode => SerializationMode.Loading;
 188
 189        public void LookValue<T>(ref T value, string name, T? defaultValue = default)
 190        {
 371191            if (!_entries.TryGetValue(name, out byte[]? entry)
 371192                || entry == null)
 193            {
 153194                value = defaultValue!;
 153195                return;
 196            }
 197
 218198            T? loadedValue = MemoryPackSerializer.Deserialize<T>(entry);
 218199            if (loadedValue is null)
 200            {
 1201                value = defaultValue!;
 1202                return;
 203            }
 204
 217205            value = loadedValue;
 217206        }
 207
 208        public void LookDeep<T>(ref T value, string name) where T : class, IRecordable
 209        {
 11210            if (!_entries.TryGetValue(name, out byte[]? entry)
 11211                || entry == null)
 2212                return;
 213
 9214            if (value == null)
 1215                throw new InvalidOperationException(
 1216                    $"Unable to load '{name}' because {typeof(T).Name} must already be instantiated for a deep chronicle
 217
 8218            var nested = new MemoryPackRecordReader(entry, Context);
 8219            value.RecordData(nested);
 8220        }
 221
 222        public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable
 223        {
 109224            if (!_entries.TryGetValue(name, out byte[]? entry)
 109225                || entry == null)
 226            {
 11227                value = CreateDefaultDeepStruct<T>();
 10228                return;
 229            }
 230
 98231            value = new();
 98232            var nested = new MemoryPackRecordReader(entry, Context);
 98233            value.RecordData(nested);
 92234        }
 235
 236        public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable
 237        {
 13238            if (!_entries.TryGetValue(name, out byte[]? entry)
 13239                || entry == null)
 240            {
 4241                value = null;
 4242                return;
 243            }
 244
 9245            T nestedValue = new();
 9246            var nested = new MemoryPackRecordReader(entry, Context);
 9247            nestedValue.RecordData(nested);
 3248            value = nestedValue;
 3249        }
 250
 251        public void LookLink<T>(
 252            ref T value,
 253            string name,
 254            string? slot = null,
 255            RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate,
 256            Action<T>? assignLoadedValue = null)
 257        {
 15258            if (!TryReadLinkId(name, out string? id))
 259            {
 6260                value = default!;
 6261                assignLoadedValue?.Invoke(value);
 6262                return;
 263            }
 264
 9265            if (resolveMode == RecordLinkResolveMode.Deferred)
 266            {
 5267                LoadDeferredLink(ref value, name, id, slot, assignLoadedValue);
 4268                return;
 269            }
 270
 4271            LoadImmediateLink(ref value, name, id, slot, assignLoadedValue);
 3272        }
 273
 274        private bool TryReadLinkId(string name, [NotNullWhen(true)] out string? id)
 275        {
 15276            if (!_entries.TryGetValue(name, out byte[]? entry)
 15277                || entry == null)
 278            {
 3279                id = null;
 3280                return false;
 281            }
 282
 12283            id = MemoryPackSerializer.Deserialize<string>(entry);
 12284            return id != null;
 285        }
 286
 287        private void LoadDeferredLink<T>(
 288            ref T value,
 289            string name,
 290            string id,
 291            string? slot,
 292            Action<T>? assignLoadedValue)
 293        {
 5294            if (assignLoadedValue == null)
 1295                throw new InvalidOperationException(
 1296                    $"Deferred link '{name}' of type {typeof(T).Name} requires an assignment callback.");
 297
 4298            if (Context.Links.TryResolve(id, out T? deferredValue, slot))
 299            {
 1300                value = deferredValue!;
 1301                assignLoadedValue(deferredValue!);
 1302                return;
 303            }
 304
 3305            Context.QueueDeferredLink(name, id, slot, assignLoadedValue);
 3306            value = default!;
 3307        }
 308
 309        private void LoadImmediateLink<T>(
 310            ref T value,
 311            string name,
 312            string id,
 313            string? slot,
 314            Action<T>? assignLoadedValue)
 315        {
 4316            if (!Context.Links.TryResolve(id, out T? resolvedValue, slot))
 1317                throw new InvalidOperationException(
 1318                    $"Unable to load link '{name}' of type {typeof(T).Name} with id '{id}'{FormatSlot(slot)}.");
 319
 3320            value = resolvedValue!;
 3321            assignLoadedValue?.Invoke(resolvedValue!);
 3322        }
 323
 324        private T CreateDefaultDeepStruct<T>() where T : struct, IRecordable
 325        {
 11326            T defaultValue = new();
 11327            var nested = new MemoryPackRecordReader(EmptyRecordBytes, Context);
 11328            defaultValue.RecordData(nested);
 10329            return defaultValue;
 330        }
 331    }
 332
 333    private static string FormatSlot(string? slot)
 334    {
 3335        return string.IsNullOrEmpty(slot)
 3336            ? string.Empty
 3337            : $" in slot '{slot}'";
 338    }
 339}
 340
 341#endif