< Summary

Information
Class: Chronicler.Hashing.ChronicleHashWriter
Assembly: Chronicler
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler/Hashing/ChronicleHashWriter.cs
Line coverage
100%
Covered lines: 86
Uncovered lines: 0
Coverable lines: 86
Total lines: 239
Line coverage: 100%
Branch coverage
100%
Covered branches: 22
Total branches: 22
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%
WriteSection(...)100%1010100%
WriteBool(...)100%11100%
WriteByte(...)100%11100%
WriteSByte(...)100%11100%
WriteInt16(...)100%11100%
WriteUInt16(...)100%11100%
WriteInt32(...)100%11100%
WriteUInt32(...)100%11100%
WriteInt64(...)100%11100%
WriteUInt64(...)100%11100%
WriteChar(...)100%11100%
WriteString(...)100%44100%
WriteEnum(...)100%66100%
ToHash()100%11100%
EnsureInitialized()100%22100%
FinalizeLane(...)100%11100%

File(s)

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

#LineLine coverage
 1//=======================================================================
 2// ChronicleHashWriter.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.Runtime.CompilerServices;
 10
 11namespace Chronicler.Hashing;
 12
 13/// <summary>Accumulates a deterministic 128-bit record hash.</summary>
 14/// <remarks>
 15/// Each write appends to the current stream in call order. A default writer is equivalent to a newly
 16/// constructed writer. This non-cryptographic hash is intended for state comparison and replay validation.
 17/// </remarks>
 18public struct ChronicleHashWriter
 19{
 20    private const ulong FnvPrime = 1099511628211UL;
 21    private const ulong LowOffset = 14695981039346656037UL;
 22    private const ulong HighOffset = 7809847782465536322UL;
 23
 24    private ulong _low;
 25    private ulong _high;
 26    private bool _initialized;
 27
 28    /// <summary>
 29    /// Creates a writer seeded for an empty deterministic hash stream.
 30    /// </summary>
 31    public ChronicleHashWriter()
 32    {
 11087933        _low = LowOffset;
 11087934        _high = HighOffset;
 11087935        _initialized = true;
 11087936    }
 37
 38    /// <summary>Appends a section header.</summary>
 39    /// <param name="tag">A nonempty ASCII identifier shared by writers of this schema.</param>
 40    /// <param name="version">The signed 32-bit schema revision to include in the hash.</param>
 41    /// <remarks>Writes the byte count, ASCII bytes, then version. Invalid tags leave the writer unchanged.</remarks>
 42    /// <exception cref="ArgumentNullException">The tag is null.</exception>
 43    /// <exception cref="ArgumentException">The tag is empty or contains a non-ASCII character.</exception>
 44    public void WriteSection(string tag, int version)
 45    {
 48093446        if (tag == null)
 147            throw new ArgumentNullException(nameof(tag));
 48093348        if (tag.Length == 0)
 149            throw new ArgumentException("Record hash section tags must not be empty.", nameof(tag));
 50
 1790775051        for (int i = 0; i < tag.Length; i++)
 52        {
 847294453            if (tag[i] > 0x7f)
 154                throw new ArgumentException("Record hash section tags must be stable ASCII.", nameof(tag));
 55        }
 56
 48093157        WriteInt32(tag.Length);
 1790774458        for (int i = 0; i < tag.Length; i++)
 59        {
 847294160            WriteByte((byte)tag[i]);
 61        }
 62
 48093163        WriteInt32(version);
 48093164    }
 65
 66    /// <summary>Appends one byte.</summary>
 67    /// <param name="value">False writes zero and true writes one.</param>
 68    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 69    public void WriteBool(bool value)
 70    {
 163093971        WriteByte(value ? (byte)1 : (byte)0);
 163093972    }
 73
 74    /// <summary>Appends one byte.</summary>
 75    /// <param name="value">All eight input bits are written unchanged.</param>
 76    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 77    public void WriteByte(byte value)
 78    {
 6872264379        EnsureInitialized();
 80
 81        unchecked
 82        {
 6872264383            _low ^= value;
 6872264384            _low *= FnvPrime;
 85
 6872264386            _high ^= (ulong)value + 0x9e3779b97f4a7c15UL + (_low << 6) + (_low >> 2);
 6872264387            _high *= FnvPrime;
 88        }
 6872264389    }
 90
 91    /// <summary>Appends one byte.</summary>
 92    /// <param name="value">The signed value is encoded in two's complement.</param>
 93    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 94    public void WriteSByte(sbyte value)
 95    {
 3689496        WriteByte(unchecked((byte)value));
 3689497    }
 98
 99    /// <summary>Appends two little-endian bytes.</summary>
 100    /// <param name="value">The signed value is encoded in two's complement.</param>
 101    public void WriteInt16(short value)
 102    {
 36895103        WriteUInt16(unchecked((ushort)value));
 36895104    }
 105
 106    /// <summary>Appends two little-endian bytes.</summary>
 107    /// <param name="value">The full unsigned 16-bit range is accepted.</param>
 108    public void WriteUInt16(ushort value)
 109    {
 24175300110        WriteByte((byte)value);
 24175300111        WriteByte((byte)(value >> 8));
 24175300112    }
 113
 114    /// <summary>Appends four little-endian bytes.</summary>
 115    /// <param name="value">The signed value is encoded in two's complement.</param>
 116    public void WriteInt32(int value)
 117    {
 2111150118        WriteUInt32(unchecked((uint)value));
 2111150119    }
 120
 121    /// <summary>Appends four little-endian bytes.</summary>
 122    /// <param name="value">The full unsigned 32-bit range is accepted.</param>
 123    public void WriteUInt32(uint value)
 124    {
 2259516125        WriteByte((byte)value);
 2259516126        WriteByte((byte)(value >> 8));
 2259516127        WriteByte((byte)(value >> 16));
 2259516128        WriteByte((byte)(value >> 24));
 2259516129    }
 130
 131    /// <summary>Appends eight little-endian bytes.</summary>
 132    /// <param name="value">The signed value is encoded in two's complement.</param>
 133    public void WriteInt64(long value)
 134    {
 37971135        WriteUInt64(unchecked((ulong)value));
 37971136    }
 137
 138    /// <summary>Appends eight little-endian bytes.</summary>
 139    /// <param name="value">The full unsigned 64-bit range is accepted.</param>
 140    public void WriteUInt64(ulong value)
 141    {
 74908142        WriteByte((byte)value);
 74908143        WriteByte((byte)(value >> 8));
 74908144        WriteByte((byte)(value >> 16));
 74908145        WriteByte((byte)(value >> 24));
 74908146        WriteByte((byte)(value >> 32));
 74908147        WriteByte((byte)(value >> 40));
 74908148        WriteByte((byte)(value >> 48));
 74908149        WriteByte((byte)(value >> 56));
 74908150    }
 151
 152    /// <summary>Appends one little-endian UTF-16 code unit.</summary>
 153    /// <param name="value">The single code unit to record, including an isolated surrogate.</param>
 154    public void WriteChar(char value)
 155    {
 24101468156        WriteUInt16(value);
 24101468157    }
 158
 159    /// <summary>Appends a nullable sequence of UTF-16 code units.</summary>
 160    /// <param name="value">Null writes a zero presence byte. A string writes a one byte, its 32-bit code-unit count, th
 161    public void WriteString(string? value)
 162    {
 1000667163        if (value == null)
 164        {
 36896165            WriteBool(false);
 36896166            return;
 167        }
 168
 963771169        WriteBool(true);
 963771170        WriteInt32(value.Length);
 50056686171        for (int i = 0; i < value.Length; i++)
 172        {
 24064572173            WriteChar(value[i]);
 174        }
 963771175    }
 176
 177    /// <summary>Appends the enum's underlying bytes in little-endian order.</summary>
 178    /// <typeparam name="TEnum">An enum with a one-, two-, four-, or eight-byte integral representation.</typeparam>
 179    /// <param name="value">The numeric bits to record, including combinations or unnamed values.</param>
 180    public void WriteEnum<TEnum>(TEnum value)
 181        where TEnum : struct, Enum
 182    {
 36885183        if (Unsafe.SizeOf<TEnum>() == 1)
 184        {
 2185            WriteByte(Unsafe.As<TEnum, byte>(ref value));
 2186            return;
 187        }
 188
 36883189        if (Unsafe.SizeOf<TEnum>() == 2)
 190        {
 2191            WriteUInt16(Unsafe.As<TEnum, ushort>(ref value));
 2192            return;
 193        }
 194
 36881195        if (Unsafe.SizeOf<TEnum>() == 4)
 196        {
 36879197            WriteUInt32(Unsafe.As<TEnum, uint>(ref value));
 36879198            return;
 199        }
 200
 2201        WriteUInt64(Unsafe.As<TEnum, ulong>(ref value));
 2202    }
 203
 204    /// <summary>Takes a snapshot of the running hash.</summary>
 205    /// <returns>The finalized hash of all bytes written so far.</returns>
 206    /// <remarks>The writer remains available for additional writes. Repeated snapshots of the same state match.</remark
 207    public ChronicleHash ToHash()
 208    {
 110874209        EnsureInitialized();
 210
 110874211        ulong low = FinalizeLane(_low);
 110874212        ulong high = FinalizeLane(_high ^ low);
 110874213        return new ChronicleHash(low, high);
 214    }
 215
 216    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 217    private void EnsureInitialized()
 218    {
 68833517219        if (_initialized)
 68833516220            return;
 221
 1222        _low = LowOffset;
 1223        _high = HighOffset;
 1224        _initialized = true;
 1225    }
 226
 227    private static ulong FinalizeLane(ulong value)
 228    {
 229        unchecked
 230        {
 221748231            value ^= value >> 33;
 221748232            value *= 0xff51afd7ed558ccdUL;
 221748233            value ^= value >> 33;
 221748234            value *= 0xc4ceb9fe1a85ec53UL;
 221748235            value ^= value >> 33;
 221748236            return value;
 237        }
 238    }
 239}