| | | 1 | | using DeltaSharp.Format; |
| | | 2 | | using DeltaSharp.Util; |
| | | 3 | | using DeltaSharp.Util.Hashtable; |
| | | 4 | | using System; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.Numerics; |
| | | 8 | | using System.Runtime.CompilerServices; |
| | | 9 | | using System.Runtime.InteropServices; |
| | | 10 | | |
| | | 11 | | namespace DeltaSharp; |
| | | 12 | | |
| | | 13 | | /// <summary>Creates patches that reconstruct a target from an original source.</summary> |
| | | 14 | | public 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> |
| | | 33 | | public 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; |
| | 50 | 39 | | private static readonly System.Reflection.ConstructorInfo? SizeHintConstructor = |
| | 50 | 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> |
| | 80 | 47 | | public DeltaCreate() : this(new TChecksum(), DeltaSearchMode.Exhaustive) |
| | | 48 | | { |
| | 80 | 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> |
| | 10 | 53 | | public DeltaCreate(TChecksum checksum) : this(checksum, DeltaSearchMode.Exhaustive) |
| | | 54 | | { |
| | 10 | 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 |
| | 680 | 61 | | public DeltaCreate(TChecksum checksum, DeltaSearchMode searchMode) |
| | | 62 | | { |
| | 680 | 63 | | _maxCandidatesPerPosition = GetCandidateLimit(searchMode); |
| | 640 | 64 | | _checksum = checksum; |
| | 640 | 65 | | } |
| | | 66 | | |
| | | 67 | | /// <inheritdoc cref="IDeltaCreate.Create"/> |
| | | 68 | | public DeltaResult Create(ReadOnlySpan<byte> origin, ReadOnlySpan<byte> target) |
| | 8250 | 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) |
| | 20 | 79 | | => CreateCore(origin, target, GetCandidateLimit(searchMode)); |
| | | 80 | | |
| | 700 | 81 | | private static int GetCandidateLimit(DeltaSearchMode searchMode) => searchMode switch |
| | 700 | 82 | | { |
| | 700 | 83 | | // Source spans cannot contain enough eight-byte blocks to reach this limit. |
| | 550 | 84 | | DeltaSearchMode.Exhaustive => int.MaxValue, |
| | 100 | 85 | | DeltaSearchMode.Bounded => BoundedCandidateLimit, |
| | 50 | 86 | | _ => throw new ArgumentOutOfRangeException(nameof(searchMode), searchMode, "Unknown search mode.") |
| | 700 | 87 | | }; |
| | | 88 | | |
| | | 89 | | private DeltaResult CreateCore(ReadOnlySpan<byte> origin, ReadOnlySpan<byte> target, int maxCandidatesPerPosition) |
| | | 90 | | { |
| | 8260 | 91 | | var writer = SizeHintConstructor is null |
| | 8260 | 92 | | ? new TWriter() |
| | 8260 | 93 | | : (TWriter)SizeHintConstructor.Invoke(new object[] { Math.Min(origin.Length / 2, target.Length) }); |
| | | 94 | | |
| | | 95 | | try |
| | | 96 | | { |
| | 8260 | 97 | | writer.WriteLength((ulong)target.Length); |
| | 8260 | 98 | | var checksum = _checksum.Checksum(target); |
| | | 99 | | |
| | 8260 | 100 | | if (target.Length > MinEvaluateLength) |
| | 6840 | 101 | | WriteMatches(origin, target, maxCandidatesPerPosition, ref writer); |
| | 1420 | 102 | | else if (!target.IsEmpty) |
| | 790 | 103 | | writer.WriteInsert(target); |
| | | 104 | | |
| | 8260 | 105 | | writer.WriteChecksum(checksum); |
| | 8260 | 106 | | return new DeltaResult { Data = writer.GetOutput(), Crc32 = checksum }; |
| | | 107 | | } |
| | | 108 | | finally |
| | | 109 | | { |
| | 8260 | 110 | | writer.Dispose(); |
| | 8260 | 111 | | } |
| | 8260 | 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 |
| | 4104 | 118 | | switch (Hashtable64.GetIndexWidth(origin.Length)) |
| | | 119 | | { |
| | | 120 | | case 8: |
| | 2328 | 121 | | using (var table = new Hashtable64_8(origin)) |
| | 2328 | 122 | | EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer); |
| | | 123 | | break; |
| | | 124 | | case 16: |
| | 1740 | 125 | | using (var table = new Hashtable64_16(origin)) |
| | 1740 | 126 | | EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer); |
| | | 127 | | break; |
| | | 128 | | #if DELTASHARP_HASHTABLE24 |
| | | 129 | | case 24: |
| | 18 | 130 | | using (var table = new Hashtable64_24(origin)) |
| | 18 | 131 | | EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer); |
| | | 132 | | break; |
| | | 133 | | #endif |
| | | 134 | | default: |
| | 18 | 135 | | using (var table = new Hashtable64_32(origin)) |
| | 18 | 136 | | EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer); |
| | | 137 | | break; |
| | | 138 | | } |
| | | 139 | | #else |
| | 2736 | 140 | | using var table = new Hashtable64(origin); |
| | 2736 | 141 | | EncodeMatches(table, origin, target, maxCandidatesPerPosition, ref writer); |
| | | 142 | | #endif |
| | 9576 | 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 | | { |
| | 6840 | 154 | | var unmatched = ReadOnlySpan<byte>.Empty; |
| | 6840 | 155 | | var unwritten = target; |
| | 6840 | 156 | | var next = target; |
| | | 157 | | |
| | 5048900 | 158 | | while (!next.IsEmpty) |
| | | 159 | | { |
| | 5043920 | 160 | | if (next.Length < Hashtable64.BytesPerBlock) |
| | | 161 | | break; |
| | | 162 | | |
| | 5042060 | 163 | | var bestMatchStart = 0; |
| | 5042060 | 164 | | var bestMatchLength = 0; |
| | 5042060 | 165 | | var bestMatchedBackwards = 0; |
| | | 166 | | |
| | 5042060 | 167 | | var firstByte = next[0]; |
| | 5042060 | 168 | | var p = hashtable.Match(next); |
| | 5042060 | 169 | | var candidatesRemaining = maxCandidatesPerPosition; |
| | 265351290 | 170 | | while (p >= 0 && candidatesRemaining-- > 0) |
| | | 171 | | { |
| | | 172 | | // A hash collision can still extend backwards if even one byte matches forwards. |
| | 260311030 | 173 | | if (origin[p] == firstByte) |
| | | 174 | | { |
| | 256924260 | 175 | | var matchedForward = SpanHelper.MatchForward(next, origin.Slice(p)); |
| | 256924260 | 176 | | var matchedBackwards = !unmatched.IsEmpty && p > 0 && unmatched[unmatched.Length - 1] == origin[p - |
| | 256924260 | 177 | | ? SpanHelper.MatchBackward(unmatched, origin.Slice(0, p)) |
| | 256924260 | 178 | | : 0; |
| | 256924260 | 179 | | var matchedTotal = matchedForward + matchedBackwards; |
| | 256924260 | 180 | | if (matchedTotal > bestMatchLength) |
| | | 181 | | { |
| | | 182 | | //this match is the new best so far |
| | 1211050 | 183 | | bestMatchLength = matchedTotal; |
| | 1211050 | 184 | | bestMatchStart = p - matchedBackwards; |
| | 1211050 | 185 | | bestMatchedBackwards = matchedBackwards; |
| | | 186 | | |
| | 1211050 | 187 | | if (matchedTotal == unwritten.Length) |
| | | 188 | | break; //no need to continue search, we matched the whole target |
| | | 189 | | } |
| | | 190 | | } |
| | | 191 | | |
| | | 192 | | |
| | 260309230 | 193 | | p = hashtable.More(p); |
| | | 194 | | } |
| | | 195 | | |
| | 5042060 | 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 | | |
| | 202060 | 201 | | var insertLength = unmatched.Length - bestMatchedBackwards; |
| | 202060 | 202 | | if (insertLength>0) |
| | | 203 | | { |
| | | 204 | | //insert unmatched bytes |
| | 187000 | 205 | | writer.WriteInsert(unwritten.Slice(0, insertLength)); |
| | | 206 | | } |
| | | 207 | | |
| | | 208 | | //write copy |
| | 202060 | 209 | | writer.WriteCopy((ulong)bestMatchStart, (ulong)bestMatchLength); |
| | | 210 | | |
| | 202060 | 211 | | unwritten = unwritten.Slice(insertLength + bestMatchLength); |
| | | 212 | | |
| | 202060 | 213 | | next = unwritten; |
| | 202060 | 214 | | unmatched = ReadOnlySpan<byte>.Empty; |
| | | 215 | | |
| | | 216 | | } |
| | | 217 | | else |
| | | 218 | | { |
| | 4840000 | 219 | | unmatched = unwritten.Slice(0, unmatched.Length + 1); |
| | 4840000 | 220 | | next = next.Slice(1); |
| | | 221 | | } |
| | | 222 | | } |
| | | 223 | | |
| | 6840 | 224 | | if (unwritten.Length > 0) |
| | 1860 | 225 | | writer.WriteInsert(unwritten); |
| | 6840 | 226 | | } |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | /// <summary>Contains the bytes produced by creating or applying a patch and the target checksum.</summary> |
| | | 230 | | public 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> |
| | | 255 | | public class DeltaCreateException : Exception |
| | | 256 | | { |
| | | 257 | | /// <summary>Gets the creation error code supplied to the constructor.</summary> |
| | | 258 | | 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> |
| | | 262 | | public DeltaCreateException(DeltaCreateExceptionError error) |
| | | 263 | | { |
| | | 264 | | Error = error; |
| | | 265 | | } |
| | | 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 | | |