< Summary

Information
Class: Chronicler.ChronicleLinkRegistry
Assembly: Chronicler
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler/Recording/Links/ChronicleLinkRegistry.cs
Line coverage
100%
Covered lines: 61
Uncovered lines: 0
Coverable lines: 61
Total lines: 222
Line coverage: 100%
Branch coverage
100%
Covered branches: 40
Total branches: 40
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%11100%
RegisterResolver(...)100%22100%
RegisterInstance(...)100%22100%
UnregisterInstance(...)100%44100%
TryResolve(...)100%88100%
TryGetReferenceId(...)100%88100%
GetOrCreateInstanceTable(...)100%22100%
.ctor(...)100%44100%
Equals(...)100%22100%
Equals(...)100%22100%
GetHashCode()100%11100%
.ctor()100%11100%
Register(...)100%11100%
Unregister(...)100%11100%
TryResolve(...)100%11100%
TryGetReferenceId(...)100%44100%
ValuesMatch(...)100%22100%

File(s)

/home/runner/work/Chronicler/Chronicler/src/Chronicler/Recording/Links/ChronicleLinkRegistry.cs

#LineLine coverage
 1//=======================================================================
 2// ChronicleLinkRegistry.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.Collections.Generic;
 10using System.Diagnostics.CodeAnalysis;
 11using Chronicler.Serialization;
 12
 13namespace Chronicler;
 14
 15/// <summary>
 16/// Maps stable IDs to host-owned values within a recording session.
 17/// </summary>
 18/// <remarks>
 19/// Each lookup uses the declared link type and slot. Slot names are case-sensitive.
 20/// Null and empty slots select the same default slot.
 21/// </remarks>
 22public sealed class ChronicleLinkRegistry
 23{
 62224    private readonly Dictionary<ChronicleLinkKey, object> _resolvers = new();
 62225    private readonly Dictionary<ChronicleLinkKey, object> _registeredInstances = new();
 26
 27    /// <summary>
 28    /// Sets the custom resolver for a link type and slot.
 29    /// </summary>
 30    /// <typeparam name="T">The declared type used by the recording schema.</typeparam>
 31    /// <param name="resolver">The resolver to retain and consult before instance registrations.</param>
 32    /// <param name="slot">An optional identity domain. Null or empty selects the default slot.</param>
 33    /// <remarks>Replaces any previous resolver in that type and slot.</remarks>
 34    /// <exception cref="ArgumentNullException"><paramref name="resolver"/> is null.</exception>
 35    public void RegisterResolver<T>(IRecordLinkResolver<T> resolver, string? slot = null)
 36    {
 1337        _resolvers[new ChronicleLinkKey(typeof(T), slot)] = resolver ?? throw new ArgumentNullException(nameof(resolver)
 1238    }
 39
 40    /// <summary>
 41    /// Associates a value with a stable ID.
 42    /// </summary>
 43    /// <typeparam name="T">The declared type used by the recording schema.</typeparam>
 44    /// <param name="id">A case-sensitive ID containing at least one non-whitespace character.</param>
 45    /// <param name="value">The value to retain. For reference types, the registry keeps the instance.</param>
 46    /// <param name="slot">An optional identity domain. Null or empty selects the default slot.</param>
 47    /// <remarks>Registering the same ID for the same type and slot replaces its value in place.</remarks>
 48    /// <exception cref="ArgumentException"><paramref name="id"/> is null, empty, or whitespace.</exception>
 49    public void RegisterInstance<T>(string id, T value, string? slot = null)
 50    {
 3451        if (string.IsNullOrWhiteSpace(id))
 352            throw new ArgumentException("A registered link id must not be null or empty.", nameof(id));
 53
 3154        RegisteredLinkTable<T> table = GetOrCreateInstanceTable<T>(slot);
 3155        table.Register(id, value);
 3156    }
 57
 58    /// <summary>
 59    /// Removes an instance registration.
 60    /// </summary>
 61    /// <typeparam name="T">The declared type used to register the value.</typeparam>
 62    /// <param name="id">The case-sensitive ID of the registration.</param>
 63    /// <param name="slot">The registration's identity domain. Null or empty selects the default slot.</param>
 64    /// <returns>
 65    /// <see langword="true"/> if the registration was removed. Returns <see langword="false"/> for a blank ID
 66    /// or when the type and slot contain no registration for it.
 67    /// </returns>
 68    /// <remarks>The custom resolver for the same type and slot remains available.</remarks>
 69    public bool UnregisterInstance<T>(string id, string? slot = null)
 70    {
 671        if (string.IsNullOrWhiteSpace(id))
 372            return false;
 73
 374        ChronicleLinkKey key = new(typeof(T), slot);
 375        if (!_registeredInstances.TryGetValue(key, out object? tableObject))
 176            return false;
 77
 278        return ((RegisteredLinkTable<T>)tableObject!).Unregister(id);
 79    }
 80
 81    /// <summary>
 82    /// Looks up the value for a recorded ID.
 83    /// </summary>
 84    /// <typeparam name="T">The declared link type to look up.</typeparam>
 85    /// <param name="id">The non-null recorded ID. Instance registrations use case-sensitive matching.</param>
 86    /// <param name="value">The resolved value on success. Otherwise, the default value of <typeparamref name="T"/>.</pa
 87    /// <param name="slot">The recorded link's identity domain. Null or empty selects the default slot.</param>
 88    /// <returns><see langword="true"/> if the resolver or an instance registration supplied a value.</returns>
 89    /// <remarks>Consults the custom resolver first and falls back to instance registrations on a miss.</remarks>
 90    /// <exception cref="ArgumentNullException"><paramref name="id"/> is null when an instance table is consulted.</exce
 91    public bool TryResolve<T>(string id, [MaybeNullWhen(false)] out T value, string? slot = null)
 92    {
 2493        ChronicleLinkKey key = new(typeof(T), slot);
 2494        if (_resolvers.TryGetValue(key, out object? resolverObject)
 2495            && ((IRecordLinkResolver<T>)resolverObject!).TryResolveReference(id, out value))
 96        {
 497            return true;
 98        }
 99
 20100        if (_registeredInstances.TryGetValue(key, out object? tableObject)
 20101            && ((RegisteredLinkTable<T>)tableObject!).TryResolve(id, out value))
 102        {
 7103            return true;
 104        }
 105
 13106        value = default!;
 13107        return false;
 108    }
 109
 110    /// <summary>
 111    /// Looks up the stable ID for a value.
 112    /// </summary>
 113    /// <typeparam name="T">The declared link type to look up.</typeparam>
 114    /// <param name="value">The value to identify in this session.</param>
 115    /// <param name="id">The stable ID on success. Otherwise, null.</param>
 116    /// <param name="slot">The link's identity domain. Null or empty selects the default slot.</param>
 117    /// <returns><see langword="true"/> if the resolver or an instance registration supplied an ID.</returns>
 118    /// <remarks>
 119    /// Consults the custom resolver first. Instance lookup uses reference identity for reference types
 120    /// and default equality for value types. If several registrations match, returns the first in registration order.
 121    /// </remarks>
 122    public bool TryGetReferenceId<T>(T value, [NotNullWhen(true)] out string? id, string? slot = null)
 123    {
 39124        ChronicleLinkKey key = new(typeof(T), slot);
 39125        if (_resolvers.TryGetValue(key, out object? resolverObject)
 39126            && ((IRecordLinkResolver<T>)resolverObject!).TryGetReferenceId(value, out id))
 127        {
 8128            return true;
 129        }
 130
 31131        if (_registeredInstances.TryGetValue(key, out object? tableObject)
 31132            && ((RegisteredLinkTable<T>)tableObject!).TryGetReferenceId(value, out id))
 133        {
 24134            return true;
 135        }
 136
 7137        id = null;
 7138        return false;
 139    }
 140
 141    private RegisteredLinkTable<T> GetOrCreateInstanceTable<T>(string? slot)
 142    {
 31143        ChronicleLinkKey key = new(typeof(T), slot);
 31144        if (_registeredInstances.TryGetValue(key, out object? tableObject))
 2145            return (RegisteredLinkTable<T>)tableObject!;
 146
 29147        var table = new RegisteredLinkTable<T>();
 29148        _registeredInstances[key] = table;
 29149        return table;
 150    }
 151
 152    private readonly struct ChronicleLinkKey : IEquatable<ChronicleLinkKey>
 153    {
 154        private readonly Type _type;
 155        private readonly string _slot;
 156
 157        public ChronicleLinkKey(Type type, string? slot)
 158        {
 116159            _type = type ?? throw new ArgumentNullException(nameof(type));
 115160            _slot = slot ?? string.Empty;
 115161        }
 162
 163        public bool Equals(ChronicleLinkKey other)
 164        {
 51165            return _type == other._type
 51166                && string.Equals(_slot, other._slot, StringComparison.Ordinal);
 167        }
 168
 2169        public override bool Equals(object? obj) => obj is ChronicleLinkKey other && Equals(other);
 170
 171        public override int GetHashCode()
 172        {
 173            unchecked
 174            {
 90175                return (_type.GetHashCode() * 397) ^ _slot.GetHashCode();
 176            }
 177        }
 178    }
 179
 180    private sealed class RegisteredLinkTable<T>
 181    {
 29182        private readonly OrderedStringMap<T> _byId = new(8, StringComparer.Ordinal);
 183
 184        public void Register(string id, T value)
 185        {
 31186            _byId[id] = value;
 31187        }
 188
 189        public bool Unregister(string id)
 190        {
 2191            return _byId.Remove(id);
 192        }
 193
 194        public bool TryResolve(string id, [MaybeNullWhen(false)] out T value)
 195        {
 7196            return _byId.TryGetValue(id, out value);
 197        }
 198
 199        public bool TryGetReferenceId(T value, [NotNullWhen(true)] out string? id)
 200        {
 78201            foreach (KeyValuePair<string, T> pair in _byId)
 202            {
 26203                if (!ValuesMatch(pair.Value, value))
 204                    continue;
 205
 24206                id = pair.Key;
 24207                return true;
 208            }
 209
 1210            id = null;
 1211            return false;
 24212        }
 213
 214        private static bool ValuesMatch(T left, T right)
 215        {
 26216            if (typeof(T).IsValueType)
 2217                return EqualityComparer<T>.Default.Equals(left, right);
 218
 24219            return ReferenceEquals(left, right);
 220        }
 221    }
 222}