| | | 1 | | using DeltaSharp.Format; |
| | | 2 | | using System; |
| | | 3 | | using static DeltaSharp.DeltaApplyException; |
| | | 4 | | |
| | | 5 | | namespace DeltaSharp; |
| | | 6 | | |
| | | 7 | | /// <summary>Reconstructs target bytes from an original source and a patch in a supported format.</summary> |
| | | 8 | | public interface IDeltaApply |
| | | 9 | | { |
| | | 10 | | /// <summary>Applies a patch and validates the reconstructed target checksum.</summary> |
| | | 11 | | /// <param name="source">The original source bytes against which the patch was created.</param> |
| | | 12 | | /// <param name="delta">The encoded patch, including its output-length header and final checksum.</param> |
| | | 13 | | /// <returns>The reconstructed target in newly allocated memory and its verified checksum.</returns> |
| | | 14 | | /// <remarks> |
| | | 15 | | /// The built-in implementation allocates the length declared by the patch before validating all commands. |
| | | 16 | | /// Use <see cref="DeltaApplyExtensions.Apply"/> to impose an output-size limit. |
| | | 17 | | /// Processing stops at the first valid checksum command; trailing bytes are ignored. |
| | | 18 | | /// </remarks> |
| | | 19 | | /// <exception cref="DeltaApplyException">The patch structure, output length, source ranges, or checksum is invalid, |
| | | 20 | | /// <exception cref="DeltaReaderException">The format reader rejects malformed command syntax.</exception> |
| | | 21 | | DeltaResult Apply(ReadOnlySpan<byte> source, ReadOnlySpan<byte> delta); |
| | | 22 | | |
| | | 23 | | /// <summary>Applies a patch into caller-provided memory and validates the reconstructed target checksum.</summary> |
| | | 24 | | /// <param name="source">The original source bytes against which the patch was created.</param> |
| | | 25 | | /// <param name="delta">The encoded patch, including its output-length header and final checksum.</param> |
| | | 26 | | /// <param name="output">Writable memory at least as large as the declared target length.</param> |
| | | 27 | | /// <returns>A result whose data is the written prefix of <paramref name="output"/>, together with its verified chec |
| | | 28 | | /// <remarks> |
| | | 29 | | /// The result shares the caller's memory; subsequent changes to it affect the result. |
| | | 30 | | /// Bytes beyond the declared target length are left unchanged. Failure may leave partially written output. |
| | | 31 | | /// The built-in implementation supports overlapping source, patch, and output memory by copying overlapping inputs |
| | | 32 | | /// before writing. Processing stops at the first valid checksum command; trailing bytes are ignored. |
| | | 33 | | /// </remarks> |
| | | 34 | | /// <exception cref="DeltaApplyException">The output buffer is too small, or the patch structure, output length, sou |
| | | 35 | | /// <exception cref="DeltaReaderException">The format reader rejects malformed command syntax.</exception> |
| | | 36 | | DeltaResult Apply(ReadOnlySpan<byte> source, ReadOnlySpan<byte> delta, Memory<byte> output); |
| | | 37 | | |
| | | 38 | | /// <summary>Reads the target length declared in the first patch command without allocating an output buffer.</summa |
| | | 39 | | /// <param name="delta">The encoded patch beginning with an output-length header.</param> |
| | | 40 | | /// <returns>The declared target length in bytes, which may exceed supported allocation sizes.</returns> |
| | | 41 | | /// <remarks>This only checks the first command; it does not validate the remaining patch or its checksum.</remarks> |
| | | 42 | | /// <exception cref="DeltaApplyException">The patch does not start with a valid output-length command.</exception> |
| | | 43 | | /// <exception cref="DeltaReaderException">The format reader rejects malformed header syntax.</exception> |
| | | 44 | | ulong GetOutputLength(ReadOnlySpan<byte> delta); |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <summary>Applies patches using a configurable format reader and target checksum algorithm.</summary> |
| | | 48 | | /// <typeparam name="TReader">The command reader for the patch format, with a public parameterless constructor.</typepar |
| | | 49 | | /// <typeparam name="TChecksum">The checksum algorithm used when the patch was created, with a public parameterless cons |
| | | 50 | | /// <remarks>Reader and checksum instances are reused across calls; their implementations determine whether concurrent u |
| | | 51 | | public class DeltaApply<TReader, TChecksum> : IDeltaApply |
| | | 52 | | where TReader : IDeltaReader, new() |
| | | 53 | | where TChecksum : IDeltaChecksum, new() |
| | | 54 | | { |
| | | 55 | | TReader _reader; |
| | | 56 | | TChecksum _checksum; |
| | | 57 | | |
| | | 58 | | /// <summary>Initializes an applier with new reader and checksum instances.</summary> |
| | | 59 | | public DeltaApply() |
| | | 60 | | { |
| | | 61 | | _reader = new(); |
| | | 62 | | _checksum = new(); |
| | | 63 | | } |
| | | 64 | | |
| | | 65 | | /// <summary>Initializes an applier using the supplied reader and checksum instances.</summary> |
| | | 66 | | /// <param name="reader">The non-null reader used to decode commands; retained for subsequent calls.</param> |
| | | 67 | | /// <param name="checksum">The non-null checksum implementation; retained for subsequent calls.</param> |
| | | 68 | | public DeltaApply(TReader reader, TChecksum checksum) |
| | | 69 | | { |
| | | 70 | | _reader = reader; |
| | | 71 | | _checksum = checksum; |
| | | 72 | | } |
| | | 73 | | |
| | | 74 | | /// <inheritdoc cref="IDeltaApply.GetOutputLength"/> |
| | | 75 | | public ulong GetOutputLength(ReadOnlySpan<byte> delta) |
| | | 76 | | { |
| | | 77 | | if (!_reader.TryRead(delta, out var cmd, out var consumed)) |
| | | 78 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidDelta); |
| | | 79 | | |
| | | 80 | | if (cmd.Command != DeltaCommandEnum.Length || consumed == 0 || consumed > (uint)delta.Length) |
| | | 81 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidDelta); |
| | | 82 | | |
| | | 83 | | return cmd.Length; |
| | | 84 | | } |
| | | 85 | | |
| | | 86 | | /// <inheritdoc cref="IDeltaApply.Apply(ReadOnlySpan{byte}, ReadOnlySpan{byte}, Memory{byte})"/> |
| | | 87 | | public DeltaResult Apply(ReadOnlySpan<byte> source, ReadOnlySpan<byte> delta, Memory<byte> output) |
| | | 88 | | { |
| | | 89 | | var outputLength = GetOutputLength(delta); |
| | | 90 | | |
| | | 91 | | if (outputLength > int.MaxValue) |
| | | 92 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidOutputLength); |
| | | 93 | | |
| | | 94 | | if ((ulong)output.Length < outputLength) |
| | | 95 | | throw new DeltaApplyException(DeltaApplyExceptionError.OutputMemorySizeLessThanRequired); |
| | | 96 | | |
| | | 97 | | var destination = output.Span.Slice(0, (int)outputLength); |
| | | 98 | | // Preserve unread input when the caller reuses either input buffer. |
| | | 99 | | if (source.Overlaps(destination)) |
| | | 100 | | source = source.ToArray(); |
| | | 101 | | if (delta.Overlaps(destination)) |
| | | 102 | | delta = delta.ToArray(); |
| | | 103 | | |
| | | 104 | | var applyResult = Apply(source, delta, destination, out var checksum); |
| | | 105 | | |
| | | 106 | | return new DeltaResult() |
| | | 107 | | { |
| | | 108 | | Crc32 = checksum, |
| | | 109 | | Data = output.Slice(0,applyResult.Length) |
| | | 110 | | }; |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <inheritdoc cref="IDeltaApply.Apply(ReadOnlySpan{byte}, ReadOnlySpan{byte})"/> |
| | | 114 | | public DeltaResult Apply(ReadOnlySpan<byte> source, ReadOnlySpan<byte> delta) |
| | | 115 | | { |
| | | 116 | | var outputLength = GetOutputLength(delta); |
| | | 117 | | |
| | | 118 | | if (outputLength > int.MaxValue) |
| | | 119 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidOutputLength); |
| | | 120 | | |
| | | 121 | | #if NETSTANDARD2_0 |
| | | 122 | | var buffer = new byte[(int)outputLength]; |
| | | 123 | | #else |
| | | 124 | | var buffer = GC.AllocateUninitializedArray<byte>((int)outputLength); |
| | | 125 | | #endif |
| | | 126 | | |
| | | 127 | | var output = Apply(source, delta, buffer, out var checksum); |
| | | 128 | | |
| | | 129 | | return new DeltaResult() |
| | | 130 | | { |
| | | 131 | | Crc32 = checksum, |
| | | 132 | | Data = buffer |
| | | 133 | | }; |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | private Span<byte> Apply(ReadOnlySpan<byte> source, ReadOnlySpan<byte> delta, Span<byte> outputBuffer, out uint chec |
| | | 137 | | { |
| | | 138 | | var outputSpan = outputBuffer; |
| | | 139 | | var writeSpan = outputSpan; |
| | | 140 | | var hasLength = false; |
| | | 141 | | |
| | | 142 | | while (_reader.TryRead(delta, out var cmd, out var consumed)) |
| | | 143 | | { |
| | | 144 | | if (consumed == 0 || consumed > (uint)delta.Length || |
| | | 145 | | (!hasLength && cmd.Command != DeltaCommandEnum.Length)) |
| | | 146 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidDelta); |
| | | 147 | | |
| | | 148 | | switch (cmd.Command) |
| | | 149 | | { |
| | | 150 | | case DeltaCommandEnum.Length: |
| | | 151 | | { |
| | | 152 | | if (hasLength) |
| | | 153 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidDelta); |
| | | 154 | | |
| | | 155 | | if (cmd.Length != (ulong)outputBuffer.Length) |
| | | 156 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidOutputLength); |
| | | 157 | | |
| | | 158 | | hasLength = true; |
| | | 159 | | |
| | | 160 | | writeSpan = writeSpan.Slice(0, (int)cmd.Length); |
| | | 161 | | outputSpan = writeSpan; |
| | | 162 | | |
| | | 163 | | delta = delta.Slice((int)consumed); |
| | | 164 | | |
| | | 165 | | break; |
| | | 166 | | } |
| | | 167 | | case DeltaCommandEnum.Insert: |
| | | 168 | | { |
| | | 169 | | if (cmd.Length > (ulong)writeSpan.Length) |
| | | 170 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidInsertLength); |
| | | 171 | | |
| | | 172 | | delta = delta.Slice((int)consumed); |
| | | 173 | | |
| | | 174 | | // The declared insert length must not exceed the bytes actually |
| | | 175 | | // present in the (untrusted) delta tail, otherwise the Slice below |
| | | 176 | | // throws ArgumentOutOfRangeException on malformed input. |
| | | 177 | | if (cmd.Length > (ulong)delta.Length) |
| | | 178 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidInsertLength); |
| | | 179 | | |
| | | 180 | | var insertSlice = delta.Slice(0, (int)cmd.Length); |
| | | 181 | | |
| | | 182 | | insertSlice.CopyTo(writeSpan); |
| | | 183 | | |
| | | 184 | | delta = delta.Slice((int)cmd.Length); |
| | | 185 | | |
| | | 186 | | writeSpan = writeSpan.Slice((int)cmd.Length); |
| | | 187 | | |
| | | 188 | | break; |
| | | 189 | | } |
| | | 190 | | case DeltaCommandEnum.Copy: |
| | | 191 | | { |
| | | 192 | | if (cmd.Position > (ulong)source.Length) |
| | | 193 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidCopyPosition); |
| | | 194 | | |
| | | 195 | | if (cmd.Length > (ulong)writeSpan.Length) |
| | | 196 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidCopyLength); |
| | | 197 | | |
| | | 198 | | // Position alone being in range is not enough: the copied region |
| | | 199 | | // (Position + Length) must also stay within the source, otherwise |
| | | 200 | | // the Slice below reads past the source end on a crafted delta. |
| | | 201 | | // Compared in ulong space to avoid 32-bit overflow of the sum. |
| | | 202 | | if (cmd.Position + cmd.Length > (ulong)source.Length) |
| | | 203 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidCopyLength); |
| | | 204 | | |
| | | 205 | | delta = delta.Slice((int)consumed); |
| | | 206 | | |
| | | 207 | | var copySlice = source.Slice((int)cmd.Position, (int)cmd.Length); |
| | | 208 | | copySlice.CopyTo(writeSpan); |
| | | 209 | | |
| | | 210 | | writeSpan = writeSpan.Slice((int)cmd.Length); |
| | | 211 | | |
| | | 212 | | break; |
| | | 213 | | } |
| | | 214 | | case DeltaCommandEnum.Checksum: |
| | | 215 | | { |
| | | 216 | | // Every output byte must come from a copy or insert command. |
| | | 217 | | // A checksum of existing/uninitialized buffer contents is not enough. |
| | | 218 | | if (!writeSpan.IsEmpty) |
| | | 219 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidOutputLength); |
| | | 220 | | |
| | | 221 | | delta = delta.Slice((int)consumed); |
| | | 222 | | |
| | | 223 | | var deltaChecksum = cmd.Length; |
| | | 224 | | |
| | | 225 | | var outputChecksum = _checksum.Checksum(outputSpan); |
| | | 226 | | |
| | | 227 | | if (deltaChecksum != outputChecksum) |
| | | 228 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidChecksum); |
| | | 229 | | |
| | | 230 | | checksum = outputChecksum; |
| | | 231 | | |
| | | 232 | | return outputSpan; |
| | | 233 | | |
| | | 234 | | } |
| | | 235 | | default: |
| | | 236 | | throw new DeltaApplyException(DeltaApplyExceptionError.InvalidDelta); |
| | | 237 | | } |
| | | 238 | | } |
| | | 239 | | |
| | | 240 | | throw new DeltaApplyException(DeltaApplyExceptionError.IncompleteDelta); |
| | | 241 | | } |
| | | 242 | | |
| | | 243 | | |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | /// <summary>Reports a patch validation or output-size failure during delta application.</summary> |
| | | 247 | | /// <remarks>Inspect <see cref="Error"/> for the specific failure; command parsing may instead throw <see cref="DeltaRea |
| | | 248 | | public class DeltaApplyException : Exception |
| | | 249 | | { |
| | | 250 | | /// <summary>Gets the validation failure that caused the exception.</summary> |
| | 23450 | 251 | | public DeltaApplyExceptionError Error { get; private set; } |
| | | 252 | | |
| | | 253 | | /// <summary>Initializes an exception for the specified application failure.</summary> |
| | | 254 | | /// <param name="error">The validation failure to report.</param> |
| | 22380 | 255 | | public DeltaApplyException(DeltaApplyExceptionError error) |
| | | 256 | | { |
| | 22380 | 257 | | Error = error; |
| | 22380 | 258 | | } |
| | | 259 | | |
| | | 260 | | /// <summary>Identifies validation failures reported while applying a patch.</summary> |
| | | 261 | | public enum DeltaApplyExceptionError |
| | | 262 | | { |
| | | 263 | | /// <summary>The command stream has an invalid header, command order, command kind, or consumed-byte count.</sum |
| | | 264 | | InvalidDelta, |
| | | 265 | | /// <summary>The declared target length is unsupported or differs from the number of bytes reconstructed.</summa |
| | | 266 | | InvalidOutputLength, |
| | | 267 | | /// <summary>The caller-provided output memory is smaller than the declared target length.</summary> |
| | | 268 | | OutputMemorySizeLessThanRequired, |
| | | 269 | | /// <summary>An insert exceeds the remaining output space or available patch payload.</summary> |
| | | 270 | | InvalidInsertLength, |
| | | 271 | | /// <summary>A copy starts beyond the end of the original source.</summary> |
| | | 272 | | InvalidCopyPosition, |
| | | 273 | | /// <summary>A copy extends beyond the original source or remaining output space.</summary> |
| | | 274 | | InvalidCopyLength, |
| | | 275 | | /// <summary>The reconstructed target checksum differs from the checksum in the patch.</summary> |
| | | 276 | | InvalidChecksum, |
| | | 277 | | /// <summary>Reading stopped before a terminating checksum command was processed.</summary> |
| | | 278 | | IncompleteDelta, |
| | | 279 | | /// <summary>The declared target length exceeds the caller's output-size limit.</summary> |
| | | 280 | | OutputLengthLimitExceeded |
| | | 281 | | |
| | | 282 | | } |
| | | 283 | | } |