< Summary

Information
Class: DeltaSharp.DeltaCreateException
Assembly: DeltaSharp
File(s): /home/runner/work/DeltaSharp/DeltaSharp/src/DeltaSharp/DeltaCreate.cs
Line coverage
100%
Covered lines: 4
Uncovered lines: 0
Coverable lines: 4
Total lines: 287
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_Error()100%11100%
.ctor(...)100%11100%

File(s)

/home/runner/work/DeltaSharp/DeltaSharp/src/DeltaSharp/DeltaCreate.cs

#LineLine coverage
 1using DeltaSharp.Format;
 2using DeltaSharp.Util;
 3using DeltaSharp.Util.Hashtable;
 4using System;
 5using System.Collections.Generic;
 6using System.Diagnostics;
 7using System.Numerics;
 8using System.Runtime.CompilerServices;
 9using System.Runtime.InteropServices;
 10
 11namespace DeltaSharp;
 12
 13/// <summary>Creates patches that reconstruct a target from an original source.</summary>
 14public interface IDeltaCreate
 15{
 16    /// <summary>Creates a patch using this encoder's format, checksum algorithm, and search settings.</summary>
 17    /// <param name="origin">The original source bytes that will be available when applying the patch; may be empty.</pa
 18    /// <param name="target">The desired reconstructed bytes; may be empty.</param>
 19    /// <returns>The encoded patch and the checksum of the target, rather than of the patch bytes.</returns>
 20    /// <remarks>The patch must be applied with the same format and checksum algorithm. Inputs are not modified.</remark
 21    DeltaResult Create(ReadOnlySpan<byte> origin, ReadOnlySpan<byte> target);
 22}
 23
 24/// <summary>Creates patches using a configurable format writer and target checksum algorithm.</summary>
 25/// <typeparam name="TWriter">The patch writer, with a public parameterless constructor.</typeparam>
 26/// <typeparam name="TChecksum">The target checksum algorithm, with a public parameterless constructor.</typeparam>
 27/// <remarks>
 28/// Each call creates and disposes a writer. If the writer has a public constructor taking a single
 29/// <see cref="int"/>, it receives an initial capacity hint in bytes. Output returned by the writer must
 30/// remain valid after disposal. The checksum instance is reused, so its implementation determines
 31/// whether concurrent calls are safe. Source-match search does not guarantee a minimum-size patch.
 32/// </remarks>
 33public class DeltaCreate<TWriter,TChecksum>: IDeltaCreate
 34    where TWriter : IDeltaWriter, new()
 35    where TChecksum : IDeltaChecksum,new()
 36{
 37    private const int MinEvaluateLength = 16;
 38    private const int BoundedCandidateLimit = 256;
 39    private static readonly System.Reflection.ConstructorInfo? SizeHintConstructor =
 40        typeof(TWriter).GetConstructor(new[] { typeof(int) });
 41
 42
 43    private TChecksum _checksum;
 44    private readonly int _maxCandidatesPerPosition;
 45
 46    /// <summary>Initializes an encoder with a new checksum instance and exhaustive source-match search.</summary>
 47    public DeltaCreate() : this(new TChecksum(), DeltaSearchMode.Exhaustive)
 48    {
 49    }
 50
 51    /// <summary>Initializes an encoder with the supplied checksum instance and exhaustive source-match search.</summary
 52    /// <param name="checksum">The non-null checksum implementation to retain for subsequent calls.</param>
 53    public DeltaCreate(TChecksum checksum) : this(checksum, DeltaSearchMode.Exhaustive)
 54    {
 55    }
 56
 57    /// <summary>Initializes an encoder with the supplied checksum instance and default source-match search mode.</summa
 58    /// <param name="checksum">The non-null checksum implementation to retain for subsequent calls.</param>
 59    /// <param name="searchMode">The search-effort policy used by calls without an explicit mode.</param>
 60    /// <exception cref="ArgumentOutOfRangeException"><paramref name="searchMode"/> is not a defined search mode.</excep
 61    public DeltaCreate(TChecksum checksum, DeltaSearchMode searchMode)
 62    {
 63        _maxCandidatesPerPosition = GetCandidateLimit(searchMode);
 64        _checksum = checksum;
 65    }
 66
 67    /// <inheritdoc cref="IDeltaCreate.Create"/>
 68    public DeltaResult Create(ReadOnlySpan<byte> origin, ReadOnlySpan<byte> target)
 69        => CreateCore(origin, target, _maxCandidatesPerPosition);
 70
 71    /// <summary>Creates a patch using the selected search mode for this call only.</summary>
 72    /// <param name="origin">The original source bytes that will be available when applying the patch; may be empty.</pa
 73    /// <param name="target">The desired reconstructed bytes; may be empty.</param>
 74    /// <param name="searchMode">The search-effort policy for this call; does not change the encoder's default.</param>
 75    /// <returns>The encoded patch and the checksum of the target, rather than of the patch bytes.</returns>
 76    /// <remarks>The patch must be applied with the same format and checksum algorithm. Inputs are not modified.</remark
 77    /// <exception cref="ArgumentOutOfRangeException"><paramref name="searchMode"/> is not a defined search mode.</excep
 78    public DeltaResult Create(ReadOnlySpan<byte> origin, ReadOnlySpan<byte> target, DeltaSearchMode searchMode)
 79        => CreateCore(origin, target, GetCandidateLimit(searchMode));
 80
 81    private static int GetCandidateLimit(DeltaSearchMode searchMode) => searchMode switch
 82    {
 83        // Source spans cannot contain enough eight-byte blocks to reach this limit.
 84        DeltaSearchMode.Exhaustive => int.MaxValue,
 85        DeltaSearchMode.Bounded => BoundedCandidateLimit,
 86        _ => throw new ArgumentOutOfRangeException(nameof(searchMode), searchMode, "Unknown search mode.")
 87    };
 88
 89    private DeltaResult CreateCore(ReadOnlySpan<byte> origin, ReadOnlySpan<byte> target, int maxCandidatesPerPosition)
 90    {
 91        var writer = SizeHintConstructor is null
 92            ? new TWriter()
 93            : (TWriter)SizeHintConstructor.Invoke(new object[] { Math.Min(origin.Length / 2, target.Length) });
 94
 95        try
 96        {
 97            writer.WriteLength((ulong)target.Length);
 98            var checksum = _checksum.Checksum(target);
 99
 100            if (target.Length > MinEvaluateLength)
 101                WriteMatches(origin, target, maxCandidatesPerPosition, ref writer);
 102            else if (!target.IsEmpty)
 103                writer.WriteInsert(target);
 104
 105            writer.WriteChecksum(checksum);
 106            return new DeltaResult { Data = writer.GetOutput(), Crc32 = checksum };
 107        }
 108        finally
 109        {
 110            writer.Dispose();
 111        }
 112    }
 113
 114    private static void WriteMatches(ReadOnlySpan<byte> origin, ReadOnlySpan<byte> target,
 115        int maxCandidatesPerPosition, ref TWriter writer)
 116    {
 117#if NET9_0_OR_GREATER
 118        switch (Hashtable64.GetIndexWidth(origin.Length))
 119        {
 120            case 8:
 121                using (var table = new Hashtable64_8(origin))
 122                    EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer);
 123                break;
 124            case 16:
 125                using (var table = new Hashtable64_16(origin))
 126                    EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer);
 127                break;
 128#if DELTASHARP_HASHTABLE24
 129            case 24:
 130                using (var table = new Hashtable64_24(origin))
 131                    EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer);
 132                break;
 133#endif
 134            default:
 135                using (var table = new Hashtable64_32(origin))
 136                    EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer);
 137                break;
 138        }
 139#else
 140        using var table = new Hashtable64(origin);
 141        EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer);
 142#endif
 143    }
 144
 145#if NET9_0_OR_GREATER
 146    private static void EncodeMatches<TTable>(TTable hashtable, ReadOnlySpan<byte> origin,
 147        ReadOnlySpan<byte> target, int maxCandidatesPerPosition, ref TWriter writer)
 148        where TTable : IHashtable, allows ref struct
 149#else
 150    private static void EncodeMatches(Hashtable64 hashtable, ReadOnlySpan<byte> origin,
 151        ReadOnlySpan<byte> target, int maxCandidatesPerPosition, ref TWriter writer)
 152#endif
 153    {
 154        var unmatched = ReadOnlySpan<byte>.Empty;
 155        var unwritten = target;
 156        var next = target;
 157
 158        while (!next.IsEmpty)
 159        {
 160            if (next.Length < Hashtable64.BytesPerBlock)
 161                break;
 162
 163            var bestMatchStart = 0;
 164            var bestMatchLength = 0;
 165            var bestMatchedBackwards = 0;
 166
 167            var firstByte = next[0];
 168            var p = hashtable.Match(next);
 169            var candidatesRemaining = maxCandidatesPerPosition;
 170            while (p >= 0 && candidatesRemaining-- > 0)
 171            {
 172                // A hash collision can still extend backwards if even one byte matches forwards.
 173                if (origin[p] == firstByte)
 174                {
 175                    var matchedForward = SpanHelper.MatchForward(next, origin.Slice(p));
 176                    var matchedBackwards = !unmatched.IsEmpty && p > 0 && unmatched[unmatched.Length - 1] == origin[p - 
 177                        ? SpanHelper.MatchBackward(unmatched, origin.Slice(0, p))
 178                        : 0;
 179                    var matchedTotal = matchedForward + matchedBackwards;
 180                    if (matchedTotal > bestMatchLength)
 181                    {
 182                        //this match is the new best so far
 183                        bestMatchLength = matchedTotal;
 184                        bestMatchStart = p - matchedBackwards;
 185                        bestMatchedBackwards = matchedBackwards;
 186
 187                        if (matchedTotal == unwritten.Length)
 188                            break; //no need to continue search, we matched the whole target
 189                    }
 190                }
 191
 192
 193                p = hashtable.More(p);
 194            }
 195
 196            if (bestMatchLength > 8)
 197            {
 198                //a sensible limit for a copy command
 199                //short matches may end up being longer than insert commands when encoding
 200
 201                var insertLength = unmatched.Length - bestMatchedBackwards;
 202                if (insertLength>0)
 203                {
 204                    //insert unmatched bytes
 205                    writer.WriteInsert(unwritten.Slice(0, insertLength));
 206                }
 207
 208                //write copy
 209                writer.WriteCopy((ulong)bestMatchStart, (ulong)bestMatchLength);
 210
 211                unwritten = unwritten.Slice(insertLength + bestMatchLength);
 212
 213                next = unwritten;
 214                unmatched = ReadOnlySpan<byte>.Empty;
 215
 216            }
 217            else
 218            {
 219                unmatched = unwritten.Slice(0, unmatched.Length + 1);
 220                next = next.Slice(1);
 221            }
 222        }
 223
 224        if (unwritten.Length > 0)
 225            writer.WriteInsert(unwritten);
 226    }
 227}
 228
 229/// <summary>Contains the bytes produced by creating or applying a patch and the target checksum.</summary>
 230public class DeltaResult
 231{
 232    /// <summary>Gets or sets the encoded patch after creation, or the reconstructed target after application.</summary>
 233    /// <remarks>
 234    /// A read-only view does not make the backing storage immutable. When applying into caller-provided
 235    /// memory, this references the written portion of that memory. Built-in allocating overloads return
 236    /// newly allocated storage; custom writers determine the storage lifetime of their creation results.
 237    /// </remarks>
 238    public ReadOnlyMemory<byte> Data { get; set; }
 239
 240    /// <summary>Gets or sets the checksum of the reconstructed target, as computed by the configured checksum implement
 241    /// <remarks>
 242    /// The built-in formats use the Fossil additive checksum, not CRC-32. The property retains its
 243    /// historical name; custom checksum implementations may use a different algorithm.
 244    /// </remarks>
 245    public uint Crc32 { get; set; }
 246
 247}
 248
 249
 250/// <summary>Represents a delta creation failure using the legacy creation error codes.</summary>
 251/// <remarks>
 252/// Retained for API compatibility. The built-in encoder currently does not throw this type;
 253/// invalid search modes throw <see cref="ArgumentOutOfRangeException"/> and writer or checksum failures propagate.
 254/// </remarks>
 255public class DeltaCreateException : Exception
 256{
 257    /// <summary>Gets the creation error code supplied to the constructor.</summary>
 20258    public DeltaCreateExceptionError Error { get; private set; }
 259
 260    /// <summary>Initializes an exception with the specified legacy creation error code.</summary>
 261    /// <param name="error">The error code to report.</param>
 10262    public DeltaCreateException(DeltaCreateExceptionError error)
 263    {
 10264        Error = error;
 10265    }
 266
 267    /// <summary>Defines legacy creation error codes retained for API compatibility.</summary>
 268    public enum DeltaCreateExceptionError
 269    {
 270        /// <summary>Identifies an invalid delta representation.</summary>
 271        InvalidDelta,
 272        /// <summary>Identifies an invalid output length.</summary>
 273        InvalidOutputLength,
 274        /// <summary>Identifies output memory smaller than the required length.</summary>
 275        OutputMemorySizeLessThanRequired,
 276        /// <summary>Identifies an invalid literal insertion length.</summary>
 277        InvalidInsertLength,
 278        /// <summary>Identifies an invalid source position for a copy.</summary>
 279        InvalidCopyPosition,
 280        /// <summary>Identifies an invalid source copy length.</summary>
 281        InvalidCopyLength,
 282        /// <summary>Identifies an invalid checksum.</summary>
 283        InvalidChecksum,
 284
 285    }
 286}
 287