< Summary

Information
Class: Chronicler.Hashing.ChronicleHashChronicler
Assembly: Chronicler
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler/Hashing/ChronicleHashChronicler.cs
Line coverage
100%
Covered lines: 176
Uncovered lines: 0
Coverable lines: 176
Total lines: 382
Line coverage: 100%
Branch coverage
100%
Covered branches: 57
Total branches: 57
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%
.ctor()100%11100%
get_Context()100%22100%
get_Mode()100%11100%
Contribute(...)100%11100%
LookValue(...)100%11100%
LookDeep(...)100%22100%
LookDeepStruct(...)100%11100%
LookNullableDeep(...)100%22100%
LookLink(...)100%66100%
Rent()100%44100%
WriteRecordStart(...)100%11100%
WriteRecordEnd()100%11100%
WriteFieldHeader(...)100%22100%
WriteLeafKind(...)100%22100%
GetLeafKind(...)100%44100%
WriteLeafValue(...)100%1313100%
WriteEnumValue(...)100%66100%
GetStableTypeName(...)100%22100%
BuildStableTypeName(...)100%44100%
BuildStableArrayTypeName(...)100%22100%
BuildStableGenericTypeName(...)100%44100%
FormatSlot(...)100%22100%

File(s)

/home/runner/work/Chronicler/Chronicler/src/Chronicler/Hashing/ChronicleHashChronicler.cs

#LineLine coverage
 1//=======================================================================
 2// ChronicleHashChronicler.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.Runtime.CompilerServices;
 11using System.Text;
 12
 13namespace Chronicler.Hashing;
 14
 15internal sealed class ChronicleHashChronicler : IChronicler
 16{
 17    private enum FieldKind : byte
 18    {
 19        Value = 1,
 20        DeepClass = 2,
 21        DeepStruct = 3,
 22        NullableDeepStruct = 4,
 23        Link = 5
 24    }
 25
 26    private enum LeafKind : byte
 27    {
 28        Bool = 1,
 29        Byte = 2,
 30        SByte = 3,
 31        Int16 = 4,
 32        UInt16 = 5,
 33        Int32 = 6,
 34        UInt32 = 7,
 35        Int64 = 8,
 36        UInt64 = 9,
 37        Char = 10,
 38        String = 11,
 39        Enum = 12
 40    }
 41
 42    [ThreadStatic]
 43    private static ChronicleHashChronicler? _cached;
 44
 145    private static readonly Dictionary<Type, LeafKind> LeafKindsByType = new()
 146    {
 147        [typeof(bool)] = LeafKind.Bool,
 148        [typeof(byte)] = LeafKind.Byte,
 149        [typeof(sbyte)] = LeafKind.SByte,
 150        [typeof(short)] = LeafKind.Int16,
 151        [typeof(ushort)] = LeafKind.UInt16,
 152        [typeof(int)] = LeafKind.Int32,
 153        [typeof(uint)] = LeafKind.UInt32,
 154        [typeof(long)] = LeafKind.Int64,
 155        [typeof(ulong)] = LeafKind.UInt64,
 156        [typeof(char)] = LeafKind.Char,
 157        [typeof(string)] = LeafKind.String
 158    };
 59
 160    private static readonly Dictionary<Type, string> StableTypeNames = new();
 161    private static readonly object StableTypeNameSync = new();
 62
 63    private ChronicleHashWriter _writer;
 64    private ChronicleContext? _context;
 65    private bool _isInUse;
 66
 567    private ChronicleHashChronicler()
 68    {
 569    }
 70
 71    public ChronicleContext Context
 72    {
 73        get
 74        {
 1375            if (_context == null)
 276                throw new InvalidOperationException("Record hash chronicler context is not active.");
 77
 1178            return _context;
 79        }
 80    }
 81
 3700082    public SerializationMode Mode => SerializationMode.Saving;
 83
 84    public static void Contribute(IRecordable target, ChronicleContext context, ref ChronicleHashWriter writer)
 85    {
 7399686        ChronicleHashChronicler chronicler = Rent();
 87
 7399688        chronicler._writer = writer;
 7399689        chronicler._context = context;
 90
 91        try
 92        {
 7399693            chronicler.WriteRecordStart(target.GetType());
 7399694            target.RecordData(chronicler);
 7399195            chronicler.WriteRecordEnd();
 7399196            writer = chronicler._writer;
 7399197        }
 98        finally
 99        {
 73996100            chronicler._writer = default;
 73996101            chronicler._context = null;
 73996102            chronicler._isInUse = false;
 73996103        }
 73991104    }
 105
 106    public void LookValue<T>(ref T value, string name, T? defaultValue = default)
 107    {
 222960108        WriteFieldHeader(name, FieldKind.Value, typeof(T));
 222959109        LeafKind kind = WriteLeafKind(typeof(T), name);
 222958110        WriteLeafValue(ref value, kind);
 111
 222958112        T declaredDefault = defaultValue!;
 222958113        WriteLeafValue(ref declaredDefault, kind);
 222958114    }
 115
 116    public void LookDeep<T>(ref T value, string name)
 117        where T : class, IRecordable
 118    {
 36874119        WriteFieldHeader(name, FieldKind.DeepClass, typeof(T));
 120
 36874121        if (value == null)
 122        {
 1123            _writer.WriteBool(false);
 1124            return;
 125        }
 126
 36873127        _writer.WriteBool(true);
 36873128        WriteRecordStart(typeof(T));
 36873129        value.RecordData(this);
 36873130        WriteRecordEnd();
 36873131    }
 132
 133    public void LookDeepStruct<T>(ref T value, string name)
 134        where T : struct, IRecordable
 135    {
 37288136        WriteFieldHeader(name, FieldKind.DeepStruct, typeof(T));
 37288137        WriteRecordStart(typeof(T));
 37288138        value.RecordData(this);
 37288139        WriteRecordEnd();
 37288140    }
 141
 142    public void LookNullableDeep<T>(ref T? value, string name)
 143        where T : struct, IRecordable
 144    {
 36876145        WriteFieldHeader(name, FieldKind.NullableDeepStruct, typeof(T));
 146
 36876147        if (!value.HasValue)
 148        {
 3149            _writer.WriteBool(false);
 3150            return;
 151        }
 152
 36873153        _writer.WriteBool(true);
 36873154        T nestedValue = value.Value;
 36873155        WriteRecordStart(typeof(T));
 36873156        nestedValue.RecordData(this);
 36873157        WriteRecordEnd();
 36873158    }
 159
 160    public void LookLink<T>(
 161        ref T value,
 162        string name,
 163        string? slot = null,
 164        RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate,
 165        Action<T>? assignLoadedValue = null)
 166    {
 10167        string? normalizedSlot = string.IsNullOrEmpty(slot) ? null : slot;
 10168        WriteFieldHeader(name, FieldKind.Link, typeof(T));
 10169        _writer.WriteString(normalizedSlot);
 10170        _writer.WriteEnum(resolveMode);
 171
 10172        if (value is null)
 173        {
 1174            _writer.WriteString(null);
 1175            return;
 176        }
 177
 9178        if (!Context.Links.TryGetReferenceId(value, out string? id, normalizedSlot))
 179        {
 2180            throw new InvalidOperationException(
 2181                $"Unable to hash link '{name}' of type {typeof(T).Name} because no stable id could be produced{FormatSlo
 182        }
 183
 7184        _writer.WriteString(id);
 7185    }
 186
 187    private static ChronicleHashChronicler Rent()
 188    {
 73996189        ChronicleHashChronicler? cached = _cached;
 73996190        if (cached == null)
 191        {
 4192            cached = new ChronicleHashChronicler();
 4193            _cached = cached;
 194        }
 195
 73996196        if (cached._isInUse)
 1197            return new ChronicleHashChronicler { _isInUse = true };
 198
 73995199        cached._isInUse = true;
 73995200        return cached;
 201    }
 202
 203    private void WriteRecordStart(Type declaredType)
 204    {
 185030205        _writer.WriteSection("chronicler.record", 1);
 185030206        _writer.WriteString(GetStableTypeName(declaredType));
 185030207    }
 208
 209    private void WriteRecordEnd()
 210    {
 185025211        _writer.WriteSection("chronicler.record.end", 1);
 185025212    }
 213
 214    private void WriteFieldHeader(string name, FieldKind kind, Type declaredType)
 215    {
 334008216        if (name == null)
 1217            throw new ArgumentNullException(nameof(name));
 218
 334007219        _writer.WriteString(name);
 334007220        _writer.WriteByte((byte)kind);
 334007221        _writer.WriteString(GetStableTypeName(declaredType));
 334007222    }
 223
 224    private LeafKind WriteLeafKind(Type declaredType, string name)
 225    {
 222959226        LeafKind kind = GetLeafKind(declaredType, name);
 222958227        _writer.WriteByte((byte)kind);
 228
 222958229        if (kind == LeafKind.Enum)
 36944230            _writer.WriteString(GetStableTypeName(Enum.GetUnderlyingType(declaredType)));
 231
 222958232        return kind;
 233    }
 234
 235    private static LeafKind GetLeafKind(Type declaredType, string name)
 236    {
 222959237        if (declaredType.IsEnum)
 36944238            return LeafKind.Enum;
 239
 186015240        if (LeafKindsByType.TryGetValue(declaredType, out LeafKind kind))
 186014241            return kind;
 242
 1243        throw new NotSupportedException($"Unsupported record-hash leaf value '{name}' of type {GetStableTypeName(declare
 244    }
 245
 246    private void WriteLeafValue<T>(ref T value, LeafKind kind)
 247    {
 445916248        if (kind == LeafKind.String)
 249        {
 73780250            _writer.WriteString(value as string);
 73780251            return;
 252        }
 253
 372136254        _writer.WriteBool(true);
 255
 256        switch (kind)
 257        {
 258            case LeafKind.Bool:
 147508259                _writer.WriteBool(Unsafe.As<T, bool>(ref value));
 147508260                break;
 261            case LeafKind.Byte:
 26262                _writer.WriteByte(Unsafe.As<T, byte>(ref value));
 26263                break;
 264            case LeafKind.SByte:
 26265                _writer.WriteSByte(Unsafe.As<T, sbyte>(ref value));
 26266                break;
 267            case LeafKind.Int16:
 26268                _writer.WriteInt16(Unsafe.As<T, short>(ref value));
 26269                break;
 270            case LeafKind.UInt16:
 26271                _writer.WriteUInt16(Unsafe.As<T, ushort>(ref value));
 26272                break;
 273            case LeafKind.Int32:
 148632274                _writer.WriteInt32(Unsafe.As<T, int>(ref value));
 148632275                break;
 276            case LeafKind.UInt32:
 850277                _writer.WriteUInt32(Unsafe.As<T, uint>(ref value));
 850278                break;
 279            case LeafKind.Int64:
 1102280                _writer.WriteInt64(Unsafe.As<T, long>(ref value));
 1102281                break;
 282            case LeafKind.UInt64:
 26283                _writer.WriteUInt64(Unsafe.As<T, ulong>(ref value));
 26284                break;
 285            case LeafKind.Char:
 26286                _writer.WriteChar(Unsafe.As<T, char>(ref value));
 26287                break;
 288            default:
 289                // GetLeafKind validates the type; Enum is the only remaining kind.
 73888290                WriteEnumValue(ref value);
 291                break;
 292        }
 73888293    }
 294
 295    private void WriteEnumValue<T>(ref T value)
 296    {
 73888297        if (Unsafe.SizeOf<T>() == 1)
 298        {
 40299            _writer.WriteByte(Unsafe.As<T, byte>(ref value));
 40300            return;
 301        }
 302
 73848303        if (Unsafe.SizeOf<T>() == 2)
 304        {
 40305            _writer.WriteUInt16(Unsafe.As<T, ushort>(ref value));
 40306            return;
 307        }
 308
 73808309        if (Unsafe.SizeOf<T>() == 4)
 310        {
 73768311            _writer.WriteUInt32(Unsafe.As<T, uint>(ref value));
 73768312            return;
 313        }
 314
 40315        _writer.WriteUInt64(Unsafe.As<T, ulong>(ref value));
 40316    }
 317
 318    private static string GetStableTypeName(Type type)
 319    {
 555991320        lock (StableTypeNameSync)
 321        {
 555991322            if (StableTypeNames.TryGetValue(type, out string? name))
 555941323                return name;
 324
 50325            name = BuildStableTypeName(type);
 50326            StableTypeNames[type] = name;
 50327            return name;
 328        }
 555991329    }
 330
 331    private static string BuildStableTypeName(Type type)
 332    {
 50333        if (type.IsArray)
 2334            return BuildStableArrayTypeName(type);
 335
 48336        if (!type.IsGenericType)
 337            // Runtime records and typeof(T) supply closed types, never generic parameters.
 44338            return type.FullName!;
 339
 4340        return BuildStableGenericTypeName(type);
 341    }
 342
 343    private static string BuildStableArrayTypeName(Type type)
 344    {
 2345        Type elementType = type.GetElementType()!;
 2346        int rank = type.GetArrayRank();
 2347        string suffix = rank == 1
 2348            ? "[]"
 2349            : "[" + new string(',', rank - 1) + "]";
 350
 2351        return GetStableTypeName(elementType) + suffix;
 352    }
 353
 354    private static string BuildStableGenericTypeName(Type type)
 355    {
 4356        Type genericTypeDefinition = type.GetGenericTypeDefinition();
 4357        string baseName = genericTypeDefinition.FullName!;
 4358        Type[] arguments = type.GetGenericArguments();
 359
 4360        var builder = new StringBuilder(baseName.Length + (arguments.Length * 16) + 2);
 4361        builder.Append(baseName);
 4362        builder.Append('<');
 363
 22364        for (int i = 0; i < arguments.Length; i++)
 365        {
 7366            if (i > 0)
 3367                builder.Append(',');
 368
 7369            builder.Append(GetStableTypeName(arguments[i]));
 370        }
 371
 4372        builder.Append('>');
 4373        return builder.ToString();
 374    }
 375
 376    private static string FormatSlot(string? slot)
 377    {
 2378        return string.IsNullOrEmpty(slot)
 2379            ? string.Empty
 2380            : $" in slot '{slot}'";
 381    }
 382}