| | | 1 | | using System; |
| | | 2 | | using System.Buffers; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.IO; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Runtime.CompilerServices; |
| | | 7 | | using System.Text; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | |
| | | 11 | | namespace Jellyfin.Extensions |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Extension methods for the <see cref="Stream"/> class. |
| | | 15 | | /// </summary> |
| | | 16 | | public static class StreamExtensions |
| | | 17 | | { |
| | | 18 | | private const int StreamComparisonBufferSize = 81920; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Reads all lines in the <see cref="Stream" />. |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="stream">The <see cref="Stream" /> to read from.</param> |
| | | 24 | | /// <returns>All lines in the stream.</returns> |
| | | 25 | | public static string[] ReadAllLines(this Stream stream) |
| | 5 | 26 | | => ReadAllLines(stream, Encoding.UTF8); |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Reads all lines in the <see cref="Stream" />. |
| | | 30 | | /// </summary> |
| | | 31 | | /// <param name="stream">The <see cref="Stream" /> to read from.</param> |
| | | 32 | | /// <param name="encoding">The character encoding to use.</param> |
| | | 33 | | /// <returns>All lines in the stream.</returns> |
| | | 34 | | public static string[] ReadAllLines(this Stream stream, Encoding encoding) |
| | | 35 | | { |
| | 5 | 36 | | using StreamReader reader = new StreamReader(stream, encoding); |
| | 5 | 37 | | return ReadAllLines(reader).ToArray(); |
| | 5 | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Reads all lines in the <see cref="TextReader" />. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="reader">The <see cref="TextReader" /> to read from.</param> |
| | | 44 | | /// <returns>All lines in the stream.</returns> |
| | | 45 | | public static IEnumerable<string> ReadAllLines(this TextReader reader) |
| | | 46 | | { |
| | | 47 | | string? line; |
| | 72 | 48 | | while ((line = reader.ReadLine()) is not null) |
| | | 49 | | { |
| | 67 | 50 | | yield return line; |
| | | 51 | | } |
| | 5 | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <summary> |
| | | 55 | | /// Reads all lines in the <see cref="TextReader" />. |
| | | 56 | | /// </summary> |
| | | 57 | | /// <param name="reader">The <see cref="TextReader" /> to read from.</param> |
| | | 58 | | /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> |
| | | 59 | | /// <returns>All lines in the stream.</returns> |
| | | 60 | | public static async IAsyncEnumerable<string> ReadAllLinesAsync(this TextReader reader, [EnumeratorCancellation] |
| | | 61 | | { |
| | | 62 | | string? line; |
| | 31311 | 63 | | while ((line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false)) is not null) |
| | | 64 | | { |
| | 31248 | 65 | | yield return line; |
| | | 66 | | } |
| | 63 | 67 | | } |
| | | 68 | | |
| | | 69 | | /// <summary> |
| | | 70 | | /// Determines whether a stream is identical to a file on disk. |
| | | 71 | | /// </summary> |
| | | 72 | | /// <param name="stream">The stream to compare.</param> |
| | | 73 | | /// <param name="path">The file path to compare against.</param> |
| | | 74 | | /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> |
| | | 75 | | /// <returns>True if the stream and file are identical; otherwise false.</returns> |
| | | 76 | | /// <exception cref="ArgumentException"><paramref name="stream"/> does not support seeking.</exception> |
| | | 77 | | /// <remarks> |
| | | 78 | | /// The entire stream is compared against the file from the beginning (the position is reset to 0 on entry) |
| | | 79 | | /// and restored to its original value after the call. |
| | | 80 | | /// </remarks> |
| | | 81 | | public static async Task<bool> IsFileIdenticalAsync(this Stream stream, string path, CancellationToken cancellat |
| | | 82 | | { |
| | 5 | 83 | | ArgumentNullException.ThrowIfNull(stream); |
| | 5 | 84 | | ArgumentException.ThrowIfNullOrEmpty(path); |
| | | 85 | | |
| | 5 | 86 | | if (!stream.CanSeek) |
| | | 87 | | { |
| | 1 | 88 | | throw new ArgumentException("Stream must support seeking.", nameof(stream)); |
| | | 89 | | } |
| | | 90 | | |
| | 4 | 91 | | var originalPosition = stream.Position; |
| | | 92 | | try |
| | | 93 | | { |
| | 4 | 94 | | stream.Position = 0; |
| | | 95 | | |
| | 4 | 96 | | var existingFileStream = new FileStream( |
| | 4 | 97 | | path, |
| | 4 | 98 | | FileMode.Open, |
| | 4 | 99 | | FileAccess.Read, |
| | 4 | 100 | | FileShare.Read, |
| | 4 | 101 | | bufferSize: StreamComparisonBufferSize, |
| | 4 | 102 | | FileOptions.Asynchronous | FileOptions.SequentialScan); |
| | 4 | 103 | | await using (existingFileStream.ConfigureAwait(false)) |
| | | 104 | | { |
| | 4 | 105 | | return await stream.IsStreamIdenticalAsync(existingFileStream, cancellationToken).ConfigureAwait(fal |
| | | 106 | | } |
| | 0 | 107 | | } |
| | | 108 | | finally |
| | | 109 | | { |
| | 4 | 110 | | stream.Position = originalPosition; |
| | | 111 | | } |
| | 4 | 112 | | } |
| | | 113 | | |
| | | 114 | | /// <summary> |
| | | 115 | | /// Determines whether two streams are identical. |
| | | 116 | | /// </summary> |
| | | 117 | | /// <param name="a">The first stream to compare.</param> |
| | | 118 | | /// <param name="b">The second stream to compare.</param> |
| | | 119 | | /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> |
| | | 120 | | /// <returns>True if the streams are identical; otherwise false.</returns> |
| | | 121 | | /// <remarks> |
| | | 122 | | /// Seekable streams are compared from the beginning (their position is reset to 0 on entry). |
| | | 123 | | /// Non-seekable streams are compared from their current read position. Stream positions are not |
| | | 124 | | /// restored after the call. |
| | | 125 | | /// </remarks> |
| | | 126 | | public static async Task<bool> IsStreamIdenticalAsync(this Stream a, Stream b, CancellationToken cancellationTok |
| | | 127 | | { |
| | 16 | 128 | | ArgumentNullException.ThrowIfNull(a); |
| | 16 | 129 | | ArgumentNullException.ThrowIfNull(b); |
| | | 130 | | |
| | 16 | 131 | | if (ReferenceEquals(a, b)) |
| | | 132 | | { |
| | 0 | 133 | | return true; |
| | | 134 | | } |
| | | 135 | | |
| | 16 | 136 | | if (a.CanSeek is var aCanSeek && aCanSeek) |
| | | 137 | | { |
| | 12 | 138 | | a.Position = 0; |
| | | 139 | | } |
| | | 140 | | |
| | 16 | 141 | | if (b.CanSeek is var bCanSeek && bCanSeek) |
| | | 142 | | { |
| | 12 | 143 | | b.Position = 0; |
| | | 144 | | } |
| | | 145 | | |
| | 16 | 146 | | if (aCanSeek && bCanSeek && b.Length != a.Length) |
| | | 147 | | { |
| | 1 | 148 | | return false; |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | // MemoryStreams only unlock a fast path if their underlying buffer is exposed via TryGetBuffer. |
| | 15 | 152 | | var segmentA = a is MemoryStream streamA && streamA.TryGetBuffer(out var bufA) ? bufA : default; |
| | 15 | 153 | | var segmentB = b is MemoryStream streamB && streamB.TryGetBuffer(out var bufB) ? bufB : default; |
| | | 154 | | |
| | | 155 | | // Fast path A: both streams expose buffers, compare segments directly |
| | 15 | 156 | | if (segmentA.Array is not null && segmentB.Array is not null) |
| | | 157 | | { |
| | 1 | 158 | | return segmentA.AsSpan().SequenceEqual(segmentB.AsSpan()); |
| | | 159 | | } |
| | | 160 | | |
| | 14 | 161 | | if (segmentB.Array is not null) // && segmentA.Array is null guaranteed by previous check |
| | | 162 | | { |
| | | 163 | | // swap so that segmentA is the non-null one, compared to b we need only one fast path B |
| | 1 | 164 | | (segmentA, b) = (segmentB, a); |
| | | 165 | | } |
| | | 166 | | |
| | 14 | 167 | | if (segmentA.Array is not null) // either a was non-null, or b was non-null and was swapped there |
| | | 168 | | { |
| | | 169 | | // Fast path B: only one stream exposed a buffer, compare against the other chunk-by-chunk |
| | 4 | 170 | | var bufferB = ArrayPool<byte>.Shared.Rent(StreamComparisonBufferSize); |
| | | 171 | | try |
| | | 172 | | { |
| | 4 | 173 | | var memoryB = bufferB.AsMemory(); |
| | 4 | 174 | | int offset = 0; |
| | | 175 | | int bytesRead; |
| | 7 | 176 | | while ((bytesRead = await b.ReadAtLeastAsync(memoryB, memoryB.Length, throwOnEndOfStream: false, can |
| | | 177 | | { |
| | 4 | 178 | | if (offset + bytesRead > segmentA.Count || !segmentA.AsSpan(offset, bytesRead).SequenceEqual(mem |
| | | 179 | | { |
| | 1 | 180 | | return false; |
| | | 181 | | } |
| | | 182 | | |
| | 3 | 183 | | offset += bytesRead; |
| | | 184 | | } |
| | | 185 | | |
| | 3 | 186 | | return offset == segmentA.Count; |
| | | 187 | | } |
| | | 188 | | finally |
| | | 189 | | { |
| | 4 | 190 | | ArrayPool<byte>.Shared.Return(bufferB); |
| | | 191 | | } |
| | | 192 | | } |
| | | 193 | | else |
| | | 194 | | { |
| | 10 | 195 | | var bufferA = ArrayPool<byte>.Shared.Rent(StreamComparisonBufferSize); |
| | 10 | 196 | | var bufferB = ArrayPool<byte>.Shared.Rent(StreamComparisonBufferSize); |
| | | 197 | | try |
| | | 198 | | { |
| | 10 | 199 | | var memoryA = bufferA.AsMemory(); |
| | 10 | 200 | | var memoryB = bufferB.AsMemory(); |
| | 7 | 201 | | while (true) |
| | | 202 | | { |
| | 17 | 203 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 204 | | |
| | 17 | 205 | | var taskA = a.ReadAtLeastAsync(memoryA, memoryA.Length, throwOnEndOfStream: false, cancellationT |
| | 17 | 206 | | var taskB = b.ReadAtLeastAsync(memoryB, memoryB.Length, throwOnEndOfStream: false, cancellationT |
| | 17 | 207 | | await Task.WhenAll(taskA, taskB).ConfigureAwait(false); |
| | | 208 | | |
| | 17 | 209 | | var bytesReadA = await taskA.ConfigureAwait(false); |
| | 17 | 210 | | var bytesReadB = await taskB.ConfigureAwait(false); |
| | | 211 | | |
| | 17 | 212 | | if (bytesReadA != bytesReadB) |
| | | 213 | | { |
| | 1 | 214 | | return false; |
| | | 215 | | } |
| | | 216 | | |
| | 16 | 217 | | if (bytesReadA == 0) |
| | | 218 | | { |
| | 7 | 219 | | return true; |
| | | 220 | | } |
| | | 221 | | |
| | 9 | 222 | | if (!memoryA.Span[..bytesReadA].SequenceEqual(memoryB.Span[..bytesReadB])) |
| | | 223 | | { |
| | 2 | 224 | | return false; |
| | | 225 | | } |
| | 7 | 226 | | } |
| | | 227 | | } |
| | | 228 | | finally |
| | | 229 | | { |
| | 10 | 230 | | ArrayPool<byte>.Shared.Return(bufferA); |
| | 10 | 231 | | ArrayPool<byte>.Shared.Return(bufferB); |
| | | 232 | | } |
| | | 233 | | } |
| | 16 | 234 | | } |
| | | 235 | | } |
| | | 236 | | } |