team-ljyzipelo

공개
464줄23 KB
1using System.Formats.Tar;
2using System.Security.Cryptography;
3using System.Text;
4using Zipelo.Core;
5using Zipelo.Worker.Tar;
6
7var tests = new List<(string Name, Func<Task> Run)>();
8var normal = Fixtures.Archive(new Fixture("folder/", [], '5'), new Fixture("folder/a.txt", "alpha"u8.ToArray()),
9 new Fixture("empty", []), new Fixture("b.bin", Enumerable.Range(0, 140000).Select(i => (byte)i).ToArray()));
10var defaults = new UstarLimits(new JobLimits(1024, 128L << 20, 16L << 20, TimeSpan.FromSeconds(15), 1), 16L << 20, 1L << 20);
11
12tests.Add(("list", async () =>
13{
14 using var source = new MemoryStream(normal, false);
15 using var sink = new HashSink();
16 var result = await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => [], sink.Write, default);
17 Check(result.Entries.Count == 4 && result.Entries[0].Name == "folder" && result.Usage.Entries == 4);
18 Check(result.Usage.ProcessedBytes == normal.Length && result.Usage.OutputBytes == 0 && sink.Calls == 0);
19 Check(result.ContentVerification == VerificationState.Unavailable);
20 Check(result.InputSha256 == Convert.ToHexString(SHA256.HashData(normal)) && source.CanRead);
21}));
22tests.Add(("selected.hash.chunks", async () =>
23{
24 using var source = new FragmentedStream(normal);
25 using var sink = new HashSink();
26 var result = await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => ["2", "3"], sink.Write, default);
27 Check(sink.Counts["2"] == 0 && sink.Counts["3"] == 140000 && !sink.Counts.ContainsKey("1"));
28 Check(sink.Digest("3") == Convert.ToHexString(SHA256.HashData(Enumerable.Range(0, 140000).Select(i => (byte)i).ToArray())));
29 Check(sink.MaxChunk == UstarReader.ChunkSize && result.Usage.ProcessedBytes == normal.Length * 2L);
30 Check(result.Usage.OutputBytes == 140000 && result.Usage.Entries == 4);
31}));
32tests.Add(("bcl.ustar.prefix", async () =>
33{
34 using var archive = new MemoryStream();
35 var prefix = new string('p', 80) + "/" + new string('q', 60);
36 using (var writer = new TarWriter(archive, TarEntryFormat.Ustar, leaveOpen: true))
37 {
38 var entry = new UstarTarEntry(TarEntryType.RegularFile, prefix + "/a") { DataStream = new MemoryStream("ok"u8.ToArray()) };
39 writer.WriteEntry(entry);
40 }
41 using var sink = new HashSink();
42 var result = await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(archive, _ => ["0"], sink.Write, default);
43 Check(result.Entries[0].Name == prefix + "/a" && sink.Counts["0"] == 2);
44}));
45tests.Add(("empty.archive", async () => { await Run(new byte[1024]); }));
46tests.Add(("zero.trailing.blocks", async () => { await Run([.. normal, .. new byte[1024]]); }));
47tests.Add(("directory.after.child", async () => { await Run(Fixtures.Archive(new Fixture("a/b", []), new Fixture("a/", [], '5'))); }));
48tests.Add(("linux.case.distinct", async () => { await Run(Fixtures.Archive(new Fixture("A", []), new Fixture("a", []))); }));
49tests.Add(("header.checksum.not.content", async () =>
50{
51 var bytes = Fixtures.Archive(new Fixture("a", "one"u8.ToArray()));
52 bytes[512] ^= 1;
53 var result = await Run(bytes);
54 Check(result.ContentVerification == VerificationState.Unavailable);
55}));
56
57Reject("checksum", Mutate(normal, 0, 1), ArchiveError.IntegrityFailure, checksum: false);
58Reject("truncated.header", normal[..511], ArchiveError.IntegrityFailure, checksum: false);
59Reject("truncated.body", Fixtures.Archive(new Fixture("a", new byte[1024]))[..1024], ArchiveError.IntegrityFailure, checksum: false);
60Reject("end.missing", Fixtures.Archive(new Fixture("a", []))[..512], ArchiveError.IntegrityFailure, checksum: false);
61Reject("end.single", Fixtures.Archive(new Fixture("a", []))[..1024], ArchiveError.IntegrityFailure, checksum: false);
62Reject("end.second.nonzero", Mutate(new byte[1024], 512, 1), ArchiveError.IntegrityFailure, checksum: false);
63Reject("trailing.nonzero", [.. normal, .. Enumerable.Repeat((byte)1, 512)], ArchiveError.IntegrityFailure, checksum: false);
64Reject("trailing.partial", [.. normal, (byte)0], ArchiveError.IntegrityFailure, checksum: false);
65Reject("padding.nonzero", Mutate(Fixtures.Archive(new Fixture("a", [1])), 513, 1), ArchiveError.IntegrityFailure, checksum: false);
66Reject("size.huge.octal", Field(Fixtures.Archive(new Fixture("a", [])), 124, "77777777777\0"), ArchiveError.IntegrityFailure);
67RejectSizeEncoding("size.base256", [0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], []);
68RejectSizeEncoding("size.negative", Encoding.ASCII.GetBytes("-0000000000\0"), []);
69RejectSizeEncoding("size.invalid.digit", Encoding.ASCII.GetBytes("00000000008\0"), new byte[8]);
70RejectSizeEncoding("size.internal.terminator", Encoding.ASCII.GetBytes("000000000\0" + "1\0"), new byte[1]);
71Reject("directory.nonzero", Field(normal, 124, "00000000001\0"), ArchiveError.IntegrityFailure);
72Reject("version", Mutate(normal, 264, (byte)'1'), ArchiveError.UnsupportedEntry);
73Reject("gnu.magic", Mutate(normal, 262, (byte)' '), ArchiveError.UnsupportedEntry);
74Reject("linkname.on.file", Mutate(Fixtures.Archive(new Fixture("a", [])), 157, (byte)'x'), ArchiveError.IntegrityFailure);
75Reject("reserved.bytes", Mutate(normal, 500, 1), ArchiveError.IntegrityFailure);
76Reject("name.hidden.after.nul", Mutate(Fixtures.Archive(new Fixture("a", [])), 2, (byte)'b'), ArchiveError.IntegrityFailure);
77Reject("invalid.utf8", Mutate(Fixtures.Archive(new Fixture("a", [])), 0, 255), ArchiveError.IntegrityFailure);
78foreach (var type in new[] { 'x', 'g', 'L', 'K', 'S', '1', '2', '3', '4', '6', '7', 'V', '?' })
79{
80 Reject("type." + type, Fixtures.Archive(new Fixture("a", [], type)), ArchiveError.UnsupportedEntry);
81}
82foreach (var name in new[] { "../a", "/root", "a//b", "a/./b", "a/../b", "a\\b", "" })
83{
84 Reject("path." + name, Fixtures.Archive(new Fixture(name, [])), name.Length == 0 ? ArchiveError.IntegrityFailure : ArchiveError.UnsafePath);
85}
86foreach (var entries in new[]
87{
88 new[] { new Fixture("a", []), new Fixture("a", []) },
89 new[] { new Fixture("a/", [], '5'), new Fixture("a", []) },
90 new[] { new Fixture("a", []), new Fixture("a/b", []) },
91 new[] { new Fixture("a/b", []), new Fixture("a", []) }
92})
93{
94 Reject("collision." + tests.Count, Fixtures.Archive(entries), ArchiveError.OutputConflict);
95}
96Reject("windows.case.collision", Fixtures.Archive(new Fixture("A", []), new Fixture("a", [])), ArchiveError.OutputConflict, policy: FileNamePolicy.Windows);
97Reject("windows.device", Fixtures.Archive(new Fixture("CON.txt", [])), ArchiveError.UnsafePath, policy: FileNamePolicy.Windows);
98Reject("windows.drive", Fixtures.Archive(new Fixture("C:/a", [])), ArchiveError.UnsafePath, policy: FileNamePolicy.Windows);
99Reject("unselected.unsafe", Fixtures.Archive(new Fixture("ok", [1]), new Fixture("../bad", [])), ArchiveError.UnsafePath, selection: _ => ["0"]);
100Reject("input.limit", normal, ArchiveError.BudgetExceeded, limits: defaults with { MaxInputBytes = normal.Length - 1 });
101Reject("entries.limit", normal, ArchiveError.BudgetExceeded, limits: defaults with { Job = defaults.Job with { MaxEntries = 3 } });
102Reject("metadata.limit", normal, ArchiveError.BudgetExceeded, limits: defaults with { MaxMetadataBytes = 2047 });
103Reject("processed.first.pass", normal, ArchiveError.BudgetExceeded, limits: defaults with { Job = defaults.Job with { MaxProcessedBytes = normal.Length - 1 } });
104Reject("processed.second.pass.cumulative", normal, ArchiveError.BudgetExceeded,
105 limits: defaults with { Job = defaults.Job with { MaxProcessedBytes = normal.Length * 2L - 1 } }, expectNoOutput: false);
106Reject("output.limit", normal, ArchiveError.BudgetExceeded, limits: defaults with { Job = defaults.Job with { MaxOutputBytes = 4 } });
107Reject("entries.hard.cap", Fixtures.Archive(Enumerable.Range(0, 1025).Select(i => new Fixture("f" + i, [])).ToArray()),
108 ArchiveError.BudgetExceeded, limits: defaults with { Job = defaults.Job with { MaxEntries = long.MaxValue } });
109Reject("input.hard.cap", new byte[(16 << 20) + 512], ArchiveError.BudgetExceeded,
110 limits: defaults with { MaxInputBytes = long.MaxValue });
111Reject("selection.duplicate", normal, ArchiveError.UnsupportedEntry, selection: _ => ["1", "1"]);
112Reject("selection.unknown", normal, ArchiveError.UnsupportedEntry, selection: _ => ["99"]);
113
114tests.Add(("cancel.before.read", async () =>
115{
116 using var cts = new CancellationTokenSource();
117 cts.Cancel();
118 await Cancelled(() => Run(normal, token: cts.Token));
119}));
120tests.Add(("cancel.during.read", async () =>
121{
122 using var cts = new CancellationTokenSource();
123 using var source = new FragmentedStream(normal, () => cts.Cancel());
124 using var sink = new HashSink();
125 await Cancelled(() => new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => [], sink.Write, cts.Token));
126 Check(sink.Calls == 0);
127}));
128tests.Add(("cancel.sink", async () =>
129{
130 using var cts = new CancellationTokenSource();
131 using var source = new MemoryStream(normal, false);
132 await Cancelled(() => new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => ["3"], (_, _, _) =>
133 {
134 cts.Cancel();
135 return ValueTask.CompletedTask;
136 }, cts.Token));
137}));
138tests.Add(("duration.cumulative", async () =>
139{
140 var time = new TestTime();
141 using var source = new MemoryStream(normal, false);
142 using var sink = new HashSink();
143 await Error(ArchiveError.BudgetExceeded, () => new UstarReader(defaults, FileNamePolicy.Linux, time).ReadAsync(source, _ =>
144 {
145 time.Ticks = TimeSpan.FromSeconds(15).Ticks;
146 return ["1"];
147 }, sink.Write, default));
148 Check(sink.Calls == 0);
149}));
150tests.Add(("input.changed.between.passes", async () =>
151{
152 var bytes = Fixtures.Archive(new Fixture("a", "old"u8.ToArray()));
153 using var source = new MemoryStream(bytes, false);
154 using var sink = new HashSink();
155 await Error(ArchiveError.IntegrityFailure, () => new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ =>
156 {
157 bytes[512] ^= 1;
158 return ["0"];
159 }, sink.Write, default));
160 Check(sink.Calls > 0);
161}));
162tests.Add(("input.unselected.changed", async () =>
163{
164 var bytes = Fixtures.Archive(new Fixture("a", [1]), new Fixture("b", [2]));
165 using var source = new MemoryStream(bytes, false);
166 using var sink = new HashSink();
167 await Error(ArchiveError.IntegrityFailure, () => new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ =>
168 {
169 bytes[1536] ^= 1;
170 return ["0"];
171 }, sink.Write, default));
172}));
173tests.Add(("single.use", async () =>
174{
175 var reader = new UstarReader(defaults, FileNamePolicy.Linux);
176 using var source = new MemoryStream(normal, false);
177 using var sink = new HashSink();
178 await reader.ReadAsync(source, _ => [], sink.Write, default);
179 try { await reader.ReadAsync(source, _ => [], sink.Write, default); }
180 catch (InvalidOperationException) { return; }
181 throw new Exception("Reuse accepted.");
182}));
183
184tests.Add(("metadata.exact.boundary", async () =>
185{
186 using var source = new MemoryStream(normal, false);
187 using var sink = new HashSink();
188 var result = await new UstarReader(defaults with { MaxMetadataBytes = 2048 }, FileNamePolicy.Linux)
189 .ReadAsync(source, _ => ["0"], sink.Write, default);
190 Check(result.Entries.Count == 4 && sink.Calls == 0);
191}));
192tests.Add(("input.limit.exact", async () =>
193{
194 using var source = new MemoryStream(normal, false);
195 using var sink = new HashSink();
196 await new UstarReader(defaults with { MaxInputBytes = normal.Length }, FileNamePolicy.Linux)
197 .ReadAsync(source, _ => [], sink.Write, default);
198}));
199tests.Add(("sink.failure.propagates", async () =>
200{
201 using var source = new MemoryStream(normal, false);
202 var expected = new IOException("Test sink failure.");
203 try
204 {
205 await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => ["1"],
206 (_, _, _) => throw expected, default);
207 }
208 catch (IOException error) when (ReferenceEquals(error, expected)) { Check(source.CanRead); return; }
209 throw new Exception("Sink failure suppressed.");
210}));
211tests.Add(("nonseekable.rejected", async () =>
212{
213 using var source = new NonSeekableStream(normal);
214 using var sink = new HashSink();
215 try { await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => [], sink.Write, default); }
216 catch (ArgumentException) { Check(sink.Calls == 0); return; }
217 throw new Exception("Nonseekable input accepted.");
218}));
219tests.Add(("invalid.limits", () =>
220{
221 foreach (var limits in new[]
222 {
223 defaults with { MaxMetadataBytes = 0 }, defaults with { MaxInputBytes = 0 },
224 defaults with { Job = defaults.Job with { MaxEntries = 0 } },
225 defaults with { Job = defaults.Job with { MaxDuration = TimeSpan.Zero } }
226 })
227 {
228 try { _ = new UstarReader(limits, FileNamePolicy.Linux); }
229 catch (ArgumentOutOfRangeException) { continue; }
230 throw new Exception("Invalid limits accepted.");
231 }
232 return Task.CompletedTask;
233}));
234
235var longPrefix = new string('p', 70) + "/" + new string('q', 70);
236var longLeaf = new string('a', 80);
237foreach (var policy in new[] { FileNamePolicy.Linux, FileNamePolicy.Windows })
238{
239 Reject("long.exact." + policy, Fixtures.Archive(
240 new Fixture(longLeaf, [], Prefix: longPrefix), new Fixture(longLeaf, [], Prefix: longPrefix)),
241 ArchiveError.OutputConflict, policy: policy);
242 Reject("long.parent.first." + policy, Fixtures.Archive(
243 new Fixture(longLeaf, [], Prefix: longPrefix), new Fixture(longLeaf + "/child", [], Prefix: longPrefix)),
244 ArchiveError.OutputConflict, policy: policy);
245 Reject("long.child.first." + policy, Fixtures.Archive(
246 new Fixture(longLeaf + "/child", [], Prefix: longPrefix), new Fixture(longLeaf, [], Prefix: longPrefix)),
247 ArchiveError.OutputConflict, policy: policy);
248 Reject("long.directory.file.same." + policy, Fixtures.Archive(
249 new Fixture(longLeaf + "/", [], '5', longPrefix), new Fixture(longLeaf, [], Prefix: longPrefix)),
250 ArchiveError.OutputConflict, policy: policy);
251 foreach (var reverse in new[] { false, true })
252 {
253 tests.Add(($"long.siblings.directories.{policy}.{reverse}", async () =>
254 {
255 var entries = new[]
256 {
257 new Fixture(longLeaf, [1], Prefix: longPrefix),
258 new Fixture(longLeaf + "x", [2], Prefix: longPrefix),
259 new Fixture(longLeaf + "-dir/", [], '5', longPrefix),
260 new Fixture(longLeaf + "-dir/child", [3], Prefix: longPrefix)
261 };
262 if (reverse) { Array.Reverse(entries); }
263 using var source = new MemoryStream(Fixtures.Archive(entries), false);
264 using var sink = new HashSink();
265 var result = await new UstarReader(defaults, policy).ReadAsync(source,
266 listed => listed.Select(e => e.Id).ToArray(), sink.Write, default);
267 Check(result.Entries.Count == 4 && result.Usage.OutputBytes == 3 && sink.Counts.Count == 3);
268 }));
269 }
270 tests.Add(("long.maximum.siblings." + policy, async () =>
271 {
272 var entries = Enumerable.Range(0, 1024).Select(i =>
273 new Fixture(longLeaf + i.ToString("D4", System.Globalization.CultureInfo.InvariantCulture), [(byte)i], Prefix: longPrefix)).ToArray();
274 using var source = new MemoryStream(Fixtures.Archive(entries), false);
275 using var sink = new HashSink();
276 var result = await new UstarReader(defaults, policy).ReadAsync(source, _ => ["1023"], sink.Write, default);
277 Check(result.Entries.Count == 1024 && result.Usage.Entries == 1024 && result.Usage.OutputBytes == 1);
278 Check(result.Usage.ProcessedBytes == source.Length * 2 && sink.Counts.Count == 1 && sink.Counts["1023"] == 1);
279 Check(sink.Digest("1023") == Convert.ToHexString(SHA256.HashData(new byte[] { 255 })));
280 }));
281}
282foreach (var childFirst in new[] { false, true })
283{
284 var entries = new[]
285 {
286 new Fixture(longLeaf.ToUpperInvariant(), [], Prefix: longPrefix.ToUpperInvariant()),
287 new Fixture(longLeaf + "/child", [], Prefix: longPrefix)
288 };
289 if (childFirst) { Array.Reverse(entries); }
290 var bytes = Fixtures.Archive(entries);
291 Reject("long.case.parent.windows." + childFirst, bytes, ArchiveError.OutputConflict, policy: FileNamePolicy.Windows);
292 tests.Add(("long.case.parent.linux." + childFirst, async () => { await Run(bytes); }));
293}
294var caseNames = Fixtures.Archive(
295 new Fixture(longLeaf, [], Prefix: longPrefix),
296 new Fixture(longLeaf.ToUpperInvariant(), [], Prefix: longPrefix.ToUpperInvariant()));
297Reject("long.case.exact.windows", caseNames, ArchiveError.OutputConflict, policy: FileNamePolicy.Windows);
298tests.Add(("long.case.exact.linux", async () => { await Run(caseNames); }));
299
300var failures = 0;
301foreach (var test in tests)
302{
303 try { await test.Run(); Console.WriteLine("PASS " + test.Name); }
304 catch (Exception error) { failures++; Console.WriteLine("FAIL " + test.Name + " " + error); }
305}
306Console.WriteLine($"total={tests.Count} failed={failures}");
307return failures == 0 ? 0 : 1;
308
309void Reject(string name, byte[] bytes, ArchiveError code, bool checksum = true, UstarLimits? limits = null,
310 FileNamePolicy policy = FileNamePolicy.Linux, Func<IReadOnlyList<ArchiveEntry>, IReadOnlyCollection<string>>? selection = null,
311 bool expectNoOutput = true)
312{
313 if (checksum && bytes.Length >= 512) { Fixtures.Checksum(bytes.AsSpan(0, 512)); }
314 tests.Add((name, async () =>
315 {
316 using var source = new MemoryStream(bytes, false);
317 using var sink = new HashSink();
318 await Error(code, () => new UstarReader(limits ?? defaults, policy).ReadAsync(source,
319 selection ?? (entries => entries.Where(e => e.Kind == EntryKind.File).Select(e => e.Id).ToArray()), sink.Write, default));
320 if (expectNoOutput) { Check(sink.Calls == 0); }
321 }));
322}
323
324void RejectSizeEncoding(string name, byte[] size, byte[] data)
325{
326 Check(size.Length == 12);
327 var valid = Fixtures.Archive(new Fixture("number.bin", data));
328 tests.Add((name + ".valid", async () =>
329 {
330 using var source = new MemoryStream(valid, false);
331 using var sink = new HashSink();
332 var result = await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => ["0"], sink.Write, default);
333 Check(result.Entries.Count == 1 && result.Entries[0].Kind == EntryKind.File);
334 Check(result.Entries[0].DeclaredSize == data.LongLength && sink.Counts["0"] == data.LongLength);
335 Check(sink.Digest("0") == Convert.ToHexString(SHA256.HashData(data)));
336 }));
337 // size 이외의 구조는 정상 대조군과 같으며 헤더 체크섬만 다시 계산함.
338 var invalid = (byte[])valid.Clone();
339 size.CopyTo(invalid, 124);
340 Reject(name, invalid, ArchiveError.IntegrityFailure);
341}
342
343async Task<UstarResult> Run(byte[] bytes, CancellationToken token = default)
344{
345 using var source = new MemoryStream(bytes, false);
346 using var sink = new HashSink();
347 return await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => [], sink.Write, token);
348}
349
350static async Task Error(ArchiveError expected, Func<Task> action)
351{
352 try { await action(); }
353 catch (ArchiveException error) when (error.Code == expected) { return; }
354 throw new Exception("Expected " + expected);
355}
356
357static async Task Cancelled(Func<Task> action)
358{
359 try { await action(); }
360 catch (OperationCanceledException) { return; }
361 throw new Exception("Expected cancellation.");
362}
363
364static void Check(bool condition) { if (!condition) { throw new Exception("Assertion failed."); } }
365static byte[] Mutate(byte[] bytes, int index, byte value) { var copy = (byte[])bytes.Clone(); copy[index] = value; return copy; }
366static byte[] Field(byte[] bytes, int offset, string value)
367{
368 var copy = (byte[])bytes.Clone();
369 Encoding.ASCII.GetBytes(value).CopyTo(copy, offset);
370 return copy;
371}
372
373internal sealed record Fixture(string Name, byte[] Data, char Type = '0', string Prefix = "");
374
375internal static class Fixtures
376{
377 internal static byte[] Archive(params Fixture[] entries)
378 {
379 using var stream = new MemoryStream();
380 foreach (var entry in entries)
381 {
382 var header = new byte[512];
383 var name = Encoding.UTF8.GetBytes(entry.Name);
384 var prefix = Encoding.UTF8.GetBytes(entry.Prefix);
385 if (name.Length > 100 || prefix.Length > 155) { throw new ArgumentException("Fixture name too long."); }
386 name.CopyTo(header, 0);
387 prefix.CopyTo(header, 345);
388 Number(header, 100, 8, 420);
389 Number(header, 108, 8, 0);
390 Number(header, 116, 8, 0);
391 Number(header, 124, 12, entry.Data.LongLength);
392 Number(header, 136, 12, 0);
393 header[156] = (byte)entry.Type;
394 "ustar\000"u8.CopyTo(header.AsSpan(257));
395 Checksum(header);
396 stream.Write(header);
397 stream.Write(entry.Data);
398 stream.Write(new byte[(512 - entry.Data.Length % 512) % 512]);
399 }
400 stream.Write(new byte[1024]);
401 return stream.ToArray();
402 }
403
404 internal static void Checksum(Span<byte> header)
405 {
406 header.Slice(148, 8).Fill(32);
407 var sum = 0;
408 foreach (var b in header) { sum += b; }
409 Encoding.ASCII.GetBytes(Convert.ToString(sum, 8).PadLeft(6, '0')).CopyTo(header.Slice(148, 6));
410 header[154] = 0;
411 header[155] = 32;
412 }
413
414 private static void Number(byte[] bytes, int offset, int width, long value) =>
415 Encoding.ASCII.GetBytes(Convert.ToString(value, 8).PadLeft(width - 1, '0') + "\0").CopyTo(bytes, offset);
416}
417
418internal sealed class HashSink : IDisposable
419{
420 private readonly Dictionary<string, IncrementalHash> hashes = new();
421 internal Dictionary<string, long> Counts { get; } = new();
422 internal int Calls { get; private set; }
423 internal int MaxChunk { get; private set; }
424
425 internal ValueTask Write(ArchiveEntry entry, ReadOnlyMemory<byte> bytes, CancellationToken token)
426 {
427 token.ThrowIfCancellationRequested();
428 if (!hashes.TryGetValue(entry.Id, out var hash))
429 {
430 hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
431 hashes.Add(entry.Id, hash);
432 Counts.Add(entry.Id, 0);
433 }
434 hash.AppendData(bytes.Span);
435 Counts[entry.Id] += bytes.Length;
436 Calls++;
437 MaxChunk = Math.Max(MaxChunk, bytes.Length);
438 return ValueTask.CompletedTask;
439 }
440
441 internal string Digest(string id) => Convert.ToHexString(hashes[id].GetHashAndReset());
442 public void Dispose() { foreach (var hash in hashes.Values) { hash.Dispose(); } }
443}
444
445internal sealed class FragmentedStream(byte[] bytes, Action? onRead = null) : MemoryStream(bytes, false)
446{
447 public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
448 {
449 onRead?.Invoke();
450 return base.ReadAsync(buffer[..Math.Min(buffer.Length, 97)], cancellationToken);
451 }
452}
453
454internal sealed class TestTime : TimeProvider
455{
456 internal long Ticks { get; set; }
457 public override long TimestampFrequency => TimeSpan.TicksPerSecond;
458 public override long GetTimestamp() => Ticks;
459}
460
461internal sealed class NonSeekableStream(byte[] bytes) : MemoryStream(bytes, false)
462{
463 public override bool CanSeek => false;
464}