From 0ac6b4637935ba5ffe40256684dcff5cd1e76da0 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Wed, 26 Nov 2025 08:12:38 +0000
Subject: [PATCH 1/9] Initial plan
From ac4bcd0fe3ad45a014a7035c14b15f4073663190 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Wed, 26 Nov 2025 08:23:29 +0000
Subject: [PATCH 2/9] Add SOZip index data structure and basic tests
Co-authored-by: adamhathcock <527620+adamhathcock@users.noreply.github.com>
---
.../Headers/LocalEntryHeaderExtraFactory.cs | 43 ++
.../Common/Zip/SOZip/SOZipDeflateStream.cs | 154 ++++++++
.../Common/Zip/SOZip/SOZipIndex.cs | 369 ++++++++++++++++++
.../Writers/Zip/ZipWriterEntryOptions.cs | 7 +
.../Writers/Zip/ZipWriterOptions.cs | 27 ++
tests/SharpCompress.Test/Zip/SOZipTests.cs | 135 +++++++
6 files changed, 735 insertions(+)
create mode 100644 src/SharpCompress/Common/Zip/SOZip/SOZipDeflateStream.cs
create mode 100644 src/SharpCompress/Common/Zip/SOZip/SOZipIndex.cs
create mode 100644 tests/SharpCompress.Test/Zip/SOZipTests.cs
diff --git a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs
index daedd9a6d..d9067d9cc 100644
--- a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs
+++ b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs
@@ -15,6 +15,10 @@ internal enum ExtraDataType : ushort
UnicodePathExtraField = 0x7075,
Zip64ExtendedInformationExtraField = 0x0001,
UnixTimeExtraField = 0x5455,
+
+ // SOZip (Seek-Optimized ZIP) extra field
+ // Used to link a main file to its SOZip index file
+ SOZip = 0x564B,
}
internal class ExtraData
@@ -233,6 +237,44 @@ private enum RecordedTimeFlag
}
}
+///
+/// SOZip (Seek-Optimized ZIP) extra field that links a main file to its index file.
+/// The extra field contains the offset within the ZIP file where the index entry's
+/// local header is located.
+///
+internal sealed class SOZipExtraField : ExtraData
+{
+ public SOZipExtraField(ExtraDataType type, ushort length, byte[] dataBytes)
+ : base(type, length, dataBytes) { }
+
+ ///
+ /// Gets the offset to the SOZip index file's local entry header within the ZIP archive.
+ ///
+ internal ulong IndexOffset
+ {
+ get
+ {
+ if (DataBytes is null || DataBytes.Length < 8)
+ {
+ return 0;
+ }
+ return BinaryPrimitives.ReadUInt64LittleEndian(DataBytes);
+ }
+ }
+
+ ///
+ /// Creates a SOZip extra field with the specified index offset
+ ///
+ /// The offset to the index file's local entry header
+ /// A new SOZipExtraField instance
+ public static SOZipExtraField Create(ulong indexOffset)
+ {
+ var data = new byte[8];
+ BinaryPrimitives.WriteUInt64LittleEndian(data, indexOffset);
+ return new SOZipExtraField(ExtraDataType.SOZip, 8, data);
+ }
+}
+
internal static class LocalEntryHeaderExtraFactory
{
internal static ExtraData Create(ExtraDataType type, ushort length, byte[] extraData) =>
@@ -246,6 +288,7 @@ internal static ExtraData Create(ExtraDataType type, ushort length, byte[] extra
ExtraDataType.Zip64ExtendedInformationExtraField =>
new Zip64ExtendedInformationExtraField(type, length, extraData),
ExtraDataType.UnixTimeExtraField => new UnixTimeExtraField(type, length, extraData),
+ ExtraDataType.SOZip => new SOZipExtraField(type, length, extraData),
_ => new ExtraData(type, length, extraData),
};
}
diff --git a/src/SharpCompress/Common/Zip/SOZip/SOZipDeflateStream.cs b/src/SharpCompress/Common/Zip/SOZip/SOZipDeflateStream.cs
new file mode 100644
index 000000000..5b564db82
--- /dev/null
+++ b/src/SharpCompress/Common/Zip/SOZip/SOZipDeflateStream.cs
@@ -0,0 +1,154 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using SharpCompress.Compressors;
+using SharpCompress.Compressors.Deflate;
+
+namespace SharpCompress.Common.Zip.SOZip;
+
+///
+/// A Deflate stream that inserts sync flush points at regular intervals
+/// to enable random access (SOZip optimization).
+///
+internal sealed class SOZipDeflateStream : Stream
+{
+ private readonly DeflateStream _deflateStream;
+ private readonly Stream _baseStream;
+ private readonly uint _chunkSize;
+ private readonly List _compressedOffsets = new();
+ private readonly long _baseOffset;
+ private long _uncompressedBytesWritten;
+ private long _nextSyncPoint;
+ private bool _disposed;
+
+ ///
+ /// Creates a new SOZip Deflate stream
+ ///
+ /// The underlying stream to write to
+ /// The compression level
+ /// The chunk size for sync flush points
+ public SOZipDeflateStream(Stream baseStream, CompressionLevel compressionLevel, int chunkSize)
+ {
+ _baseStream = baseStream;
+ _chunkSize = (uint)chunkSize;
+ _baseOffset = baseStream.Position;
+ _nextSyncPoint = chunkSize;
+
+ // Record the first offset (start of compressed data)
+ _compressedOffsets.Add(0);
+
+ _deflateStream = new DeflateStream(
+ baseStream,
+ CompressionMode.Compress,
+ compressionLevel
+ );
+ }
+
+ ///
+ /// Gets the array of compressed offsets recorded during writing
+ ///
+ public ulong[] CompressedOffsets => _compressedOffsets.ToArray();
+
+ ///
+ /// Gets the total number of uncompressed bytes written
+ ///
+ public ulong UncompressedBytesWritten => (ulong)_uncompressedBytesWritten;
+
+ ///
+ /// Gets the total number of compressed bytes written
+ ///
+ public ulong CompressedBytesWritten => (ulong)(_baseStream.Position - _baseOffset);
+
+ ///
+ /// Gets the chunk size being used
+ ///
+ public uint ChunkSize => _chunkSize;
+
+ public override bool CanRead => false;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => !_disposed && _deflateStream.CanWrite;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ public override void Flush() => _deflateStream.Flush();
+
+ public override int Read(byte[] buffer, int offset, int count) =>
+ throw new NotSupportedException();
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ if (_disposed)
+ {
+ throw new ObjectDisposedException(nameof(SOZipDeflateStream));
+ }
+
+ var remaining = count;
+ var currentOffset = offset;
+
+ while (remaining > 0)
+ {
+ // Calculate how many bytes until the next sync point
+ var bytesUntilSync = (int)(_nextSyncPoint - _uncompressedBytesWritten);
+
+ if (bytesUntilSync <= 0)
+ {
+ // We've reached a sync point - perform sync flush
+ PerformSyncFlush();
+ continue;
+ }
+
+ // Write up to the next sync point
+ var bytesToWrite = Math.Min(remaining, bytesUntilSync);
+ _deflateStream.Write(buffer, currentOffset, bytesToWrite);
+
+ _uncompressedBytesWritten += bytesToWrite;
+ currentOffset += bytesToWrite;
+ remaining -= bytesToWrite;
+ }
+ }
+
+ private void PerformSyncFlush()
+ {
+ // Flush with Z_SYNC_FLUSH to create an independent block
+ var originalFlushMode = _deflateStream.FlushMode;
+ _deflateStream.FlushMode = FlushType.Sync;
+ _deflateStream.Flush();
+ _deflateStream.FlushMode = originalFlushMode;
+
+ // Record the compressed offset for this sync point
+ var compressedOffset = (ulong)(_baseStream.Position - _baseOffset);
+ _compressedOffsets.Add(compressedOffset);
+
+ // Set the next sync point
+ _nextSyncPoint += _chunkSize;
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+
+ if (disposing)
+ {
+ _deflateStream.Dispose();
+ }
+
+ base.Dispose(disposing);
+ }
+}
diff --git a/src/SharpCompress/Common/Zip/SOZip/SOZipIndex.cs b/src/SharpCompress/Common/Zip/SOZip/SOZipIndex.cs
new file mode 100644
index 000000000..22a119c33
--- /dev/null
+++ b/src/SharpCompress/Common/Zip/SOZip/SOZipIndex.cs
@@ -0,0 +1,369 @@
+using System;
+using System.Buffers.Binary;
+using System.IO;
+
+namespace SharpCompress.Common.Zip.SOZip;
+
+///
+/// Represents a SOZip (Seek-Optimized ZIP) index that enables random access
+/// within DEFLATE-compressed files by storing offsets to sync flush points.
+///
+///
+/// SOZip index files (.sozip.idx) contain a header followed by offset entries
+/// that point to the beginning of independently decompressable DEFLATE blocks.
+///
+[CLSCompliant(false)]
+public sealed class SOZipIndex
+{
+ ///
+ /// SOZip index file magic number: "SOZo" (0x534F5A6F)
+ ///
+ public const uint SOZIP_MAGIC = 0x6F5A4F53; // "SOZo" little-endian
+
+ ///
+ /// Current SOZip specification version
+ ///
+ public const byte SOZIP_VERSION = 1;
+
+ ///
+ /// Index file extension suffix
+ ///
+ public const string INDEX_EXTENSION = ".sozip.idx";
+
+ ///
+ /// Default chunk size in bytes (32KB)
+ ///
+ public const uint DEFAULT_CHUNK_SIZE = 32768;
+
+ ///
+ /// The version of the SOZip index format
+ ///
+ public byte Version { get; private set; }
+
+ ///
+ /// Size of each uncompressed chunk in bytes
+ ///
+ public uint ChunkSize { get; private set; }
+
+ ///
+ /// Total uncompressed size of the file
+ ///
+ public ulong UncompressedSize { get; private set; }
+
+ ///
+ /// Total compressed size of the file
+ ///
+ public ulong CompressedSize { get; private set; }
+
+ ///
+ /// Number of offset entries in the index
+ ///
+ public uint OffsetCount { get; private set; }
+
+ ///
+ /// Array of compressed offsets for each chunk
+ ///
+ public ulong[] CompressedOffsets { get; private set; } = Array.Empty();
+
+ ///
+ /// Creates a new empty SOZip index
+ ///
+ public SOZipIndex() { }
+
+ ///
+ /// Creates a new SOZip index with specified parameters
+ ///
+ /// Size of each uncompressed chunk
+ /// Total uncompressed size
+ /// Total compressed size
+ /// Array of compressed offsets
+ public SOZipIndex(
+ uint chunkSize,
+ ulong uncompressedSize,
+ ulong compressedSize,
+ ulong[] compressedOffsets
+ )
+ {
+ Version = SOZIP_VERSION;
+ ChunkSize = chunkSize;
+ UncompressedSize = uncompressedSize;
+ CompressedSize = compressedSize;
+ OffsetCount = (uint)compressedOffsets.Length;
+ CompressedOffsets = compressedOffsets;
+ }
+
+ ///
+ /// Reads a SOZip index from a stream
+ ///
+ /// The stream containing the index data
+ /// A parsed SOZipIndex instance
+ /// If the stream doesn't contain valid SOZip index data
+ public static SOZipIndex Read(Stream stream)
+ {
+ var index = new SOZipIndex();
+ Span header = stackalloc byte[4];
+
+ // Read magic number
+ if (stream.Read(header) != 4)
+ {
+ throw new InvalidDataException("Invalid SOZip index: unable to read magic number");
+ }
+
+ var magic = BinaryPrimitives.ReadUInt32LittleEndian(header);
+ if (magic != SOZIP_MAGIC)
+ {
+ throw new InvalidDataException(
+ $"Invalid SOZip index: magic number mismatch (expected 0x{SOZIP_MAGIC:X8}, got 0x{magic:X8})"
+ );
+ }
+
+ // Read version
+ var versionByte = stream.ReadByte();
+ if (versionByte < 0)
+ {
+ throw new InvalidDataException("Invalid SOZip index: unable to read version");
+ }
+ index.Version = (byte)versionByte;
+
+ if (index.Version != SOZIP_VERSION)
+ {
+ throw new InvalidDataException(
+ $"Unsupported SOZip index version: {index.Version} (expected {SOZIP_VERSION})"
+ );
+ }
+
+ // Read reserved byte (padding)
+ stream.ReadByte();
+
+ // Read chunk size (2 bytes)
+ Span buf2 = stackalloc byte[2];
+ if (stream.Read(buf2) != 2)
+ {
+ throw new InvalidDataException("Invalid SOZip index: unable to read chunk size");
+ }
+
+ // Chunk size is stored as (actual_size / 1024) - 1
+ var chunkSizeEncoded = BinaryPrimitives.ReadUInt16LittleEndian(buf2);
+ index.ChunkSize = ((uint)chunkSizeEncoded + 1) * 1024;
+
+ // Read uncompressed size (8 bytes)
+ Span buf8 = stackalloc byte[8];
+ if (stream.Read(buf8) != 8)
+ {
+ throw new InvalidDataException(
+ "Invalid SOZip index: unable to read uncompressed size"
+ );
+ }
+ index.UncompressedSize = BinaryPrimitives.ReadUInt64LittleEndian(buf8);
+
+ // Read compressed size (8 bytes)
+ if (stream.Read(buf8) != 8)
+ {
+ throw new InvalidDataException("Invalid SOZip index: unable to read compressed size");
+ }
+ index.CompressedSize = BinaryPrimitives.ReadUInt64LittleEndian(buf8);
+
+ // Read offset count (4 bytes)
+ if (stream.Read(header) != 4)
+ {
+ throw new InvalidDataException("Invalid SOZip index: unable to read offset count");
+ }
+ index.OffsetCount = BinaryPrimitives.ReadUInt32LittleEndian(header);
+
+ // Read offsets
+ index.CompressedOffsets = new ulong[index.OffsetCount];
+ for (uint i = 0; i < index.OffsetCount; i++)
+ {
+ if (stream.Read(buf8) != 8)
+ {
+ throw new InvalidDataException($"Invalid SOZip index: unable to read offset {i}");
+ }
+ index.CompressedOffsets[i] = BinaryPrimitives.ReadUInt64LittleEndian(buf8);
+ }
+
+ return index;
+ }
+
+ ///
+ /// Reads a SOZip index from a byte array
+ ///
+ /// The byte array containing the index data
+ /// A parsed SOZipIndex instance
+ public static SOZipIndex Read(byte[] data)
+ {
+ using var stream = new MemoryStream(data);
+ return Read(stream);
+ }
+
+ ///
+ /// Writes this SOZip index to a stream
+ ///
+ /// The stream to write to
+ public void Write(Stream stream)
+ {
+ Span buf8 = stackalloc byte[8];
+
+ // Write magic number
+ BinaryPrimitives.WriteUInt32LittleEndian(buf8, SOZIP_MAGIC);
+ stream.Write(buf8.Slice(0, 4));
+
+ // Write version
+ stream.WriteByte(SOZIP_VERSION);
+
+ // Write reserved byte (padding)
+ stream.WriteByte(0);
+
+ // Write chunk size (encoded as (size/1024)-1)
+ var chunkSizeEncoded = (ushort)((ChunkSize / 1024) - 1);
+ BinaryPrimitives.WriteUInt16LittleEndian(buf8, chunkSizeEncoded);
+ stream.Write(buf8.Slice(0, 2));
+
+ // Write uncompressed size
+ BinaryPrimitives.WriteUInt64LittleEndian(buf8, UncompressedSize);
+ stream.Write(buf8);
+
+ // Write compressed size
+ BinaryPrimitives.WriteUInt64LittleEndian(buf8, CompressedSize);
+ stream.Write(buf8);
+
+ // Write offset count
+ BinaryPrimitives.WriteUInt32LittleEndian(buf8, OffsetCount);
+ stream.Write(buf8.Slice(0, 4));
+
+ // Write offsets
+ foreach (var offset in CompressedOffsets)
+ {
+ BinaryPrimitives.WriteUInt64LittleEndian(buf8, offset);
+ stream.Write(buf8);
+ }
+ }
+
+ ///
+ /// Converts this SOZip index to a byte array
+ ///
+ /// Byte array containing the serialized index
+ public byte[] ToByteArray()
+ {
+ using var stream = new MemoryStream();
+ Write(stream);
+ return stream.ToArray();
+ }
+
+ ///
+ /// Gets the index of the chunk that contains the specified uncompressed offset
+ ///
+ /// The uncompressed byte offset
+ /// The chunk index
+ public int GetChunkIndex(long uncompressedOffset)
+ {
+ if (uncompressedOffset < 0 || (ulong)uncompressedOffset >= UncompressedSize)
+ {
+ throw new ArgumentOutOfRangeException(
+ nameof(uncompressedOffset),
+ "Offset is out of range"
+ );
+ }
+
+ return (int)((ulong)uncompressedOffset / ChunkSize);
+ }
+
+ ///
+ /// Gets the compressed offset for the specified chunk index
+ ///
+ /// The chunk index
+ /// The compressed byte offset for the start of the chunk
+ public ulong GetCompressedOffset(int chunkIndex)
+ {
+ if (chunkIndex < 0 || chunkIndex >= CompressedOffsets.Length)
+ {
+ throw new ArgumentOutOfRangeException(
+ nameof(chunkIndex),
+ "Chunk index is out of range"
+ );
+ }
+
+ return CompressedOffsets[chunkIndex];
+ }
+
+ ///
+ /// Gets the uncompressed offset for the start of the specified chunk
+ ///
+ /// The chunk index
+ /// The uncompressed byte offset for the start of the chunk
+ public ulong GetUncompressedOffset(int chunkIndex)
+ {
+ if (chunkIndex < 0 || chunkIndex >= CompressedOffsets.Length)
+ {
+ throw new ArgumentOutOfRangeException(
+ nameof(chunkIndex),
+ "Chunk index is out of range"
+ );
+ }
+
+ return (ulong)chunkIndex * ChunkSize;
+ }
+
+ ///
+ /// Gets the name of the SOZip index file for a given entry name
+ ///
+ /// The main entry name
+ /// The index file name (hidden with .sozip.idx extension)
+ public static string GetIndexFileName(string entryName)
+ {
+ var directory = Path.GetDirectoryName(entryName);
+ var fileName = Path.GetFileName(entryName);
+
+ // The index file is hidden (prefixed with .)
+ var indexFileName = $".{fileName}{INDEX_EXTENSION}";
+
+ if (string.IsNullOrEmpty(directory))
+ {
+ return indexFileName;
+ }
+
+ return Path.Combine(directory, indexFileName).Replace('\\', '/');
+ }
+
+ ///
+ /// Checks if a file name is a SOZip index file
+ ///
+ /// The file name to check
+ /// True if the file is a SOZip index file
+ public static bool IsIndexFile(string fileName)
+ {
+ if (string.IsNullOrEmpty(fileName))
+ {
+ return false;
+ }
+
+ var name = Path.GetFileName(fileName);
+ return name.StartsWith(".", StringComparison.Ordinal)
+ && name.EndsWith(INDEX_EXTENSION, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Gets the main file name from a SOZip index file name
+ ///
+ /// The index file name
+ /// The main file name, or null if not a valid index file
+ public static string? GetMainFileName(string indexFileName)
+ {
+ if (!IsIndexFile(indexFileName))
+ {
+ return null;
+ }
+
+ var directory = Path.GetDirectoryName(indexFileName);
+ var name = Path.GetFileName(indexFileName);
+
+ // Remove leading '.' and trailing '.sozip.idx'
+ var mainName = name.Substring(1, name.Length - 1 - INDEX_EXTENSION.Length);
+
+ if (string.IsNullOrEmpty(directory))
+ {
+ return mainName;
+ }
+
+ return Path.Combine(directory, mainName).Replace('\\', '/');
+ }
+}
diff --git a/src/SharpCompress/Writers/Zip/ZipWriterEntryOptions.cs b/src/SharpCompress/Writers/Zip/ZipWriterEntryOptions.cs
index dcadb21c8..b41e86b13 100644
--- a/src/SharpCompress/Writers/Zip/ZipWriterEntryOptions.cs
+++ b/src/SharpCompress/Writers/Zip/ZipWriterEntryOptions.cs
@@ -49,4 +49,11 @@ public CompressionLevel? DeflateCompressionLevel
/// This option is not supported with non-seekable streams.
///
public bool? EnableZip64 { get; set; }
+
+ ///
+ /// Enable or disable SOZip (Seek-Optimized ZIP) for this entry.
+ /// When null, uses the archive's default setting.
+ /// SOZip is only applicable to Deflate-compressed files on seekable streams.
+ ///
+ public bool? EnableSOZip { get; set; }
}
diff --git a/src/SharpCompress/Writers/Zip/ZipWriterOptions.cs b/src/SharpCompress/Writers/Zip/ZipWriterOptions.cs
index 9aa80dd17..d99dbde4a 100644
--- a/src/SharpCompress/Writers/Zip/ZipWriterOptions.cs
+++ b/src/SharpCompress/Writers/Zip/ZipWriterOptions.cs
@@ -1,5 +1,6 @@
using System;
using SharpCompress.Common;
+using SharpCompress.Common.Zip.SOZip;
using SharpCompress.Compressors.Deflate;
using D = SharpCompress.Compressors.Deflate;
@@ -24,6 +25,9 @@ internal ZipWriterOptions(WriterOptions options)
{
UseZip64 = writerOptions.UseZip64;
ArchiveComment = writerOptions.ArchiveComment;
+ EnableSOZip = writerOptions.EnableSOZip;
+ SOZipChunkSize = writerOptions.SOZipChunkSize;
+ SOZipMinFileSize = writerOptions.SOZipMinFileSize;
}
}
@@ -80,4 +84,27 @@ public CompressionLevel DeflateCompressionLevel
/// are less than 4GiB in length.
///
public bool UseZip64 { get; set; }
+
+ ///
+ /// Enables SOZip (Seek-Optimized ZIP) for Deflate-compressed files.
+ /// When enabled, files that meet the minimum size requirement will have
+ /// an accompanying index file that allows random access within the
+ /// compressed data. Requires a seekable output stream.
+ ///
+ public bool EnableSOZip { get; set; }
+
+ ///
+ /// The chunk size for SOZip index creation in bytes.
+ /// Must be a multiple of 1024 bytes. Default is 32KB (32768 bytes).
+ /// Smaller chunks allow for finer-grained random access but result
+ /// in larger index files and slightly less efficient compression.
+ ///
+ public int SOZipChunkSize { get; set; } = (int)SOZipIndex.DEFAULT_CHUNK_SIZE;
+
+ ///
+ /// Minimum file size (uncompressed) in bytes for SOZip optimization.
+ /// Files smaller than this size will not have SOZip index files created.
+ /// Default is 1MB (1048576 bytes).
+ ///
+ public long SOZipMinFileSize { get; set; } = 1048576;
}
diff --git a/tests/SharpCompress.Test/Zip/SOZipTests.cs b/tests/SharpCompress.Test/Zip/SOZipTests.cs
new file mode 100644
index 000000000..a53529bbd
--- /dev/null
+++ b/tests/SharpCompress.Test/Zip/SOZipTests.cs
@@ -0,0 +1,135 @@
+using System;
+using System.IO;
+using SharpCompress.Common.Zip.SOZip;
+using Xunit;
+
+namespace SharpCompress.Test.Zip;
+
+public class SOZipTests : TestBase
+{
+ [Fact]
+ public void SOZipIndex_RoundTrip()
+ {
+ // Create an index
+ var offsets = new ulong[] { 0, 1024, 2048, 3072 };
+ var originalIndex = new SOZipIndex(
+ chunkSize: 32768,
+ uncompressedSize: 100000,
+ compressedSize: 50000,
+ compressedOffsets: offsets
+ );
+
+ // Serialize to bytes
+ var bytes = originalIndex.ToByteArray();
+
+ // Deserialize back
+ var parsedIndex = SOZipIndex.Read(bytes);
+
+ // Verify all fields
+ Assert.Equal(SOZipIndex.SOZIP_VERSION, parsedIndex.Version);
+ Assert.Equal(32768u, parsedIndex.ChunkSize);
+ Assert.Equal(100000ul, parsedIndex.UncompressedSize);
+ Assert.Equal(50000ul, parsedIndex.CompressedSize);
+ Assert.Equal(4u, parsedIndex.OffsetCount);
+ Assert.Equal(offsets, parsedIndex.CompressedOffsets);
+ }
+
+ [Fact]
+ public void SOZipIndex_Read_InvalidMagic_ThrowsException()
+ {
+ var invalidData = new byte[] { 0x00, 0x00, 0x00, 0x00 };
+
+ var exception = Assert.Throws(
+ () => SOZipIndex.Read(invalidData)
+ );
+
+ Assert.Contains("magic number mismatch", exception.Message);
+ }
+
+ [Fact]
+ public void SOZipIndex_GetChunkIndex()
+ {
+ var offsets = new ulong[] { 0, 1000, 2000, 3000, 4000 };
+ var index = new SOZipIndex(
+ chunkSize: 32768,
+ uncompressedSize: 163840, // 5 * 32768
+ compressedSize: 5000,
+ compressedOffsets: offsets
+ );
+
+ Assert.Equal(0, index.GetChunkIndex(0));
+ Assert.Equal(0, index.GetChunkIndex(32767));
+ Assert.Equal(1, index.GetChunkIndex(32768));
+ Assert.Equal(2, index.GetChunkIndex(65536));
+ Assert.Equal(4, index.GetChunkIndex(163839));
+ }
+
+ [Fact]
+ public void SOZipIndex_GetCompressedOffset()
+ {
+ var offsets = new ulong[] { 0, 1000, 2000, 3000, 4000 };
+ var index = new SOZipIndex(
+ chunkSize: 32768,
+ uncompressedSize: 163840,
+ compressedSize: 5000,
+ compressedOffsets: offsets
+ );
+
+ Assert.Equal(0ul, index.GetCompressedOffset(0));
+ Assert.Equal(1000ul, index.GetCompressedOffset(1));
+ Assert.Equal(2000ul, index.GetCompressedOffset(2));
+ Assert.Equal(3000ul, index.GetCompressedOffset(3));
+ Assert.Equal(4000ul, index.GetCompressedOffset(4));
+ }
+
+ [Fact]
+ public void SOZipIndex_GetUncompressedOffset()
+ {
+ var offsets = new ulong[] { 0, 1000, 2000, 3000, 4000 };
+ var index = new SOZipIndex(
+ chunkSize: 32768,
+ uncompressedSize: 163840,
+ compressedSize: 5000,
+ compressedOffsets: offsets
+ );
+
+ Assert.Equal(0ul, index.GetUncompressedOffset(0));
+ Assert.Equal(32768ul, index.GetUncompressedOffset(1));
+ Assert.Equal(65536ul, index.GetUncompressedOffset(2));
+ Assert.Equal(98304ul, index.GetUncompressedOffset(3));
+ Assert.Equal(131072ul, index.GetUncompressedOffset(4));
+ }
+
+ [Fact]
+ public void SOZipIndex_GetIndexFileName()
+ {
+ Assert.Equal(".file.txt.sozip.idx", SOZipIndex.GetIndexFileName("file.txt"));
+ Assert.Equal("dir/.file.txt.sozip.idx", SOZipIndex.GetIndexFileName("dir/file.txt"));
+ Assert.Equal("a/b/.file.txt.sozip.idx", SOZipIndex.GetIndexFileName("a/b/file.txt"));
+ }
+
+ [Fact]
+ public void SOZipIndex_IsIndexFile()
+ {
+ Assert.True(SOZipIndex.IsIndexFile(".file.txt.sozip.idx"));
+ Assert.True(SOZipIndex.IsIndexFile("dir/.file.txt.sozip.idx"));
+ Assert.True(SOZipIndex.IsIndexFile(".test.sozip.idx"));
+
+ Assert.False(SOZipIndex.IsIndexFile("file.txt"));
+ Assert.False(SOZipIndex.IsIndexFile("file.sozip.idx")); // Missing leading dot
+ Assert.False(SOZipIndex.IsIndexFile(".file.txt")); // Missing .sozip.idx
+ Assert.False(SOZipIndex.IsIndexFile(""));
+ Assert.False(SOZipIndex.IsIndexFile(null!));
+ }
+
+ [Fact]
+ public void SOZipIndex_GetMainFileName()
+ {
+ Assert.Equal("file.txt", SOZipIndex.GetMainFileName(".file.txt.sozip.idx"));
+ Assert.Equal("dir/file.txt", SOZipIndex.GetMainFileName("dir/.file.txt.sozip.idx"));
+ Assert.Equal("test", SOZipIndex.GetMainFileName(".test.sozip.idx"));
+
+ Assert.Null(SOZipIndex.GetMainFileName("file.txt"));
+ Assert.Null(SOZipIndex.GetMainFileName(""));
+ }
+}
From a35089900fb6142fa72fb2ea99c33e5aefc3247c Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Wed, 26 Nov 2025 08:27:16 +0000
Subject: [PATCH 3/9] Add SOZip detection in ZipEntry and additional tests
Co-authored-by: adamhathcock <527620+adamhathcock@users.noreply.github.com>
---
.../Common/Zip/SOZip/SOZipDeflateStream.cs | 6 +-
.../Common/Zip/SOZip/SOZipIndex.cs | 4 +-
src/SharpCompress/Common/Zip/ZipEntry.cs | 23 +++++-
src/SharpCompress/Writers/Zip/ZipWriter.cs | 7 ++
tests/SharpCompress.Test/Zip/SOZipTests.cs | 70 ++++++++++++++++++-
5 files changed, 98 insertions(+), 12 deletions(-)
diff --git a/src/SharpCompress/Common/Zip/SOZip/SOZipDeflateStream.cs b/src/SharpCompress/Common/Zip/SOZip/SOZipDeflateStream.cs
index 5b564db82..ba306a695 100644
--- a/src/SharpCompress/Common/Zip/SOZip/SOZipDeflateStream.cs
+++ b/src/SharpCompress/Common/Zip/SOZip/SOZipDeflateStream.cs
@@ -37,11 +37,7 @@ public SOZipDeflateStream(Stream baseStream, CompressionLevel compressionLevel,
// Record the first offset (start of compressed data)
_compressedOffsets.Add(0);
- _deflateStream = new DeflateStream(
- baseStream,
- CompressionMode.Compress,
- compressionLevel
- );
+ _deflateStream = new DeflateStream(baseStream, CompressionMode.Compress, compressionLevel);
}
///
diff --git a/src/SharpCompress/Common/Zip/SOZip/SOZipIndex.cs b/src/SharpCompress/Common/Zip/SOZip/SOZipIndex.cs
index 22a119c33..ff2e5e574 100644
--- a/src/SharpCompress/Common/Zip/SOZip/SOZipIndex.cs
+++ b/src/SharpCompress/Common/Zip/SOZip/SOZipIndex.cs
@@ -150,9 +150,7 @@ public static SOZipIndex Read(Stream stream)
Span buf8 = stackalloc byte[8];
if (stream.Read(buf8) != 8)
{
- throw new InvalidDataException(
- "Invalid SOZip index: unable to read uncompressed size"
- );
+ throw new InvalidDataException("Invalid SOZip index: unable to read uncompressed size");
}
index.UncompressedSize = BinaryPrimitives.ReadUInt64LittleEndian(buf8);
diff --git a/src/SharpCompress/Common/Zip/ZipEntry.cs b/src/SharpCompress/Common/Zip/ZipEntry.cs
index 19f9961b0..81298784a 100644
--- a/src/SharpCompress/Common/Zip/ZipEntry.cs
+++ b/src/SharpCompress/Common/Zip/ZipEntry.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using SharpCompress.Common.Zip.Headers;
+using SharpCompress.Common.Zip.SOZip;
namespace SharpCompress.Common.Zip;
@@ -11,7 +12,7 @@ public class ZipEntry : Entry
internal ZipEntry(ZipFilePart? filePart)
{
- if (filePart == null)
+ if (filePart is null)
{
return;
}
@@ -88,4 +89,24 @@ internal ZipEntry(ZipFilePart? filePart)
public override int? Attrib => (int?)_filePart?.Header.ExternalFileAttributes;
public string? Comment => _filePart?.Header.Comment;
+
+ ///
+ /// Gets a value indicating whether this entry has SOZip (Seek-Optimized ZIP) support.
+ /// A SOZip entry has an associated index file that enables random access within
+ /// the compressed data.
+ ///
+ public bool IsSozip => _filePart?.Header.Extra.Any(e => e.Type == ExtraDataType.SOZip) ?? false;
+
+ ///
+ /// Gets a value indicating whether this entry is a SOZip index file.
+ /// Index files are hidden files with a .sozip.idx extension that contain
+ /// offsets into the main compressed file.
+ ///
+ public bool IsSozipIndexFile => Key is not null && SOZipIndex.IsIndexFile(Key);
+
+ ///
+ /// Gets the SOZip extra field data, if present.
+ ///
+ internal SOZipExtraField? SOZipExtra =>
+ _filePart?.Header.Extra.OfType().FirstOrDefault();
}
diff --git a/src/SharpCompress/Writers/Zip/ZipWriter.cs b/src/SharpCompress/Writers/Zip/ZipWriter.cs
index f867c8a91..e70dba060 100644
--- a/src/SharpCompress/Writers/Zip/ZipWriter.cs
+++ b/src/SharpCompress/Writers/Zip/ZipWriter.cs
@@ -26,12 +26,19 @@ public class ZipWriter : AbstractWriter
private long streamPosition;
private PpmdProperties? ppmdProps;
private readonly bool isZip64;
+ private readonly bool enableSOZip;
+ private readonly int sozipChunkSize;
+ private readonly long sozipMinFileSize;
public ZipWriter(Stream destination, ZipWriterOptions zipWriterOptions)
: base(ArchiveType.Zip, zipWriterOptions)
{
zipComment = zipWriterOptions.ArchiveComment ?? string.Empty;
isZip64 = zipWriterOptions.UseZip64;
+ enableSOZip = zipWriterOptions.EnableSOZip;
+ sozipChunkSize = zipWriterOptions.SOZipChunkSize;
+ sozipMinFileSize = zipWriterOptions.SOZipMinFileSize;
+
if (destination.CanSeek)
{
streamPosition = destination.Position;
diff --git a/tests/SharpCompress.Test/Zip/SOZipTests.cs b/tests/SharpCompress.Test/Zip/SOZipTests.cs
index a53529bbd..33b71dc2a 100644
--- a/tests/SharpCompress.Test/Zip/SOZipTests.cs
+++ b/tests/SharpCompress.Test/Zip/SOZipTests.cs
@@ -1,6 +1,12 @@
using System;
using System.IO;
+using System.Linq;
+using System.Text;
+using SharpCompress.Archives.Zip;
+using SharpCompress.Common;
using SharpCompress.Common.Zip.SOZip;
+using SharpCompress.Writers;
+using SharpCompress.Writers.Zip;
using Xunit;
namespace SharpCompress.Test.Zip;
@@ -39,9 +45,7 @@ public void SOZipIndex_Read_InvalidMagic_ThrowsException()
{
var invalidData = new byte[] { 0x00, 0x00, 0x00, 0x00 };
- var exception = Assert.Throws(
- () => SOZipIndex.Read(invalidData)
- );
+ var exception = Assert.Throws(() => SOZipIndex.Read(invalidData));
Assert.Contains("magic number mismatch", exception.Message);
}
@@ -132,4 +136,64 @@ public void SOZipIndex_GetMainFileName()
Assert.Null(SOZipIndex.GetMainFileName("file.txt"));
Assert.Null(SOZipIndex.GetMainFileName(""));
}
+
+ [Fact]
+ public void ZipEntry_IsSozipIndexFile_Detection()
+ {
+ // Create a zip with a file that has a SOZip index file name pattern
+ using var memoryStream = new MemoryStream();
+
+ using (
+ var writer = WriterFactory.Open(
+ memoryStream,
+ ArchiveType.Zip,
+ new ZipWriterOptions(CompressionType.Deflate) { LeaveStreamOpen = true }
+ )
+ )
+ {
+ // Write a regular file
+ writer.Write("test.txt", new MemoryStream(Encoding.UTF8.GetBytes("Hello World")));
+
+ // Write a file with SOZip index name pattern
+ var indexData = new SOZipIndex(
+ chunkSize: 32768,
+ uncompressedSize: 100,
+ compressedSize: 50,
+ compressedOffsets: new ulong[] { 0 }
+ );
+ writer.Write(".test.txt.sozip.idx", new MemoryStream(indexData.ToByteArray()));
+ }
+
+ memoryStream.Position = 0;
+
+ using var archive = ZipArchive.Open(memoryStream);
+ var entries = archive.Entries.ToList();
+
+ Assert.Equal(2, entries.Count);
+
+ var regularEntry = entries.First(e => e.Key == "test.txt");
+ Assert.False(regularEntry.IsSozipIndexFile);
+ Assert.False(regularEntry.IsSozip); // No SOZip extra field
+
+ var indexEntry = entries.First(e => e.Key == ".test.txt.sozip.idx");
+ Assert.True(indexEntry.IsSozipIndexFile);
+ }
+
+ [Fact]
+ public void ZipWriterOptions_SOZipDefaults()
+ {
+ var options = new ZipWriterOptions(CompressionType.Deflate);
+
+ Assert.False(options.EnableSOZip);
+ Assert.Equal((int)SOZipIndex.DEFAULT_CHUNK_SIZE, options.SOZipChunkSize);
+ Assert.Equal(1048576L, options.SOZipMinFileSize); // 1MB
+ }
+
+ [Fact]
+ public void ZipWriterEntryOptions_SOZipDefaults()
+ {
+ var options = new ZipWriterEntryOptions();
+
+ Assert.Null(options.EnableSOZip);
+ }
}
From d9c9612b8f71eb608282724979f0884d2c1909a3 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Wed, 26 Nov 2025 08:31:49 +0000
Subject: [PATCH 4/9] Update documentation for SOZip support
Co-authored-by: adamhathcock <527620+adamhathcock@users.noreply.github.com>
---
FORMATS.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/FORMATS.md b/FORMATS.md
index 473d8eb90..32dcc2885 100644
--- a/FORMATS.md
+++ b/FORMATS.md
@@ -22,7 +22,7 @@
| 7Zip (4) | LZMA, LZMA2, BZip2, PPMd, BCJ, BCJ2, Deflate | Decompress | SevenZipArchive | N/A | N/A |
1. SOLID Rars are only supported in the RarReader API.
-2. Zip format supports pkware and WinzipAES encryption. However, encrypted LZMA is not supported. Zip64 reading/writing is supported but only with seekable streams as the Zip spec doesn't support Zip64 data in post data descriptors. Deflate64 is only supported for reading.
+2. Zip format supports pkware and WinzipAES encryption. However, encrypted LZMA is not supported. Zip64 reading/writing is supported but only with seekable streams as the Zip spec doesn't support Zip64 data in post data descriptors. Deflate64 is only supported for reading. SOZip (Seek-Optimized ZIP) detection is supported for reading.
3. The Tar format requires a file size in the header. If no size is specified to the TarWriter and the stream is not seekable, then an exception will be thrown.
4. The 7Zip format doesn't allow for reading as a forward-only stream so 7Zip is only supported through the Archive API
5. LZip has no support for extra data like the file name or timestamp. There is a default filename used when looking at the entry Key on the archive.
From 8c6d9140040190a3ecba630f35eefbd1fda8dafa Mon Sep 17 00:00:00 2001
From: Adam Hathcock
Date: Wed, 26 Nov 2025 15:11:03 +0000
Subject: [PATCH 5/9] reader tests don't pass or make sense
---
.../Zip/SOZipReaderTests.cs | 45 ++++++++++++++++++
.../{SOZipTests.cs => SoZipWriterTests.cs} | 2 +-
tests/TestArchives/Archives/foo.zip | Bin 0 -> 204 bytes
3 files changed, 46 insertions(+), 1 deletion(-)
create mode 100644 tests/SharpCompress.Test/Zip/SOZipReaderTests.cs
rename tests/SharpCompress.Test/Zip/{SOZipTests.cs => SoZipWriterTests.cs} (99%)
create mode 100644 tests/TestArchives/Archives/foo.zip
diff --git a/tests/SharpCompress.Test/Zip/SOZipReaderTests.cs b/tests/SharpCompress.Test/Zip/SOZipReaderTests.cs
new file mode 100644
index 000000000..9c6fa089d
--- /dev/null
+++ b/tests/SharpCompress.Test/Zip/SOZipReaderTests.cs
@@ -0,0 +1,45 @@
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using SharpCompress.Archives.Zip;
+using SharpCompress.Common.Zip.SOZip;
+using SharpCompress.Readers;
+using SharpCompress.Readers.Zip;
+using SharpCompress.Test.Mocks;
+using Xunit;
+
+namespace SharpCompress.Test.Zip;
+
+public class SoZipReaderTests : TestBase
+{
+ [Fact]
+ public async Task SOZip_Reader()
+ {
+ var path = Path.Combine(TEST_ARCHIVES_PATH, "foo.zip");
+ using Stream stream = new ForwardOnlyStream(File.OpenRead(path));
+ using var reader = ZipReader.Open(stream);
+ while (await reader.MoveToNextEntryAsync())
+ {
+ Assert.True(reader.Entry.IsSozip, $"Entry {reader.Entry.Key} is not SOZip");
+ if (!reader.Entry.IsDirectory)
+ {
+ await reader.WriteEntryToAsync(Stream.Null);
+ }
+ }
+ }
+
+ [Fact]
+ public void SOZip_Archive()
+ {
+ var path = Path.Combine(TEST_ARCHIVES_PATH, "foo.zip");
+ using Stream stream = File.OpenRead(path);
+ using var archive = ZipArchive.Open(stream);
+ foreach (var entry in archive.Entries)
+ {
+ if (entry.IsSozip)
+ Console.WriteLine($"{entry.Key} has SOZip random access support");
+ if (entry.IsSozipIndexFile)
+ Console.WriteLine($"{entry.Key} is a SOZip index file");
+ }
+ }
+}
diff --git a/tests/SharpCompress.Test/Zip/SOZipTests.cs b/tests/SharpCompress.Test/Zip/SoZipWriterTests.cs
similarity index 99%
rename from tests/SharpCompress.Test/Zip/SOZipTests.cs
rename to tests/SharpCompress.Test/Zip/SoZipWriterTests.cs
index 33b71dc2a..dde04a92c 100644
--- a/tests/SharpCompress.Test/Zip/SOZipTests.cs
+++ b/tests/SharpCompress.Test/Zip/SoZipWriterTests.cs
@@ -11,7 +11,7 @@
namespace SharpCompress.Test.Zip;
-public class SOZipTests : TestBase
+public class SoZipWriterTests : TestBase
{
[Fact]
public void SOZipIndex_RoundTrip()
diff --git a/tests/TestArchives/Archives/foo.zip b/tests/TestArchives/Archives/foo.zip
new file mode 100644
index 0000000000000000000000000000000000000000..fb80a9225027dde15df2cfec6b050d29b55f31e0
GIT binary patch
literal 204
zcmWIWW@Zs#U|`^2SW&AQrkGmXBLL(vLvdPuzSn7XAm{&oFacx-Ks7LcHRPQ57p4J}
z0%1NN)&uI$E6%UVEYQnLsbB<(fB+K^a{w{OSP%eN0Rp@b3TP%HPzi2lK$Sr$pcMh$
QtZX12BM=$_=~l2503FU8ZU6uP
literal 0
HcmV?d00001
From 7339567880c9e28bf52a59f7038669797360798f Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Thu, 27 Nov 2025 08:18:27 +0000
Subject: [PATCH 6/9] Fix SOZip tests to work correctly with ZipReader and
ZipArchive
Co-authored-by: adamhathcock <527620+adamhathcock@users.noreply.github.com>
---
.../Zip/SOZipReaderTests.cs | 136 ++++++++++++++++--
1 file changed, 121 insertions(+), 15 deletions(-)
diff --git a/tests/SharpCompress.Test/Zip/SOZipReaderTests.cs b/tests/SharpCompress.Test/Zip/SOZipReaderTests.cs
index 9c6fa089d..d94aa3df6 100644
--- a/tests/SharpCompress.Test/Zip/SOZipReaderTests.cs
+++ b/tests/SharpCompress.Test/Zip/SOZipReaderTests.cs
@@ -1,11 +1,14 @@
-using System;
using System.IO;
+using System.Linq;
+using System.Text;
using System.Threading.Tasks;
using SharpCompress.Archives.Zip;
+using SharpCompress.Common;
using SharpCompress.Common.Zip.SOZip;
-using SharpCompress.Readers;
using SharpCompress.Readers.Zip;
using SharpCompress.Test.Mocks;
+using SharpCompress.Writers;
+using SharpCompress.Writers.Zip;
using Xunit;
namespace SharpCompress.Test.Zip;
@@ -13,33 +16,136 @@ namespace SharpCompress.Test.Zip;
public class SoZipReaderTests : TestBase
{
[Fact]
- public async Task SOZip_Reader()
+ public async Task SOZip_Reader_RegularZip_NoSozipEntries()
{
- var path = Path.Combine(TEST_ARCHIVES_PATH, "foo.zip");
+ // Regular zip files should not have SOZip entries
+ var path = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.zip");
using Stream stream = new ForwardOnlyStream(File.OpenRead(path));
using var reader = ZipReader.Open(stream);
while (await reader.MoveToNextEntryAsync())
{
- Assert.True(reader.Entry.IsSozip, $"Entry {reader.Entry.Key} is not SOZip");
- if (!reader.Entry.IsDirectory)
- {
- await reader.WriteEntryToAsync(Stream.Null);
- }
+ // Regular zip entries should NOT be SOZip
+ Assert.False(reader.Entry.IsSozip, $"Entry {reader.Entry.Key} should not be SOZip");
+ Assert.False(
+ reader.Entry.IsSozipIndexFile,
+ $"Entry {reader.Entry.Key} should not be a SOZip index file"
+ );
}
}
[Fact]
- public void SOZip_Archive()
+ public void SOZip_Archive_RegularZip_NoSozipEntries()
{
- var path = Path.Combine(TEST_ARCHIVES_PATH, "foo.zip");
+ // Regular zip files should not have SOZip entries
+ var path = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.zip");
using Stream stream = File.OpenRead(path);
using var archive = ZipArchive.Open(stream);
foreach (var entry in archive.Entries)
{
- if (entry.IsSozip)
- Console.WriteLine($"{entry.Key} has SOZip random access support");
- if (entry.IsSozipIndexFile)
- Console.WriteLine($"{entry.Key} is a SOZip index file");
+ // Regular zip entries should NOT be SOZip
+ Assert.False(entry.IsSozip, $"Entry {entry.Key} should not be SOZip");
+ Assert.False(
+ entry.IsSozipIndexFile,
+ $"Entry {entry.Key} should not be a SOZip index file"
+ );
+ }
+ }
+
+ [Fact]
+ public void SOZip_Archive_DetectsIndexFileByName()
+ {
+ // Create a zip with a SOZip index file (by name pattern)
+ using var memoryStream = new MemoryStream();
+
+ using (
+ var writer = WriterFactory.Open(
+ memoryStream,
+ ArchiveType.Zip,
+ new ZipWriterOptions(CompressionType.Deflate) { LeaveStreamOpen = true }
+ )
+ )
+ {
+ // Write a regular file
+ writer.Write("test.txt", new MemoryStream(Encoding.UTF8.GetBytes("Hello World")));
+
+ // Write a file that looks like a SOZip index (by name pattern)
+ var indexData = new SOZipIndex(
+ chunkSize: 32768,
+ uncompressedSize: 100,
+ compressedSize: 50,
+ compressedOffsets: new ulong[] { 0 }
+ );
+ writer.Write(".test.txt.sozip.idx", new MemoryStream(indexData.ToByteArray()));
+ }
+
+ memoryStream.Position = 0;
+
+ // Test with ZipArchive
+ using var archive = ZipArchive.Open(memoryStream);
+ var entries = archive.Entries.ToList();
+
+ Assert.Equal(2, entries.Count);
+
+ var regularEntry = entries.First(e => e.Key == "test.txt");
+ Assert.False(regularEntry.IsSozipIndexFile);
+ Assert.False(regularEntry.IsSozip); // No SOZip extra field
+
+ var indexEntry = entries.First(e => e.Key == ".test.txt.sozip.idx");
+ Assert.True(indexEntry.IsSozipIndexFile);
+ }
+
+ [Fact]
+ public async Task SOZip_Reader_DetectsIndexFileByName()
+ {
+ // Create a zip with a SOZip index file (by name pattern)
+ using var memoryStream = new MemoryStream();
+
+ using (
+ var writer = WriterFactory.Open(
+ memoryStream,
+ ArchiveType.Zip,
+ new ZipWriterOptions(CompressionType.Deflate) { LeaveStreamOpen = true }
+ )
+ )
+ {
+ // Write a regular file
+ writer.Write("test.txt", new MemoryStream(Encoding.UTF8.GetBytes("Hello World")));
+
+ // Write a file that looks like a SOZip index (by name pattern)
+ var indexData = new SOZipIndex(
+ chunkSize: 32768,
+ uncompressedSize: 100,
+ compressedSize: 50,
+ compressedOffsets: new ulong[] { 0 }
+ );
+ writer.Write(".test.txt.sozip.idx", new MemoryStream(indexData.ToByteArray()));
+ }
+
+ memoryStream.Position = 0;
+
+ // Test with ZipReader
+ using Stream stream = new ForwardOnlyStream(memoryStream);
+ using var reader = ZipReader.Open(stream);
+
+ var foundRegular = false;
+ var foundIndex = false;
+
+ while (await reader.MoveToNextEntryAsync())
+ {
+ if (reader.Entry.Key == "test.txt")
+ {
+ foundRegular = true;
+ Assert.False(reader.Entry.IsSozipIndexFile);
+ Assert.False(reader.Entry.IsSozip);
+ }
+ else if (reader.Entry.Key == ".test.txt.sozip.idx")
+ {
+ foundIndex = true;
+ Assert.True(reader.Entry.IsSozipIndexFile);
+ }
}
+
+ Assert.True(foundRegular, "Regular entry not found");
+ Assert.True(foundIndex, "Index entry not found");
}
}
From 9058645feae652505042663a14df2de3a4234b64 Mon Sep 17 00:00:00 2001
From: Adam Hathcock
Date: Thu, 27 Nov 2025 10:49:19 +0000
Subject: [PATCH 7/9] sozip writing and validation
---
.../Writers/Zip/ZipCentralDirectoryEntry.cs | 1 +
src/SharpCompress/Writers/Zip/ZipWriter.cs | 99 ++++++++++++++++++-
tests/SharpCompress.Test/TestBase.cs | 20 +++-
.../Zip/SoZipWriterTests.cs | 93 +++++++++++++++++
4 files changed, 208 insertions(+), 5 deletions(-)
diff --git a/src/SharpCompress/Writers/Zip/ZipCentralDirectoryEntry.cs b/src/SharpCompress/Writers/Zip/ZipCentralDirectoryEntry.cs
index 6816859a2..a9fb37ad9 100644
--- a/src/SharpCompress/Writers/Zip/ZipCentralDirectoryEntry.cs
+++ b/src/SharpCompress/Writers/Zip/ZipCentralDirectoryEntry.cs
@@ -34,6 +34,7 @@ ArchiveEncoding archiveEncoding
internal ulong Decompressed { get; set; }
internal ushort Zip64HeaderOffset { get; set; }
internal ulong HeaderOffset { get; }
+ internal string FileName => fileName;
internal uint Write(Stream outputStream)
{
diff --git a/src/SharpCompress/Writers/Zip/ZipWriter.cs b/src/SharpCompress/Writers/Zip/ZipWriter.cs
index e70dba060..fbffb206a 100644
--- a/src/SharpCompress/Writers/Zip/ZipWriter.cs
+++ b/src/SharpCompress/Writers/Zip/ZipWriter.cs
@@ -8,6 +8,7 @@
using SharpCompress.Common;
using SharpCompress.Common.Zip;
using SharpCompress.Common.Zip.Headers;
+using SharpCompress.Common.Zip.SOZip;
using SharpCompress.Compressors;
using SharpCompress.Compressors.BZip2;
using SharpCompress.Compressors.Deflate;
@@ -122,12 +123,21 @@ public Stream WriteToStream(string entryPath, ZipWriterEntryOptions options)
var headersize = (uint)WriteHeader(entryPath, options, entry, useZip64);
streamPosition += headersize;
+
+ // Determine if SOZip should be used for this entry
+ var useSozip =
+ (options.EnableSOZip ?? enableSOZip)
+ && compression == ZipCompressionMethod.Deflate
+ && OutputStream.CanSeek;
+
return new ZipWritingStream(
this,
OutputStream.NotNull(),
entry,
compression,
- options.CompressionLevel ?? compressionLevel
+ options.CompressionLevel ?? compressionLevel,
+ useSozip,
+ useSozip ? sozipChunkSize : 0
);
}
@@ -309,6 +319,64 @@ private void WriteFooter(uint crc, uint compressed, uint uncompressed)
OutputStream.Write(intBuf);
}
+ private void WriteSozipIndexFile(
+ ZipCentralDirectoryEntry dataEntry,
+ SOZipDeflateStream sozipStream
+ )
+ {
+ var indexFileName = SOZipIndex.GetIndexFileName(dataEntry.FileName);
+
+ // Create the SOZip index
+ var index = new SOZipIndex(
+ chunkSize: sozipStream.ChunkSize,
+ uncompressedSize: sozipStream.UncompressedBytesWritten,
+ compressedSize: sozipStream.CompressedBytesWritten,
+ compressedOffsets: sozipStream.CompressedOffsets
+ );
+
+ var indexBytes = index.ToByteArray();
+
+ // Calculate CRC for index data
+ var crc = new CRC32();
+ crc.SlurpBlock(indexBytes, 0, indexBytes.Length);
+ var indexCrc = (uint)crc.Crc32Result;
+
+ // Write the index file as a stored (uncompressed) entry
+ var indexEntry = new ZipCentralDirectoryEntry(
+ ZipCompressionMethod.None,
+ indexFileName,
+ (ulong)streamPosition,
+ WriterOptions.ArchiveEncoding
+ )
+ {
+ ModificationTime = DateTime.Now,
+ };
+
+ // Write the local file header for index
+ var indexOptions = new ZipWriterEntryOptions { CompressionType = CompressionType.None };
+ var headerSize = (uint)WriteHeader(indexFileName, indexOptions, indexEntry, isZip64);
+ streamPosition += headerSize;
+
+ // Write the index data directly
+ OutputStream.Write(indexBytes, 0, indexBytes.Length);
+
+ // Finalize the index entry
+ indexEntry.Crc = indexCrc;
+ indexEntry.Compressed = (ulong)indexBytes.Length;
+ indexEntry.Decompressed = (ulong)indexBytes.Length;
+
+ if (OutputStream.CanSeek)
+ {
+ // Update the header with sizes and CRC
+ OutputStream.Position = (long)(indexEntry.HeaderOffset + 14);
+ WriteFooter(indexCrc, (uint)indexBytes.Length, (uint)indexBytes.Length);
+ OutputStream.Position = streamPosition + indexBytes.Length;
+ }
+
+ streamPosition += indexBytes.Length;
+ entries.Add(indexEntry);
+ }
+
private void WriteEndRecord(ulong size)
{
var zip64EndOfCentralDirectoryNeeded =
@@ -390,7 +458,10 @@ internal class ZipWritingStream : Stream
private readonly ZipWriter writer;
private readonly ZipCompressionMethod zipCompressionMethod;
private readonly int compressionLevel;
+ private readonly bool useSozip;
+ private readonly int sozipChunkSize;
private SharpCompressStream? counting;
+ private SOZipDeflateStream? sozipStream;
private ulong decompressed;
// Flag to prevent throwing exceptions on Dispose
@@ -402,7 +473,9 @@ internal ZipWritingStream(
Stream originalStream,
ZipCentralDirectoryEntry entry,
ZipCompressionMethod zipCompressionMethod,
- int compressionLevel
+ int compressionLevel,
+ bool useSozip = false,
+ int sozipChunkSize = 0
)
{
this.writer = writer;
@@ -411,6 +484,8 @@ int compressionLevel
this.entry = entry;
this.zipCompressionMethod = zipCompressionMethod;
this.compressionLevel = compressionLevel;
+ this.useSozip = useSozip;
+ this.sozipChunkSize = sozipChunkSize;
writeStream = GetWriteStream(originalStream);
}
@@ -440,6 +515,15 @@ private Stream GetWriteStream(Stream writeStream)
}
case ZipCompressionMethod.Deflate:
{
+ if (useSozip && sozipChunkSize > 0)
+ {
+ sozipStream = new SOZipDeflateStream(
+ counting,
+ (CompressionLevel)compressionLevel,
+ sozipChunkSize
+ );
+ return sozipStream;
+ }
return new DeflateStream(
counting,
CompressionMode.Compress,
@@ -586,7 +670,18 @@ protected override void Dispose(bool disposing)
writer.WriteFooter(entry.Crc, compressedvalue, decompressedvalue);
writer.streamPosition += (long)entry.Compressed + 16;
}
+
writer.entries.Add(entry);
+
+ // Write SOZip index file if SOZip was used and file meets minimum size
+ if (
+ useSozip
+ && sozipStream is not null
+ && entry.Decompressed >= (ulong)writer.sozipMinFileSize
+ )
+ {
+ writer.WriteSozipIndexFile(entry, sozipStream);
+ }
}
}
diff --git a/tests/SharpCompress.Test/TestBase.cs b/tests/SharpCompress.Test/TestBase.cs
index 184e64420..0a091de52 100644
--- a/tests/SharpCompress.Test/TestBase.cs
+++ b/tests/SharpCompress.Test/TestBase.cs
@@ -3,6 +3,7 @@
using System.IO;
using System.Linq;
using System.Text;
+using SharpCompress.Common.Zip.SOZip;
using SharpCompress.Readers;
using Xunit;
@@ -45,7 +46,7 @@ protected TestBase()
public void Dispose() => Directory.Delete(SCRATCH_BASE_PATH, true);
- public void VerifyFiles()
+ public void VerifyFiles(bool skipSoIndexes = false)
{
if (UseExtensionInsteadOfNameToVerify)
{
@@ -53,7 +54,7 @@ public void VerifyFiles()
}
else
{
- VerifyFilesByName();
+ VerifyFilesByName(skipSoIndexes);
}
}
@@ -72,10 +73,23 @@ public void VerifyFilesEx()
}
}
- protected void VerifyFilesByName()
+ private void VerifyFilesByName(bool skipSoIndexes)
{
var extracted = Directory
.EnumerateFiles(SCRATCH_FILES_PATH, "*.*", SearchOption.AllDirectories)
+ .Where(x =>
+ {
+ if (
+ skipSoIndexes
+ && Path.GetFileName(x)
+ .EndsWith(SOZipIndex.INDEX_EXTENSION, StringComparison.OrdinalIgnoreCase)
+ )
+ {
+ return false;
+ }
+
+ return true;
+ })
.ToLookup(path => path.Substring(SCRATCH_FILES_PATH.Length));
var original = Directory
.EnumerateFiles(ORIGINAL_FILES_PATH, "*.*", SearchOption.AllDirectories)
diff --git a/tests/SharpCompress.Test/Zip/SoZipWriterTests.cs b/tests/SharpCompress.Test/Zip/SoZipWriterTests.cs
index dde04a92c..42b9a314a 100644
--- a/tests/SharpCompress.Test/Zip/SoZipWriterTests.cs
+++ b/tests/SharpCompress.Test/Zip/SoZipWriterTests.cs
@@ -5,6 +5,7 @@
using SharpCompress.Archives.Zip;
using SharpCompress.Common;
using SharpCompress.Common.Zip.SOZip;
+using SharpCompress.Readers;
using SharpCompress.Writers;
using SharpCompress.Writers.Zip;
using Xunit;
@@ -196,4 +197,96 @@ public void ZipWriterEntryOptions_SOZipDefaults()
Assert.Null(options.EnableSOZip);
}
+
+ [Fact]
+ public void SOZip_RoundTrip_CompressAndDecompress()
+ {
+ // Create a SOZip archive from Original files
+ var archivePath = Path.Combine(SCRATCH2_FILES_PATH, "test.sozip.zip");
+
+ using (var stream = File.Create(archivePath))
+ {
+ var options = new ZipWriterOptions(CompressionType.Deflate)
+ {
+ EnableSOZip = true,
+ SOZipMinFileSize = 1024, // 1KB to ensure test files qualify
+ LeaveStreamOpen = false,
+ };
+
+ using var writer = new ZipWriter(stream, options);
+
+ // Write all files from Original directory
+ var files = Directory.GetFiles(ORIGINAL_FILES_PATH, "*", SearchOption.AllDirectories);
+ foreach (var filePath in files)
+ {
+ var relativePath = filePath
+ .Substring(ORIGINAL_FILES_PATH.Length + 1)
+ .Replace('\\', '/');
+ using var fileStream = File.OpenRead(filePath);
+ writer.Write(relativePath, fileStream, new ZipWriterEntryOptions());
+ }
+ }
+
+ // Validate the archive was created and has files
+ Assert.True(File.Exists(archivePath));
+
+ // Validate the archive has SOZip entries
+ using (var stream = File.OpenRead(archivePath))
+ {
+ using var archive = ZipArchive.Open(stream);
+
+ var allEntries = archive.Entries.ToList();
+
+ // Archive should have files
+ Assert.NotEmpty(allEntries);
+
+ var sozipIndexEntries = allEntries.Where(e => e.IsSozipIndexFile).ToList();
+
+ // Should have at least one SOZip index file
+ Assert.NotEmpty(sozipIndexEntries);
+
+ // Verify index files have valid SOZip index data
+ foreach (var indexEntry in sozipIndexEntries)
+ {
+ // Check that the entry is stored (not compressed)
+ Assert.Equal(CompressionType.None, indexEntry.CompressionType);
+
+ using var indexStream = indexEntry.OpenEntryStream();
+ using var memStream = new MemoryStream();
+ indexStream.CopyTo(memStream);
+ var indexBytes = memStream.ToArray();
+
+ // Debug: Check first 4 bytes
+ Assert.True(
+ indexBytes.Length >= 4,
+ $"Index file too small: {indexBytes.Length} bytes"
+ );
+
+ // Should be able to parse the index without exception
+ var index = SOZipIndex.Read(indexBytes);
+ Assert.Equal(SOZipIndex.SOZIP_VERSION, index.Version);
+ Assert.True(index.ChunkSize > 0);
+ Assert.True(index.UncompressedSize > 0);
+ Assert.True(index.OffsetCount > 0);
+
+ // Verify there's a corresponding data file
+ var mainFileName = SOZipIndex.GetMainFileName(indexEntry.Key!);
+ Assert.NotNull(mainFileName);
+ Assert.Contains(allEntries, e => e.Key == mainFileName);
+ }
+ }
+
+ // Read and decompress the archive
+ using (var stream = File.OpenRead(archivePath))
+ {
+ using var reader = ReaderFactory.Open(stream);
+ reader.WriteAllToDirectory(
+ SCRATCH_FILES_PATH,
+ new ExtractionOptions { ExtractFullPath = true }
+ );
+ }
+
+ // Verify extracted files match originals
+ VerifyFiles(true);
+ }
}
From 0dc63223abd2b71c9ea6878cae4c68c209e9e509 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 5 Jan 2026 17:21:38 +0000
Subject: [PATCH 8/9] Merge master branch and resolve FORMATS.md conflict
Co-authored-by: adamhathcock <527620+adamhathcock@users.noreply.github.com>
---
.config/dotnet-tools.json | 2 +-
.github/COPILOT_AGENT_README.md | 15 -
.github/prompts/plan-async.prompt.md | 25 +
.github/prompts/plan-for-next.prompt.md | 123 +
.github/workflows/NUGET_RELEASE.md | 155 +
.github/workflows/TESTING.md | 120 +
.github/workflows/dotnetcore.yml | 25 -
.github/workflows/nuget-release.yml | 61 +
.gitignore | 2 +-
.vscode/extensions.json | 9 +
.vscode/launch.json | 97 +
.vscode/settings.json | 29 +
.vscode/tasks.json | 178 +
AGENTS.md | 71 +-
Directory.Packages.props | 15 +-
FORMATS.md | 26 +-
README.md | 2 +-
SharpCompress.sln | 2 +-
USAGE.md | 64 +-
build/Program.cs | 177 +-
build/build.csproj | 2 +-
build/packages.lock.json | 14 +-
global.json | 2 +-
src/SharpCompress/Archives/AbstractArchive.cs | 52 +-
src/SharpCompress/Archives/IArchive.cs | 6 -
.../Archives/IArchiveEntryExtensions.cs | 231 +-
.../Archives/IArchiveExtensions.cs | 195 +-
.../Archives/IArchiveExtractionListener.cs | 10 -
src/SharpCompress/Archives/Rar/RarArchive.cs | 2 +
.../Archives/Rar/RarArchiveEntry.cs | 8 +-
.../Archives/SevenZip/SevenZipArchive.cs | 159 +-
src/SharpCompress/AssemblyInfo.cs | 3 +-
src/SharpCompress/Common/Ace/AceCrc.cs | 61 +
src/SharpCompress/Common/Ace/AceEntry.cs | 68 +
src/SharpCompress/Common/Ace/AceFilePart.cs | 52 +
src/SharpCompress/Common/Ace/AceVolume.cs | 35 +
.../Common/Ace/Headers/AceFileHeader.cs | 171 +
.../Common/Ace/Headers/AceHeader.cs | 153 +
.../Common/Ace/Headers/AceMainHeader.cs | 97 +
.../Common/Ace/Headers/CompressionQuality.cs | 16 +
.../Common/Ace/Headers/CompressionType.cs | 13 +
.../Common/Ace/Headers/HeaderFlags.cs | 33 +
.../Common/Ace/Headers/HostOS.cs | 22 +
.../Common/ArchiveExtractionEventArgs.cs | 10 -
src/SharpCompress/Common/ArchiveType.cs | 1 +
.../Common/Arj/Headers/ArjHeader.cs | 22 +-
.../Common/CompressedBytesReadEventArgs.cs | 25 -
src/SharpCompress/Common/CompressionType.cs | 1 +
src/SharpCompress/Common/ExtractionMethods.cs | 9 +-
.../FilePartExtractionBeginEventArgs.cs | 28 -
.../Common/IExtractionListener.cs | 7 -
src/SharpCompress/Common/ProgressReport.cs | 43 +
.../Common/ReaderExtractionEventArgs.cs | 17 -
.../Common/Tar/Headers/TarHeader.cs | 133 +-
.../Tar/Headers/TarHeaderWriteFormat.cs | 7 +
.../Common/Zip/WinzipAesEncryptionData.cs | 24 +-
src/SharpCompress/Common/Zip/ZipFilePart.cs | 2 +-
.../Compressors/BZip2/CBZip2OutputStream.cs | 6 +
.../Compressors/LZMA/LzmaStream.cs | 18 +-
.../Compressors/LZMA/Registry.cs | 2 +-
.../Rar/MultiVolumeReadOnlyStream.cs | 38 +-
.../Compressors/Rar/RarStream.cs | 4 +-
.../Compressors/ZStandard/BitOperations.cs | 311 +
.../ZStandard/CompressionStream.cs | 301 +
.../Compressors/ZStandard/Compressor.cs | 204 +
.../Compressors/ZStandard/Constants.cs | 8 +
.../ZStandard/DecompressionStream.cs | 293 +
.../Compressors/ZStandard/Decompressor.cs | 176 +
.../Compressors/ZStandard/JobThreadPool.cs | 141 +
.../Compressors/ZStandard/SafeHandles.cs | 163 +
.../ZStandard/SynchronizationWrapper.cs | 22 +
.../Compressors/ZStandard/ThrowHelper.cs | 48 +
.../Compressors/ZStandard/UnmanagedObject.cs | 18 +
.../ZStandard/Unsafe/Allocations.cs | 52 +
.../ZStandard/Unsafe/BIT_CStream_t.cs | 14 +
.../ZStandard/Unsafe/BIT_DStream_status.cs | 16 +
.../ZStandard/Unsafe/BIT_DStream_t.cs | 13 +
.../Compressors/ZStandard/Unsafe/Bits.cs | 60 +
.../Compressors/ZStandard/Unsafe/Bitstream.cs | 739 +
.../ZStandard/Unsafe/BlockSummary.cs | 8 +
.../ZStandard/Unsafe/COVER_best_s.cs | 20 +
.../ZStandard/Unsafe/COVER_ctx_t.cs | 19 +
.../ZStandard/Unsafe/COVER_dictSelection.cs | 11 +
.../ZStandard/Unsafe/COVER_epoch_info_t.cs | 10 +
.../ZStandard/Unsafe/COVER_map_pair_t_s.cs | 7 +
.../ZStandard/Unsafe/COVER_map_s.cs | 9 +
.../ZStandard/Unsafe/COVER_segment_t.cs | 11 +
.../Unsafe/COVER_tryParameters_data_s.cs | 12 +
.../Compressors/ZStandard/Unsafe/Clevels.cs | 849 ++
.../Compressors/ZStandard/Unsafe/Compiler.cs | 61 +
.../Compressors/ZStandard/Unsafe/Cover.cs | 444 +
.../ZStandard/Unsafe/DTableDesc.cs | 12 +
.../ZStandard/Unsafe/EStats_ress_t.cs | 13 +
.../ZStandard/Unsafe/EntropyCommon.cs | 447 +
.../ZStandard/Unsafe/ErrorPrivate.cs | 110 +
.../ZStandard/Unsafe/EstimatedBlockSize.cs | 7 +
.../ZStandard/Unsafe/FASTCOVER_accel_t.cs | 19 +
.../ZStandard/Unsafe/FASTCOVER_ctx_t.cs | 19 +
.../Unsafe/FASTCOVER_tryParameters_data_s.cs | 12 +
.../Compressors/ZStandard/Unsafe/FPStats.cs | 7 +
.../ZStandard/Unsafe/FSE_CState_t.cs | 16 +
.../ZStandard/Unsafe/FSE_DState_t.cs | 12 +
.../ZStandard/Unsafe/FSE_DTableHeader.cs | 8 +
.../ZStandard/Unsafe/FSE_DecompressWksp.cs | 6 +
.../ZStandard/Unsafe/FSE_decode_t.cs | 8 +
.../ZStandard/Unsafe/FSE_repeat.cs | 13 +
.../Unsafe/FSE_symbolCompressionTransform.cs | 10 +
.../Compressors/ZStandard/Unsafe/Fastcover.cs | 761 ++
.../ZStandard/Unsafe/Fingerprint.cs | 7 +
.../Compressors/ZStandard/Unsafe/Fse.cs | 198 +
.../ZStandard/Unsafe/FseCompress.cs | 782 ++
.../ZStandard/Unsafe/FseDecompress.cs | 462 +
.../ZStandard/Unsafe/HIST_checkInput_e.cs | 7 +
.../ZStandard/Unsafe/HUF_CStream_t.cs | 22 +
.../ZStandard/Unsafe/HUF_CTableHeader.cs | 8 +
.../Unsafe/HUF_CompressWeightsWksp.cs | 9 +
.../ZStandard/Unsafe/HUF_DEltX1.cs | 11 +
.../ZStandard/Unsafe/HUF_DEltX2.cs | 12 +
.../Unsafe/HUF_DecompressFastArgs.cs | 49 +
.../Unsafe/HUF_ReadDTableX1_Workspace.cs | 10 +
.../Unsafe/HUF_ReadDTableX2_Workspace.cs | 307 +
.../ZStandard/Unsafe/HUF_WriteCTableWksp.cs | 10 +
.../Unsafe/HUF_buildCTable_wksp_tables.cs | 739 +
.../ZStandard/Unsafe/HUF_compress_tables_t.cs | 280 +
.../ZStandard/Unsafe/HUF_flags_e.cs | 44 +
.../ZStandard/Unsafe/HUF_nbStreams_e.cs | 7 +
.../ZStandard/Unsafe/HUF_repeat.cs | 13 +
.../Compressors/ZStandard/Unsafe/Hist.cs | 273 +
.../ZStandard/Unsafe/HufCompress.cs | 1825 +++
.../ZStandard/Unsafe/HufDecompress.cs | 2505 ++++
.../Compressors/ZStandard/Unsafe/Mem.cs | 162 +
.../Compressors/ZStandard/Unsafe/Pool.cs | 122 +
.../ZStandard/Unsafe/RSyncState_t.cs | 8 +
.../Compressors/ZStandard/Unsafe/Range.cs | 14 +
.../ZStandard/Unsafe/RawSeqStore_t.cs | 29 +
.../ZStandard/Unsafe/RoundBuff_t.cs | 28 +
.../ZStandard/Unsafe/SeqCollector.cs | 9 +
.../Compressors/ZStandard/Unsafe/SeqDef_s.cs | 14 +
.../ZStandard/Unsafe/SeqStore_t.cs | 27 +
.../ZStandard/Unsafe/SerialState.cs | 23 +
.../ZStandard/Unsafe/SymbolEncodingType_e.cs | 9 +
.../Compressors/ZStandard/Unsafe/SyncPoint.cs | 10 +
.../ZStandard/Unsafe/XXH32_canonical_t.cs | 10 +
.../ZStandard/Unsafe/XXH32_state_s.cs | 34 +
.../ZStandard/Unsafe/XXH64_canonical_t.cs | 9 +
.../ZStandard/Unsafe/XXH64_state_s.cs | 34 +
.../ZStandard/Unsafe/XXH_alignment.cs | 14 +
.../ZStandard/Unsafe/XXH_errorcode.cs | 13 +
.../Compressors/ZStandard/Unsafe/Xxhash.cs | 626 +
.../ZStandard/Unsafe/ZDICT_cover_params_t.cs | 30 +
.../Unsafe/ZDICT_fastCover_params_t.cs | 32 +
.../ZStandard/Unsafe/ZDICT_legacy_params_t.cs | 8 +
.../ZStandard/Unsafe/ZDICT_params_t.cs | 20 +
.../ZStandard/Unsafe/ZSTDMT_CCtxPool.cs | 12 +
.../ZStandard/Unsafe/ZSTDMT_CCtx_s.cs | 32 +
.../ZStandard/Unsafe/ZSTDMT_bufferPool_s.cs | 11 +
.../ZStandard/Unsafe/ZSTDMT_jobDescription.cs | 61 +
.../Unsafe/ZSTD_BlockCompressor_f.cs | 12 +
.../ZStandard/Unsafe/ZSTD_BuildCTableWksp.cs | 7 +
.../ZStandard/Unsafe/ZSTD_BuildSeqStore_e.cs | 7 +
.../ZStandard/Unsafe/ZSTD_CCtx_params_s.cs | 86 +
.../ZStandard/Unsafe/ZSTD_CCtx_s.cs | 91 +
.../ZStandard/Unsafe/ZSTD_CDict_s.cs | 30 +
.../ZStandard/Unsafe/ZSTD_CParamMode_e.cs | 29 +
.../ZStandard/Unsafe/ZSTD_DCtx_s.cs | 95 +
.../ZStandard/Unsafe/ZSTD_DDictHashSet.cs | 9 +
.../ZStandard/Unsafe/ZSTD_DDict_s.cs | 15 +
.../ZStandard/Unsafe/ZSTD_DefaultPolicy_e.cs | 7 +
.../ZStandard/Unsafe/ZSTD_EndDirective.cs | 21 +
.../ZStandard/Unsafe/ZSTD_ErrorCode.cs | 59 +
.../ZStandard/Unsafe/ZSTD_MatchState_t.cs | 66 +
.../ZStandard/Unsafe/ZSTD_OffsetInfo.cs | 7 +
.../ZStandard/Unsafe/ZSTD_OptPrice_e.cs | 7 +
.../ZStandard/Unsafe/ZSTD_ResetDirective.cs | 8 +
.../ZStandard/Unsafe/ZSTD_Sequence.cs | 40 +
.../ZStandard/Unsafe/ZSTD_SequenceLength.cs | 7 +
.../ZStandard/Unsafe/ZSTD_SequencePosition.cs | 13 +
.../ZStandard/Unsafe/ZSTD_blockSplitCtx.cs | 12 +
.../ZStandard/Unsafe/ZSTD_blockState_t.cs | 8 +
.../ZStandard/Unsafe/ZSTD_bounds.cs | 8 +
.../ZStandard/Unsafe/ZSTD_bufferMode_e.cs | 11 +
.../Unsafe/ZSTD_buffered_policy_e.cs | 12 +
.../ZStandard/Unsafe/ZSTD_cParameter.cs | 218 +
.../ZStandard/Unsafe/ZSTD_cStreamStage.cs | 8 +
.../Unsafe/ZSTD_compResetPolicy_e.cs | 14 +
.../Unsafe/ZSTD_compressedBlockState_t.cs | 7 +
.../Unsafe/ZSTD_compressionParameters.cs | 44 +
.../Unsafe/ZSTD_compressionStage_e.cs | 12 +
.../ZStandard/Unsafe/ZSTD_customMem.cs | 15 +
.../ZStandard/Unsafe/ZSTD_cwksp.cs | 110 +
.../Unsafe/ZSTD_cwksp_alloc_phase_e.cs | 12 +
.../Unsafe/ZSTD_cwksp_static_alloc_e.cs | 12 +
.../ZStandard/Unsafe/ZSTD_dParameter.cs | 38 +
.../ZStandard/Unsafe/ZSTD_dStage.cs | 13 +
.../ZStandard/Unsafe/ZSTD_dStreamStage.cs | 10 +
.../ZStandard/Unsafe/ZSTD_dictAttachPref_e.cs | 16 +
.../Unsafe/ZSTD_dictContentType_e.cs | 13 +
.../ZStandard/Unsafe/ZSTD_dictLoadMethod_e.cs | 10 +
.../ZStandard/Unsafe/ZSTD_dictMode_e.cs | 9 +
.../Unsafe/ZSTD_dictTableLoadMethod_e.cs | 7 +
.../ZStandard/Unsafe/ZSTD_dictUses_e.cs | 13 +
.../Unsafe/ZSTD_entropyCTablesMetadata_t.cs | 7 +
.../ZStandard/Unsafe/ZSTD_entropyCTables_t.cs | 7 +
.../ZStandard/Unsafe/ZSTD_entropyDTables_t.cs | 1342 ++
.../Unsafe/ZSTD_forceIgnoreChecksum_e.cs | 8 +
.../ZStandard/Unsafe/ZSTD_format_e.cs | 12 +
.../ZStandard/Unsafe/ZSTD_frameHeader.cs | 21 +
.../ZStandard/Unsafe/ZSTD_frameParameters.cs | 13 +
.../ZStandard/Unsafe/ZSTD_frameProgression.cs | 22 +
.../ZStandard/Unsafe/ZSTD_frameSizeInfo.cs | 14 +
.../ZStandard/Unsafe/ZSTD_frameType_e.cs | 7 +
.../Unsafe/ZSTD_fseCTablesMetadata_t.cs | 18 +
.../ZStandard/Unsafe/ZSTD_fseCTables_t.cs | 11 +
.../ZStandard/Unsafe/ZSTD_fseState.cs | 7 +
.../ZStandard/Unsafe/ZSTD_getAllMatchesFn.cs | 15 +
.../Unsafe/ZSTD_hufCTablesMetadata_t.cs | 16 +
.../ZStandard/Unsafe/ZSTD_hufCTables_t.cs | 279 +
.../ZStandard/Unsafe/ZSTD_inBuffer_s.cs | 16 +
.../Unsafe/ZSTD_indexResetPolicy_e.cs | 12 +
.../ZStandard/Unsafe/ZSTD_litLocation_e.cs | 13 +
.../Unsafe/ZSTD_literalCompressionMode_e.cs | 16 +
.../ZStandard/Unsafe/ZSTD_localDict.cs | 10 +
.../ZStandard/Unsafe/ZSTD_longLengthType_e.cs | 14 +
.../ZStandard/Unsafe/ZSTD_longOffset_e.cs | 7 +
.../ZStandard/Unsafe/ZSTD_match_t.cs | 13 +
.../ZStandard/Unsafe/ZSTD_nextInputType_e.cs | 11 +
.../ZStandard/Unsafe/ZSTD_optLdm_t.cs | 17 +
.../ZStandard/Unsafe/ZSTD_optimal_t.cs | 19 +
.../ZStandard/Unsafe/ZSTD_outBuffer_s.cs | 13 +
.../ZStandard/Unsafe/ZSTD_overlap_e.cs | 7 +
.../ZStandard/Unsafe/ZSTD_paramSwitch_e.cs | 13 +
.../ZStandard/Unsafe/ZSTD_parameters.cs | 7 +
.../ZStandard/Unsafe/ZSTD_prefixDict_s.cs | 8 +
.../Unsafe/ZSTD_refMultipleDDicts_e.cs | 8 +
.../ZStandard/Unsafe/ZSTD_resetTarget_e.cs | 7 +
.../ZStandard/Unsafe/ZSTD_seqSymbol.cs | 17 +
.../ZStandard/Unsafe/ZSTD_seqSymbol_header.cs | 10 +
.../ZStandard/Unsafe/ZSTD_sequenceFormat_e.cs | 10 +
.../ZStandard/Unsafe/ZSTD_strategy.cs | 15 +
.../Unsafe/ZSTD_symbolEncodingTypeStats_t.cs | 16 +
.../Unsafe/ZSTD_tableFillPurpose_e.cs | 7 +
.../ZStandard/Unsafe/ZSTD_window_t.cs | 25 +
.../Compressors/ZStandard/Unsafe/Zdict.cs | 640 +
.../Compressors/ZStandard/Unsafe/Zstd.cs | 10 +
.../ZStandard/Unsafe/ZstdCommon.cs | 48 +
.../ZStandard/Unsafe/ZstdCompress.cs | 11225 ++++++++++++++++
.../ZStandard/Unsafe/ZstdCompressInternal.cs | 1444 ++
.../ZStandard/Unsafe/ZstdCompressLiterals.cs | 314 +
.../ZStandard/Unsafe/ZstdCompressSequences.cs | 1211 ++
.../Unsafe/ZstdCompressSuperblock.cs | 976 ++
.../Compressors/ZStandard/Unsafe/ZstdCwksp.cs | 581 +
.../Compressors/ZStandard/Unsafe/ZstdDdict.cs | 292 +
.../ZStandard/Unsafe/ZstdDecompress.cs | 3420 +++++
.../ZStandard/Unsafe/ZstdDecompressBlock.cs | 3218 +++++
.../Unsafe/ZstdDecompressInternal.cs | 394 +
.../ZStandard/Unsafe/ZstdDoubleFast.cs | 1118 ++
.../Compressors/ZStandard/Unsafe/ZstdFast.cs | 1209 ++
.../ZStandard/Unsafe/ZstdInternal.cs | 638 +
.../Compressors/ZStandard/Unsafe/ZstdLazy.cs | 4661 +++++++
.../Compressors/ZStandard/Unsafe/ZstdLdm.cs | 940 ++
.../ZStandard/Unsafe/ZstdLdmGeartab.cs | 539 +
.../Compressors/ZStandard/Unsafe/ZstdOpt.cs | 2254 ++++
.../ZStandard/Unsafe/ZstdPresplit.cs | 295 +
.../ZStandard/Unsafe/ZstdmtCompress.cs | 1894 +++
.../ZStandard/Unsafe/_wksps_e__Union.cs | 16 +
.../ZStandard/Unsafe/algo_time_t.cs | 13 +
.../ZStandard/Unsafe/base_directive_e.cs | 7 +
.../ZStandard/Unsafe/blockProperties_t.cs | 8 +
.../ZStandard/Unsafe/blockType_e.cs | 9 +
.../Compressors/ZStandard/Unsafe/buffer_s.cs | 15 +
.../Compressors/ZStandard/Unsafe/dictItem.cs | 8 +
.../Compressors/ZStandard/Unsafe/inBuff_t.cs | 12 +
.../ZStandard/Unsafe/ldmEntry_t.cs | 7 +
.../ZStandard/Unsafe/ldmMatchCandidate_t.cs | 9 +
.../ZStandard/Unsafe/ldmParams_t.cs | 22 +
.../ZStandard/Unsafe/ldmRollingHashState_t.cs | 7 +
.../ZStandard/Unsafe/ldmState_t.cs | 170 +
.../Compressors/ZStandard/Unsafe/nodeElt_s.cs | 12 +
.../ZStandard/Unsafe/offsetCount_t.cs | 7 +
.../ZStandard/Unsafe/optState_t.cs | 53 +
.../Compressors/ZStandard/Unsafe/rankPos.cs | 7 +
.../ZStandard/Unsafe/rankValCol_t.cs | 6 +
.../Compressors/ZStandard/Unsafe/rawSeq.cs | 13 +
.../ZStandard/Unsafe/repcodes_s.cs | 6 +
.../ZStandard/Unsafe/searchMethod_e.cs | 8 +
.../ZStandard/Unsafe/seqState_t.cs | 17 +
.../ZStandard/Unsafe/seqStoreSplits.cs | 11 +
.../Compressors/ZStandard/Unsafe/seq_t.cs | 8 +
.../ZStandard/Unsafe/sortedSymbol_t.cs | 6 +
.../ZStandard/Unsafe/streaming_operation.cs | 8 +
.../Compressors/ZStandard/UnsafeHelper.cs | 107 +
.../Compressors/ZStandard/ZStandardStream.cs | 2 +-
.../ZStandard/ZstandardConstants.cs | 6 -
.../Compressors/ZStandard/ZstdException.cs | 12 +
src/SharpCompress/Factories/AceFactory.cs | 37 +
src/SharpCompress/Factories/ArjFactory.cs | 7 +-
src/SharpCompress/Factories/Factory.cs | 1 +
src/SharpCompress/IO/ListeningStream.cs | 97 -
.../IO/ProgressReportingStream.cs | 160 +
src/SharpCompress/IO/SharpCompressStream.cs | 20 +-
.../Polyfills/StreamExtensions.cs | 24 +
src/SharpCompress/Readers/AbstractReader.cs | 94 +-
src/SharpCompress/Readers/Ace/AceReader.cs | 115 +
.../Readers/Ace/MultiVolumeAceReader.cs | 117 +
.../Readers/Ace/SingleVolumeAceReader.cs | 31 +
src/SharpCompress/Readers/IReader.cs | 5 -
.../Readers/IReaderExtensions.cs | 195 +-
.../Readers/IReaderExtractionListener.cs | 8 -
src/SharpCompress/Readers/Rar/RarReader.cs | 6 +-
src/SharpCompress/Readers/ReaderFactory.cs | 2 +-
src/SharpCompress/Readers/ReaderOptions.cs | 7 +
src/SharpCompress/Readers/ReaderProgress.cs | 21 -
src/SharpCompress/Readers/Zip/ZipReader.cs | 8 +
src/SharpCompress/SharpCompress.csproj | 25 +-
src/SharpCompress/Utility.cs | 66 -
src/SharpCompress/Writers/AbstractWriter.cs | 24 +
src/SharpCompress/Writers/GZip/GZipWriter.cs | 3 +-
src/SharpCompress/Writers/Tar/TarWriter.cs | 10 +-
.../Writers/Tar/TarWriterOptions.cs | 15 +-
src/SharpCompress/Writers/WriterOptions.cs | 7 +
src/SharpCompress/Writers/Zip/ZipWriter.cs | 6 +-
src/SharpCompress/packages.lock.json | 255 +-
.../SharpCompress.Performance.csproj | 2 +-
.../packages.lock.json | 19 +-
.../SharpCompress.Test/Ace/AceReaderTests.cs | 61 +
tests/SharpCompress.Test/ArchiveTests.cs | 2 +-
.../SharpCompress.Test/Arj/ArjReaderTests.cs | 40 +-
tests/SharpCompress.Test/ExtractAll.cs | 46 +
.../ExtractAllEntriesTests.cs | 61 +
.../Mocks/TruncatedStream.cs | 65 +
.../SharpCompress.Test/ProgressReportTests.cs | 605 +
.../SharpCompress.Test/Rar/RarArchiveTests.cs | 84 +
tests/SharpCompress.Test/ReaderTests.cs | 23 +
.../SevenZip/SevenZipArchiveTests.cs | 9 +
.../SharpCompress.Test.csproj | 4 +-
.../Zip/ZipArchiveAsyncTests.cs | 34 +
.../SharpCompress.Test/Zip/ZipReaderTests.cs | 39 +
.../SharpCompress.Test/Zip/ZipWriterTests.cs | 38 +
tests/SharpCompress.Test/packages.lock.json | 117 +-
.../Archives/7Zip.encryptedFiles.7z | Bin 0 -> 59042 bytes
tests/TestArchives/Archives/Ace.encrypted.ace | Bin 0 -> 60234 bytes
.../Archives/Ace.method1-solid.ace | Bin 0 -> 60286 bytes
tests/TestArchives/Archives/Ace.method1.ace | Bin 0 -> 60290 bytes
.../Archives/Ace.method2-solid.ace | Bin 0 -> 60234 bytes
tests/TestArchives/Archives/Ace.method2.ace | Bin 0 -> 60238 bytes
tests/TestArchives/Archives/Ace.store.ace | Bin 0 -> 101196 bytes
.../Archives/Ace.store.largefile.ace | Bin 0 -> 152188 bytes
.../TestArchives/Archives/Ace.store.split.ace | Bin 0 -> 65600 bytes
.../TestArchives/Archives/Ace.store.split.c00 | Bin 0 -> 35692 bytes
349 files changed, 60146 insertions(+), 1241 deletions(-)
delete mode 100644 .github/COPILOT_AGENT_README.md
create mode 100644 .github/prompts/plan-async.prompt.md
create mode 100644 .github/prompts/plan-for-next.prompt.md
create mode 100644 .github/workflows/NUGET_RELEASE.md
create mode 100644 .github/workflows/TESTING.md
delete mode 100644 .github/workflows/dotnetcore.yml
create mode 100644 .github/workflows/nuget-release.yml
create mode 100644 .vscode/extensions.json
create mode 100644 .vscode/launch.json
create mode 100644 .vscode/settings.json
create mode 100644 .vscode/tasks.json
delete mode 100644 src/SharpCompress/Archives/IArchiveExtractionListener.cs
create mode 100644 src/SharpCompress/Common/Ace/AceCrc.cs
create mode 100644 src/SharpCompress/Common/Ace/AceEntry.cs
create mode 100644 src/SharpCompress/Common/Ace/AceFilePart.cs
create mode 100644 src/SharpCompress/Common/Ace/AceVolume.cs
create mode 100644 src/SharpCompress/Common/Ace/Headers/AceFileHeader.cs
create mode 100644 src/SharpCompress/Common/Ace/Headers/AceHeader.cs
create mode 100644 src/SharpCompress/Common/Ace/Headers/AceMainHeader.cs
create mode 100644 src/SharpCompress/Common/Ace/Headers/CompressionQuality.cs
create mode 100644 src/SharpCompress/Common/Ace/Headers/CompressionType.cs
create mode 100644 src/SharpCompress/Common/Ace/Headers/HeaderFlags.cs
create mode 100644 src/SharpCompress/Common/Ace/Headers/HostOS.cs
delete mode 100644 src/SharpCompress/Common/ArchiveExtractionEventArgs.cs
delete mode 100644 src/SharpCompress/Common/CompressedBytesReadEventArgs.cs
delete mode 100644 src/SharpCompress/Common/FilePartExtractionBeginEventArgs.cs
delete mode 100644 src/SharpCompress/Common/IExtractionListener.cs
create mode 100644 src/SharpCompress/Common/ProgressReport.cs
delete mode 100644 src/SharpCompress/Common/ReaderExtractionEventArgs.cs
create mode 100644 src/SharpCompress/Common/Tar/Headers/TarHeaderWriteFormat.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/BitOperations.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/CompressionStream.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Compressor.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Constants.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/DecompressionStream.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Decompressor.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/JobThreadPool.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/SafeHandles.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/SynchronizationWrapper.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/ThrowHelper.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/UnmanagedObject.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Allocations.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/BIT_CStream_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/BIT_DStream_status.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/BIT_DStream_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Bits.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Bitstream.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/BlockSummary.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/COVER_best_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/COVER_ctx_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/COVER_dictSelection.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/COVER_epoch_info_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/COVER_map_pair_t_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/COVER_map_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/COVER_segment_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/COVER_tryParameters_data_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Clevels.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Compiler.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Cover.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/DTableDesc.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/EStats_ress_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/EntropyCommon.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ErrorPrivate.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/EstimatedBlockSize.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FASTCOVER_accel_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FASTCOVER_ctx_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FASTCOVER_tryParameters_data_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FPStats.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FSE_CState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FSE_DState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FSE_DTableHeader.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FSE_DecompressWksp.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FSE_decode_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FSE_repeat.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FSE_symbolCompressionTransform.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Fastcover.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Fingerprint.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Fse.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FseCompress.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/FseDecompress.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HIST_checkInput_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_CStream_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_CTableHeader.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_CompressWeightsWksp.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_DEltX1.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_DEltX2.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_DecompressFastArgs.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_ReadDTableX1_Workspace.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_ReadDTableX2_Workspace.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_WriteCTableWksp.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_buildCTable_wksp_tables.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_compress_tables_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_flags_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_nbStreams_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HUF_repeat.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Hist.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HufCompress.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/HufDecompress.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Mem.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Pool.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/RSyncState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Range.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/RawSeqStore_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/RoundBuff_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/SeqCollector.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/SeqDef_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/SeqStore_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/SerialState.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/SymbolEncodingType_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/SyncPoint.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/XXH32_canonical_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/XXH32_state_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/XXH64_canonical_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/XXH64_state_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/XXH_alignment.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/XXH_errorcode.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Xxhash.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZDICT_cover_params_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZDICT_fastCover_params_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZDICT_legacy_params_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZDICT_params_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTDMT_CCtxPool.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTDMT_CCtx_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTDMT_bufferPool_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTDMT_jobDescription.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_BlockCompressor_f.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_BuildCTableWksp.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_BuildSeqStore_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_CCtx_params_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_CCtx_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_CDict_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_CParamMode_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_DCtx_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_DDictHashSet.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_DDict_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_DefaultPolicy_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_EndDirective.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_ErrorCode.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_MatchState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_OffsetInfo.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_OptPrice_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_ResetDirective.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_Sequence.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_SequenceLength.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_SequencePosition.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_blockSplitCtx.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_blockState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_bounds.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_bufferMode_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_buffered_policy_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_cParameter.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_cStreamStage.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_compResetPolicy_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_compressedBlockState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_compressionParameters.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_compressionStage_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_customMem.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_cwksp.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_cwksp_alloc_phase_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_cwksp_static_alloc_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dParameter.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dStage.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dStreamStage.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dictAttachPref_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dictContentType_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dictLoadMethod_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dictMode_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dictTableLoadMethod_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_dictUses_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_entropyCTablesMetadata_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_entropyCTables_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_entropyDTables_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_forceIgnoreChecksum_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_format_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_frameHeader.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_frameParameters.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_frameProgression.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_frameSizeInfo.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_frameType_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_fseCTablesMetadata_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_fseCTables_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_fseState.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_getAllMatchesFn.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_hufCTablesMetadata_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_hufCTables_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_inBuffer_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_indexResetPolicy_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_litLocation_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_literalCompressionMode_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_localDict.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_longLengthType_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_longOffset_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_match_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_nextInputType_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_optLdm_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_optimal_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_outBuffer_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_overlap_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_paramSwitch_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_parameters.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_prefixDict_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_refMultipleDDicts_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_resetTarget_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_seqSymbol.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_seqSymbol_header.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_sequenceFormat_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_strategy.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_symbolEncodingTypeStats_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_tableFillPurpose_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZSTD_window_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Zdict.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/Zstd.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdCommon.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdCompress.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdCompressInternal.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdCompressLiterals.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdCompressSequences.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdCompressSuperblock.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdCwksp.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdDdict.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdDecompress.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdDecompressBlock.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdDecompressInternal.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdDoubleFast.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdFast.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdInternal.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdLazy.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdLdm.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdLdmGeartab.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdOpt.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdPresplit.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ZstdmtCompress.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/_wksps_e__Union.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/algo_time_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/base_directive_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/blockProperties_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/blockType_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/buffer_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/dictItem.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/inBuff_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ldmEntry_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ldmMatchCandidate_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ldmParams_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ldmRollingHashState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/ldmState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/nodeElt_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/offsetCount_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/optState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/rankPos.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/rankValCol_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/rawSeq.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/repcodes_s.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/searchMethod_e.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/seqState_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/seqStoreSplits.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/seq_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/sortedSymbol_t.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/Unsafe/streaming_operation.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/UnsafeHelper.cs
create mode 100644 src/SharpCompress/Compressors/ZStandard/ZstdException.cs
create mode 100644 src/SharpCompress/Factories/AceFactory.cs
delete mode 100644 src/SharpCompress/IO/ListeningStream.cs
create mode 100644 src/SharpCompress/IO/ProgressReportingStream.cs
create mode 100644 src/SharpCompress/Readers/Ace/AceReader.cs
create mode 100644 src/SharpCompress/Readers/Ace/MultiVolumeAceReader.cs
create mode 100644 src/SharpCompress/Readers/Ace/SingleVolumeAceReader.cs
delete mode 100644 src/SharpCompress/Readers/IReaderExtractionListener.cs
delete mode 100644 src/SharpCompress/Readers/ReaderProgress.cs
create mode 100644 tests/SharpCompress.Test/Ace/AceReaderTests.cs
create mode 100644 tests/SharpCompress.Test/ExtractAll.cs
create mode 100644 tests/SharpCompress.Test/ExtractAllEntriesTests.cs
create mode 100644 tests/SharpCompress.Test/Mocks/TruncatedStream.cs
create mode 100644 tests/SharpCompress.Test/ProgressReportTests.cs
create mode 100644 tests/TestArchives/Archives/7Zip.encryptedFiles.7z
create mode 100644 tests/TestArchives/Archives/Ace.encrypted.ace
create mode 100644 tests/TestArchives/Archives/Ace.method1-solid.ace
create mode 100644 tests/TestArchives/Archives/Ace.method1.ace
create mode 100644 tests/TestArchives/Archives/Ace.method2-solid.ace
create mode 100644 tests/TestArchives/Archives/Ace.method2.ace
create mode 100644 tests/TestArchives/Archives/Ace.store.ace
create mode 100644 tests/TestArchives/Archives/Ace.store.largefile.ace
create mode 100644 tests/TestArchives/Archives/Ace.store.split.ace
create mode 100644 tests/TestArchives/Archives/Ace.store.split.c00
diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json
index 03df23230..cdb3c8d1b 100644
--- a/.config/dotnet-tools.json
+++ b/.config/dotnet-tools.json
@@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"csharpier": {
- "version": "1.2.1",
+ "version": "1.2.5",
"commands": [
"csharpier"
],
diff --git a/.github/COPILOT_AGENT_README.md b/.github/COPILOT_AGENT_README.md
deleted file mode 100644
index 11f6cb5b6..000000000
--- a/.github/COPILOT_AGENT_README.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copilot Coding Agent Configuration
-
-This repository includes a minimal opt-in configuration and CI workflow to allow the GitHub Copilot coding agent to open and validate PRs.
-
-- .copilot-agent.yml: opt-in config for automated agents
-- .github/agents/copilot-agent.yml: detailed agent policy configuration
-- .github/workflows/dotnetcore.yml: CI runs on PRs touching the solution, source, or tests to validate changes
-- AGENTS.md: general instructions for Copilot coding agent with project-specific guidelines
-
-Maintainers can adjust the allowed paths or disable the agent by editing or removing .copilot-agent.yml.
-
-Notes:
-- The agent can create, modify, and delete files within the allowed paths (src, tests, README.md, AGENTS.md)
-- All changes require review before merge
-- If build/test paths are different, update the workflow accordingly; this workflow targets SharpCompress.sln and the SharpCompress.Test test project.
diff --git a/.github/prompts/plan-async.prompt.md b/.github/prompts/plan-async.prompt.md
new file mode 100644
index 000000000..50f853fa2
--- /dev/null
+++ b/.github/prompts/plan-async.prompt.md
@@ -0,0 +1,25 @@
+# Plan: Implement Missing Async Functionality in SharpCompress
+
+SharpCompress has async support for low-level stream operations and Reader/Writer APIs, but critical entry points (Archive.Open, factory methods, initialization) remain synchronous. This plan adds async overloads for all user-facing I/O operations and fixes existing async bugs, enabling full end-to-end async workflows.
+
+## Steps
+
+1. **Add async factory methods** to [ArchiveFactory.cs](src/SharpCompress/Factories/ArchiveFactory.cs), [ReaderFactory.cs](src/SharpCompress/Factories/ReaderFactory.cs), and [WriterFactory.cs](src/SharpCompress/Factories/WriterFactory.cs) with `OpenAsync` and `CreateAsync` overloads accepting `CancellationToken`
+
+2. **Implement async Open methods** on concrete archive types ([ZipArchive.cs](src/SharpCompress/Archives/Zip/ZipArchive.cs), [TarArchive.cs](src/SharpCompress/Archives/Tar/TarArchive.cs), [RarArchive.cs](src/SharpCompress/Archives/Rar/RarArchive.cs), [GZipArchive.cs](src/SharpCompress/Archives/GZip/GZipArchive.cs), [SevenZipArchive.cs](src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs)) and reader types ([ZipReader.cs](src/SharpCompress/Readers/Zip/ZipReader.cs), [TarReader.cs](src/SharpCompress/Readers/Tar/TarReader.cs), etc.)
+
+3. **Convert archive initialization logic to async** including header reading, volume loading, and format signature detection across archive constructors and internal initialization methods
+
+4. **Fix LZMA decoder async bugs** in [LzmaStream.cs](src/SharpCompress/Compressors/LZMA/LzmaStream.cs), [Decoder.cs](src/SharpCompress/Compressors/LZMA/Decoder.cs), and [OutWindow.cs](src/SharpCompress/Compressors/LZMA/OutWindow.cs) to enable true async 7Zip support and remove `NonDisposingStream` workaround
+
+5. **Complete Rar async implementation** by converting `UnpackV2017` methods to async in [UnpackV2017.cs](src/SharpCompress/Compressors/Rar/UnpackV2017.cs) and updating Rar20 decompression
+
+6. **Add comprehensive async tests** covering all new async entry points, cancellation scenarios, and concurrent operations across all archive formats in test files
+
+## Further Considerations
+
+1. **Breaking changes** - Should new async methods be added alongside existing sync methods (non-breaking), or should sync methods eventually be deprecated? Recommend additive approach for backward compatibility.
+
+2. **Performance impact** - Header parsing for formats like Zip/Tar is often small; consider whether truly async parsing adds value vs sync parsing wrapped in Task, or make it conditional based on stream type (network vs file).
+
+3. **7Zip complexity** - The LZMA async bug fix (Step 4) may be challenging due to state management in the decoder; consider whether to scope it separately or implement a simpler workaround that maintains correctness.
diff --git a/.github/prompts/plan-for-next.prompt.md b/.github/prompts/plan-for-next.prompt.md
new file mode 100644
index 000000000..2bdedd974
--- /dev/null
+++ b/.github/prompts/plan-for-next.prompt.md
@@ -0,0 +1,123 @@
+# Plan: Modernize SharpCompress Public API
+
+Based on comprehensive analysis, the API has several inconsistencies around factory patterns, async support, format capabilities, and options classes. Most improvements can be done incrementally without breaking changes.
+
+## Steps
+
+1. **Standardize factory patterns** by deprecating format-specific static `Open` methods in [Archives/Zip/ZipArchive.cs](src/SharpCompress/Archives/Zip/ZipArchive.cs), [Archives/Tar/TarArchive.cs](src/SharpCompress/Archives/Tar/TarArchive.cs), etc. in favor of centralized [Factories/ArchiveFactory.cs](src/SharpCompress/Factories/ArchiveFactory.cs)
+
+2. **Complete async implementation** in [Writers/Zip/ZipWriter.cs](src/SharpCompress/Writers/Zip/ZipWriter.cs) and other writers that currently use sync-over-async, implementing true async I/O throughout the writer hierarchy
+
+3. **Unify options classes** by making [Common/ExtractionOptions.cs](src/SharpCompress/Common/ExtractionOptions.cs) inherit from `OptionsBase` and adding progress reporting to extraction methods consistently
+
+4. **Clarify GZip semantics** in [Archives/GZip/GZipArchive.cs](src/SharpCompress/Archives/GZip/GZipArchive.cs) by adding XML documentation explaining single-entry limitation and relationship to GZip compression used in Tar.gz
+
+## Further Considerations
+
+1. **Breaking changes roadmap** - Should we plan a major version (2.0) to remove deprecated factory methods, clean up `ArchiveType` enum (remove Arc/Arj or add full support), and consolidate naming patterns?
+
+2. **Progress reporting consistency** - Should `IProgress>` be added to all extraction extension methods or consolidated into options classes?
+
+## Detailed Analysis
+
+### Factory Pattern Issues
+
+Three different factory patterns exist with overlapping functionality:
+
+1. **Static Factories**: ArchiveFactory, ReaderFactory, WriterFactory
+2. **Instance Factories**: IArchiveFactory, IReaderFactory, IWriterFactory
+3. **Format-specific static methods**: Each archive class has static `Open` methods
+
+**Example confusion:**
+```csharp
+// Three ways to open a Zip archive - which is recommended?
+var archive1 = ArchiveFactory.Open("file.zip");
+var archive2 = ZipArchive.Open("file.zip");
+var archive3 = ArchiveFactory.AutoFactory.Open(fileInfo, options);
+```
+
+### Async Support Gaps
+
+Base `IWriter` interface has async methods, but writer implementations provide minimal async support. Most writers just call synchronous methods:
+
+```csharp
+public virtual async Task WriteAsync(...)
+{
+ // Default implementation calls synchronous version
+ Write(filename, source, modificationTime);
+ await Task.CompletedTask.ConfigureAwait(false);
+}
+```
+
+Real async implementations only in:
+- `TarWriter` - Proper async implementation
+- Most other writers use sync-over-async
+
+### GZip Archive Special Case
+
+GZip is treated as both a compression format and an archive format, but only supports single-entry archives:
+
+```csharp
+protected override GZipArchiveEntry CreateEntryInternal(...)
+{
+ if (Entries.Any())
+ {
+ throw new InvalidFormatException("Only one entry is allowed in a GZip Archive");
+ }
+ // ...
+}
+```
+
+### Options Class Hierarchy
+
+```
+OptionsBase (LeaveStreamOpen, ArchiveEncoding)
+ ├─ ReaderOptions (LookForHeader, Password, DisableCheckIncomplete, BufferSize, ExtensionHint, Progress)
+ ├─ WriterOptions (CompressionType, CompressionLevel, Progress)
+ │ ├─ ZipWriterOptions (ArchiveComment, UseZip64)
+ │ ├─ TarWriterOptions (FinalizeArchiveOnClose, HeaderFormat)
+ │ └─ GZipWriterOptions (no additional properties)
+ └─ ExtractionOptions (standalone - Overwrite, ExtractFullPath, PreserveFileTime, PreserveAttributes)
+```
+
+**Issues:**
+- `ExtractionOptions` doesn't inherit from `OptionsBase` - no encoding support during extraction
+- Progress reporting inconsistency between readers and extraction
+- Obsolete properties (`ChecksumIsValid`, `Version`) with unclear migration path
+
+### Implementation Priorities
+
+**High Priority (Non-Breaking):**
+1. Add API usage guide (Archive vs Reader, factory recommendations, async best practices)
+2. Fix progress reporting consistency
+3. Complete async implementation in writers
+
+**Medium Priority (Next Major Version):**
+1. Unify factory pattern - deprecate format-specific static `Open` methods
+2. Clean up options classes - make `ExtractionOptions` inherit from `OptionsBase`
+3. Clarify archive types - remove Arc/Arj from `ArchiveType` enum or add full support
+4. Standardize naming across archive types
+
+**Low Priority:**
+1. Add BZip2 archive support similar to GZipArchive
+2. Complete obsolete property cleanup with migration guide
+
+### Backward Compatibility Strategy
+
+**Safe (Non-Breaking) Changes:**
+- Add new methods to interfaces (use default implementations)
+- Add new options properties (with defaults)
+- Add new factory methods
+- Improve async implementations
+- Add progress reporting support
+
+**Breaking Changes to Avoid:**
+- ❌ Removing format-specific `Open` methods (deprecate instead)
+- ❌ Changing `LeaveStreamOpen` default (currently `true`)
+- ❌ Removing obsolete properties before major version bump
+- ❌ Changing return types or signatures of existing methods
+
+**Deprecation Pattern:**
+- Use `[Obsolete]` for one major version
+- Use `[EditorBrowsable(EditorBrowsableState.Never)]` in next major version
+- Remove in following major version
diff --git a/.github/workflows/NUGET_RELEASE.md b/.github/workflows/NUGET_RELEASE.md
new file mode 100644
index 000000000..423750897
--- /dev/null
+++ b/.github/workflows/NUGET_RELEASE.md
@@ -0,0 +1,155 @@
+# NuGet Release Workflow
+
+This document describes the automated NuGet release workflow for SharpCompress.
+
+## Overview
+
+The `nuget-release.yml` workflow automatically builds, tests, and publishes SharpCompress packages to NuGet.org when:
+- Changes are pushed to the `master` or `release` branch
+- A version tag (format: `MAJOR.MINOR.PATCH`) is pushed
+
+The workflow runs on both Windows and Ubuntu, but only the Windows build publishes to NuGet.
+
+## How It Works
+
+### Version Determination
+
+The workflow automatically determines the version based on whether the commit is tagged using C# code in the build project:
+
+1. **Tagged Release (Stable)**:
+ - If the current commit has a version tag (e.g., `0.42.1`)
+ - Uses the tag as the version number
+ - Published as a stable release
+
+2. **Untagged Release (Prerelease)**:
+ - If the current commit is NOT tagged
+ - Creates a prerelease version based on the next minor version
+ - Format: `{NEXT_MINOR_VERSION}-beta.{COMMIT_COUNT}`
+ - Example: `0.43.0-beta.123` (if last tag is 0.42.x)
+ - Published as a prerelease to NuGet.org (Windows build only)
+
+### Workflow Steps
+
+The workflow runs on a matrix of operating systems (Windows and Ubuntu):
+
+1. **Checkout**: Fetches the repository with full history for version detection
+2. **Setup .NET**: Installs .NET 10.0
+3. **Determine Version**: Runs `determine-version` build target to check for tags and determine version
+4. **Update Version**: Runs `update-version` build target to update the version in the project file
+5. **Build and Test**: Runs the full build and test suite on both platforms
+6. **Upload Artifacts**: Uploads the generated `.nupkg` files as workflow artifacts (separate for each OS)
+7. **Push to NuGet**: (Windows only) Runs `push-to-nuget` build target to publish the package to NuGet.org using the API key
+
+All version detection, file updates, and publishing logic is implemented in C# in the `build/Program.cs` file using build targets.
+
+## Setup Requirements
+
+### 1. NuGet API Key Secret
+
+The workflow requires a `NUGET_API_KEY` secret to be configured in the repository settings:
+
+1. Go to https://www.nuget.org/account/apikeys
+2. Create a new API key with "Push" permission for the SharpCompress package
+3. In GitHub, go to: **Settings** → **Secrets and variables** → **Actions**
+4. Create a new secret named `NUGET_API_KEY` with the API key value
+
+### 2. Branch Protection (Recommended)
+
+Consider enabling branch protection rules for the `release` branch to ensure:
+- Code reviews are required before merging
+- Status checks pass before merging
+- Only authorized users can push to the branch
+
+## Usage
+
+### Creating a Stable Release
+
+There are two ways to trigger a stable release:
+
+**Method 1: Push tag to trigger workflow**
+1. Ensure all changes are committed on the `master` or `release` branch
+2. Create and push a version tag:
+ ```bash
+ git checkout master # or release
+ git tag 0.43.0
+ git push origin 0.43.0
+ ```
+3. The workflow will automatically trigger, build, test, and publish `SharpCompress 0.43.0` to NuGet.org (Windows build)
+
+**Method 2: Tag after pushing to branch**
+1. Ensure all changes are merged and pushed to the `master` or `release` branch
+2. Create and push a version tag on the already-pushed commit:
+ ```bash
+ git checkout master # or release
+ git tag 0.43.0
+ git push origin 0.43.0
+ ```
+3. The workflow will automatically trigger, build, test, and publish `SharpCompress 0.43.0` to NuGet.org (Windows build)
+
+### Creating a Prerelease
+
+1. Push changes to the `master` or `release` branch without tagging:
+ ```bash
+ git checkout master # or release
+ git push origin master # or release
+ ```
+2. The workflow will automatically:
+ - Build and test the project on both Windows and Ubuntu
+ - Publish a prerelease version like `0.43.0-beta.456` to NuGet.org (Windows build)
+
+## Troubleshooting
+
+### Workflow Fails to Push to NuGet
+
+- **Check the API Key**: Ensure `NUGET_API_KEY` is set correctly in repository secrets
+- **Check API Key Permissions**: Verify the API key has "Push" permission for SharpCompress
+- **Check API Key Expiration**: NuGet API keys may expire; create a new one if needed
+
+### Version Conflict
+
+If you see "Package already exists" errors:
+- The workflow uses `--skip-duplicate` flag to handle this gracefully
+- If you need to republish the same version, delete it from NuGet.org first (if allowed)
+
+### Build or Test Failures
+
+- The workflow will not push to NuGet if build or tests fail
+- Check the workflow logs in GitHub Actions for details
+- Fix the issues and push again
+
+## Manual Package Creation
+
+If you need to create a package manually without publishing:
+
+```bash
+dotnet run --project build/build.csproj -- publish
+```
+
+The package will be created in the `artifacts/` directory.
+
+## Build Targets
+
+The workflow uses the following C# build targets defined in `build/Program.cs`:
+
+- **determine-version**: Detects version from git tags and outputs VERSION and PRERELEASE variables
+- **update-version**: Updates VersionPrefix, AssemblyVersion, and FileVersion in the project file
+- **push-to-nuget**: Pushes the generated NuGet packages to NuGet.org (requires NUGET_API_KEY)
+
+These targets can be run manually for testing:
+
+```bash
+# Determine the version
+dotnet run --project build/build.csproj -- determine-version
+
+# Update version in project file
+VERSION=0.43.0 dotnet run --project build/build.csproj -- update-version
+
+# Push to NuGet (requires NUGET_API_KEY environment variable)
+NUGET_API_KEY=your-key dotnet run --project build/build.csproj -- push-to-nuget
+```
+
+## Related Files
+
+- `.github/workflows/nuget-release.yml` - The workflow definition
+- `build/Program.cs` - Build script with version detection and publishing logic
+- `src/SharpCompress/SharpCompress.csproj` - Project file with version information
diff --git a/.github/workflows/TESTING.md b/.github/workflows/TESTING.md
new file mode 100644
index 000000000..6afaa8aae
--- /dev/null
+++ b/.github/workflows/TESTING.md
@@ -0,0 +1,120 @@
+# Testing Guide for NuGet Release Workflow
+
+This document describes how to test the NuGet release workflow.
+
+## Testing Strategy
+
+Since this workflow publishes to NuGet.org and requires repository secrets, testing should be done carefully. The workflow runs on both Windows and Ubuntu, but only the Windows build publishes to NuGet.
+
+## Pre-Testing Checklist
+
+- [x] Workflow YAML syntax validated
+- [x] Version determination logic tested locally
+- [x] Version update logic tested locally
+- [x] Build script works (`dotnet run --project build/build.csproj`)
+
+## Manual Testing Steps
+
+### 1. Test Prerelease Publishing (Recommended First Test)
+
+This tests the workflow on untagged commits to the master or release branch.
+
+**Steps:**
+1. Ensure `NUGET_API_KEY` secret is configured in repository settings
+2. Create a test commit on the `master` or `release` branch (e.g., update a comment or README)
+3. Push to the `master` or `release` branch
+4. Monitor the GitHub Actions workflow at: https://github.com/adamhathcock/sharpcompress/actions
+5. Verify:
+ - Workflow triggers and runs successfully on both Windows and Ubuntu
+ - Version is determined correctly (e.g., `0.43.0-beta.XXX` if last tag is 0.42.x)
+ - Build and tests pass on both platforms
+ - Package artifacts are uploaded for both platforms
+ - Package is pushed to NuGet.org as prerelease (Windows build only)
+
+**Expected Outcome:**
+- A new prerelease package appears on NuGet.org: https://www.nuget.org/packages/SharpCompress/
+- Package version follows pattern: `{NEXT_MINOR_VERSION}-beta.{COMMIT_COUNT}`
+
+### 2. Test Tagged Release Publishing
+
+This tests the workflow when a version tag is pushed.
+
+**Steps:**
+1. Prepare the `master` or `release` branch with all desired changes
+2. Create a version tag (must be a pure semantic version like `MAJOR.MINOR.PATCH`):
+ ```bash
+ git checkout master # or release
+ git tag 0.42.2
+ git push origin 0.42.2
+ ```
+3. Monitor the GitHub Actions workflow
+4. Verify:
+ - Workflow triggers and runs successfully on both Windows and Ubuntu
+ - Version is determined as the tag (e.g., `0.42.2`)
+ - Build and tests pass on both platforms
+ - Package artifacts are uploaded for both platforms
+ - Package is pushed to NuGet.org as stable release (Windows build only)
+
+**Expected Outcome:**
+- A new stable release package appears on NuGet.org
+- Package version matches the tag
+
+### 3. Test Duplicate Package Handling
+
+This tests the `--skip-duplicate` flag behavior.
+
+**Steps:**
+1. Push to the `release` branch without making changes
+2. Monitor the workflow
+3. Verify:
+ - Workflow runs but NuGet push is skipped with "duplicate" message
+ - No errors occur
+
+### 4. Test Build Failure Handling
+
+This tests that failed builds don't publish packages.
+
+**Steps:**
+1. Introduce a breaking change in a test or code
+2. Push to the `release` branch
+3. Verify:
+ - Workflow runs and detects the failure
+ - Build or test step fails
+ - NuGet push step is skipped
+ - No package is published
+
+## Verification
+
+After each test, verify:
+
+1. **GitHub Actions Logs**: Check the workflow logs for any errors or warnings
+2. **NuGet.org**: Verify the package appears with correct version and metadata
+3. **Artifacts**: Download and inspect the uploaded artifacts
+
+## Rollback/Cleanup
+
+If testing produces unwanted packages:
+
+1. **Prerelease packages**: Can be unlisted on NuGet.org (Settings → Unlist)
+2. **Stable packages**: Cannot be deleted, only unlisted (use test versions)
+3. **Tags**: Can be deleted with:
+ ```bash
+ git tag -d 0.42.2
+ git push origin :refs/tags/0.42.2
+ ```
+
+## Known Limitations
+
+- NuGet.org does not allow re-uploading the same version
+- Deleted packages on NuGet.org reserve the version number
+- The workflow requires the `NUGET_API_KEY` secret to be set
+
+## Success Criteria
+
+The workflow is considered successful if:
+
+- ✅ Prerelease versions are published correctly with beta suffix
+- ✅ Tagged versions are published as stable releases
+- ✅ Build and test failures prevent publishing
+- ✅ Duplicate packages are handled gracefully
+- ✅ Workflow logs are clear and informative
diff --git a/.github/workflows/dotnetcore.yml b/.github/workflows/dotnetcore.yml
deleted file mode 100644
index fa268a672..000000000
--- a/.github/workflows/dotnetcore.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-name: SharpCompress
-on:
- push:
- branches:
- - 'master'
- pull_request:
- types: [ opened, synchronize, reopened, ready_for_review ]
-
-jobs:
- build:
- runs-on: ${{ matrix.os }}
- strategy:
- matrix:
- os: [windows-latest, ubuntu-latest]
-
- steps:
- - uses: actions/checkout@v6
- - uses: actions/setup-dotnet@v5
- with:
- dotnet-version: 8.0.x
- - run: dotnet run --project build/build.csproj
- - uses: actions/upload-artifact@v5
- with:
- name: ${{ matrix.os }}-sharpcompress.nupkg
- path: artifacts/*
diff --git a/.github/workflows/nuget-release.yml b/.github/workflows/nuget-release.yml
new file mode 100644
index 000000000..253a93edb
--- /dev/null
+++ b/.github/workflows/nuget-release.yml
@@ -0,0 +1,61 @@
+name: NuGet Release
+
+on:
+ push:
+ branches:
+ - 'master'
+ - 'release'
+ tags:
+ - '[0-9]+.[0-9]+.[0-9]+'
+ pull_request:
+ branches:
+ - 'master'
+ - 'release'
+
+permissions:
+ contents: read
+
+jobs:
+ build-and-publish:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [windows-latest, ubuntu-latest]
+
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ fetch-depth: 0 # Fetch all history for versioning
+
+ - uses: actions/setup-dotnet@v5
+ with:
+ dotnet-version: 10.0.x
+
+ # Determine version using C# build target
+ - name: Determine Version
+ id: version
+ run: dotnet run --project build/build.csproj -- determine-version
+
+ # Update version in project file using C# build target
+ - name: Update Version in Project
+ run: dotnet run --project build/build.csproj -- update-version
+ env:
+ VERSION: ${{ steps.version.outputs.version }}
+
+ # Build and test
+ - name: Build and Test
+ run: dotnet run --project build/build.csproj
+
+ # Upload artifacts for verification
+ - name: Upload NuGet Package
+ uses: actions/upload-artifact@v6
+ with:
+ name: ${{ matrix.os }}-nuget-package
+ path: artifacts/*.nupkg
+
+ # Push to NuGet.org using C# build target (Windows only, not on PRs)
+ - name: Push to NuGet
+ if: success() && matrix.os == 'windows-latest' && github.event_name != 'pull_request'
+ run: dotnet run --project build/build.csproj -- push-to-nuget
+ env:
+ NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
diff --git a/.gitignore b/.gitignore
index f101b3b15..6c6a863dc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,8 +15,8 @@ tests/TestArchives/*/Scratch
tests/TestArchives/*/Scratch2
.vs
tools
-.vscode
.idea/
+artifacts/
.DS_Store
*.snupkg
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
new file mode 100644
index 000000000..0c9d8a371
--- /dev/null
+++ b/.vscode/extensions.json
@@ -0,0 +1,9 @@
+{
+ "recommendations": [
+ "ms-dotnettools.csdevkit",
+ "ms-dotnettools.csharp",
+ "ms-dotnettools.vscode-dotnet-runtime",
+ "csharpier.csharpier-vscode",
+ "formulahendry.dotnet-test-explorer"
+ ]
+}
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 000000000..8171a42b1
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,97 @@
+{
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "Debug Tests (net10.0)",
+ "type": "coreclr",
+ "request": "launch",
+ "preLaunchTask": "build",
+ "program": "dotnet",
+ "args": [
+ "test",
+ "${workspaceFolder}/tests/SharpCompress.Test/SharpCompress.Test.csproj",
+ "-f",
+ "net10.0",
+ "--no-build",
+ "--verbosity=normal"
+ ],
+ "cwd": "${workspaceFolder}",
+ "console": "internalConsole",
+ "stopAtEntry": false
+ },
+ {
+ "name": "Debug Specific Test (net10.0)",
+ "type": "coreclr",
+ "request": "launch",
+ "preLaunchTask": "build",
+ "program": "dotnet",
+ "args": [
+ "test",
+ "${workspaceFolder}/tests/SharpCompress.Test/SharpCompress.Test.csproj",
+ "-f",
+ "net10.0",
+ "--no-build",
+ "--filter",
+ "FullyQualifiedName~${input:testName}"
+ ],
+ "cwd": "${workspaceFolder}",
+ "console": "internalConsole",
+ "stopAtEntry": false
+ },
+ {
+ "name": "Debug Performance Tests",
+ "type": "coreclr",
+ "request": "launch",
+ "preLaunchTask": "build",
+ "program": "dotnet",
+ "args": [
+ "run",
+ "--project",
+ "${workspaceFolder}/tests/SharpCompress.Performance/SharpCompress.Performance.csproj",
+ "--no-build"
+ ],
+ "cwd": "${workspaceFolder}",
+ "console": "internalConsole",
+ "stopAtEntry": false
+ },
+ {
+ "name": "Debug Build Script",
+ "type": "coreclr",
+ "request": "launch",
+ "program": "dotnet",
+ "args": [
+ "run",
+ "--project",
+ "${workspaceFolder}/build/build.csproj",
+ "--",
+ "${input:buildTarget}"
+ ],
+ "cwd": "${workspaceFolder}",
+ "console": "internalConsole",
+ "stopAtEntry": false
+ }
+ ],
+ "inputs": [
+ {
+ "id": "testName",
+ "type": "promptString",
+ "description": "Enter test name or pattern (e.g., TestMethodName or ClassName)",
+ "default": ""
+ },
+ {
+ "id": "buildTarget",
+ "type": "pickString",
+ "description": "Select build target",
+ "options": [
+ "clean",
+ "restore",
+ "build",
+ "test",
+ "format",
+ "publish",
+ "default"
+ ],
+ "default": "build"
+ }
+ ]
+}
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 000000000..079985397
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,29 @@
+{
+ "dotnet.defaultSolution": "SharpCompress.sln",
+ "files.exclude": {
+ "**/bin": true,
+ "**/obj": true
+ },
+ "files.watcherExclude": {
+ "**/bin/**": true,
+ "**/obj/**": true,
+ "**/artifacts/**": true
+ },
+ "search.exclude": {
+ "**/bin": true,
+ "**/obj": true,
+ "**/artifacts": true
+ },
+ "editor.formatOnSave": false,
+ "[csharp]": {
+ "editor.defaultFormatter": "csharpier.csharpier-vscode",
+ "editor.formatOnSave": true,
+ "editor.codeActionsOnSave": {
+ "source.fixAll": "explicit"
+ }
+ },
+ "csharpier.enableDebugLogs": false,
+ "omnisharp.enableRoslynAnalyzers": true,
+ "omnisharp.enableEditorConfigSupport": true,
+ "dotnet-test-explorer.testProjectPath": "tests/**/*.csproj"
+}
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 000000000..9f59e69dc
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,178 @@
+{
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "label": "build",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "build",
+ "${workspaceFolder}/SharpCompress.sln",
+ "/property:GenerateFullPaths=true",
+ "/consoleloggerparameters:NoSummary;ForceNoAlign"
+ ],
+ "problemMatcher": "$msCompile",
+ "group": {
+ "kind": "build",
+ "isDefault": true
+ }
+ },
+ {
+ "label": "build-release",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "build",
+ "${workspaceFolder}/SharpCompress.sln",
+ "-c",
+ "Release",
+ "/property:GenerateFullPaths=true",
+ "/consoleloggerparameters:NoSummary;ForceNoAlign"
+ ],
+ "problemMatcher": "$msCompile",
+ "group": "build"
+ },
+ {
+ "label": "build-library",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "build",
+ "${workspaceFolder}/src/SharpCompress/SharpCompress.csproj",
+ "/property:GenerateFullPaths=true",
+ "/consoleloggerparameters:NoSummary;ForceNoAlign"
+ ],
+ "problemMatcher": "$msCompile",
+ "group": "build"
+ },
+ {
+ "label": "restore",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "restore",
+ "${workspaceFolder}/SharpCompress.sln"
+ ],
+ "problemMatcher": "$msCompile"
+ },
+ {
+ "label": "clean",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "clean",
+ "${workspaceFolder}/SharpCompress.sln"
+ ],
+ "problemMatcher": "$msCompile"
+ },
+ {
+ "label": "test",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "test",
+ "${workspaceFolder}/tests/SharpCompress.Test/SharpCompress.Test.csproj",
+ "--no-build",
+ "--verbosity=normal"
+ ],
+ "problemMatcher": "$msCompile",
+ "group": {
+ "kind": "test",
+ "isDefault": true
+ },
+ "dependsOn": "build"
+ },
+ {
+ "label": "test-net10",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "test",
+ "${workspaceFolder}/tests/SharpCompress.Test/SharpCompress.Test.csproj",
+ "-f",
+ "net10.0",
+ "--no-build",
+ "--verbosity=normal"
+ ],
+ "problemMatcher": "$msCompile",
+ "group": "test",
+ "dependsOn": "build"
+ },
+ {
+ "label": "test-net48",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "test",
+ "${workspaceFolder}/tests/SharpCompress.Test/SharpCompress.Test.csproj",
+ "-f",
+ "net48",
+ "--no-build",
+ "--verbosity=normal"
+ ],
+ "problemMatcher": "$msCompile",
+ "group": "test",
+ "dependsOn": "build"
+ },
+ {
+ "label": "format",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "csharpier",
+ "."
+ ],
+ "problemMatcher": []
+ },
+ {
+ "label": "format-check",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "csharpier",
+ "check",
+ "."
+ ],
+ "problemMatcher": []
+ },
+ {
+ "label": "run-build-script",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "run",
+ "--project",
+ "${workspaceFolder}/build/build.csproj"
+ ],
+ "problemMatcher": "$msCompile"
+ },
+ {
+ "label": "pack",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "pack",
+ "${workspaceFolder}/src/SharpCompress/SharpCompress.csproj",
+ "-c",
+ "Release",
+ "-o",
+ "${workspaceFolder}/artifacts/"
+ ],
+ "problemMatcher": "$msCompile",
+ "dependsOn": "build-release"
+ },
+ {
+ "label": "performance-tests",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "run",
+ "--project",
+ "${workspaceFolder}/tests/SharpCompress.Performance/SharpCompress.Performance.csproj",
+ "-c",
+ "Release"
+ ],
+ "problemMatcher": "$msCompile"
+ }
+ ]
+}
diff --git a/AGENTS.md b/AGENTS.md
index 8275b651f..ae36265aa 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -28,14 +28,38 @@ SharpCompress is a pure C# compression library supporting multiple archive forma
## Code Formatting
+**Copilot agents: You MUST run the `format` task after making code changes to ensure consistency.**
+
- Use CSharpier for code formatting to ensure consistent style across the project
- CSharpier is configured as a local tool in `.config/dotnet-tools.json`
-- Restore tools with: `dotnet tool restore`
-- Format files from the project root with: `dotnet csharpier .`
-- **Run `dotnet csharpier .` from the project root after making code changes before committing**
-- Configure your IDE to format on save using CSharpier for the best experience
+
+### Commands
+
+1. **Restore tools** (first time only):
+ ```bash
+ dotnet tool restore
+ ```
+
+2. **Check if files are formatted correctly** (doesn't modify files):
+ ```bash
+ dotnet csharpier check .
+ ```
+ - Exit code 0: All files are properly formatted
+ - Exit code 1: Some files need formatting (will show which files and differences)
+
+3. **Format files** (modifies files):
+ ```bash
+ dotnet csharpier format .
+ ```
+ - Formats all files in the project to match CSharpier style
+ - Run from project root directory
+
+4. **Configure your IDE** to format on save using CSharpier for the best experience
+
+### Additional Notes
- The project also uses `.editorconfig` for editor settings (indentation, encoding, etc.)
- Let CSharpier handle code style while `.editorconfig` handles editor behavior
+- Always run `dotnet csharpier check .` before committing to verify formatting
## Project Setup and Structure
@@ -49,6 +73,30 @@ SharpCompress is a pure C# compression library supporting multiple archive forma
- Use `dotnet test` to run tests
- Solution file: `SharpCompress.sln`
+### Directory Structure
+```
+src/SharpCompress/
+ ├── Archives/ # IArchive implementations (Zip, Tar, Rar, 7Zip, GZip)
+ ├── Readers/ # IReader implementations (forward-only)
+ ├── Writers/ # IWriter implementations (forward-only)
+ ├── Compressors/ # Low-level compression streams (BZip2, Deflate, LZMA, etc.)
+ ├── Factories/ # Format detection and factory pattern
+ ├── Common/ # Shared types (ArchiveType, Entry, Options)
+ ├── Crypto/ # Encryption implementations
+ └── IO/ # Stream utilities and wrappers
+
+tests/SharpCompress.Test/
+ ├── Zip/, Tar/, Rar/, SevenZip/, GZip/, BZip2/ # Format-specific tests
+ ├── TestBase.cs # Base test class with helper methods
+ └── TestArchives/ # Test data (not checked into main test project)
+```
+
+### Factory Pattern
+All format types implement factory interfaces (`IArchiveFactory`, `IReaderFactory`, `IWriterFactory`) for auto-detection:
+- `ReaderFactory.Open()` - Auto-detects format by probing stream
+- `WriterFactory.Open()` - Creates writer for specified `ArchiveType`
+- Factories located in: `src/SharpCompress/Factories/`
+
## Nullable Reference Types
- Declare variables non-nullable, and check for `null` at entry points.
@@ -116,3 +164,18 @@ SharpCompress supports multiple archive and compression formats:
- Use test archives from `tests/TestArchives` directory for consistency.
- Test stream disposal and `LeaveStreamOpen` behavior.
- Test edge cases: empty archives, large files, corrupted archives, encrypted archives.
+
+### Test Organization
+- Base class: `TestBase` - Provides `TEST_ARCHIVES_PATH`, `SCRATCH_FILES_PATH`, temp directory management
+- Framework: xUnit with AwesomeAssertions
+- Test archives: `tests/TestArchives/` - Use existing archives, don't create new ones unnecessarily
+- Match naming style of nearby test files
+
+## Common Pitfalls
+
+1. **Don't mix Archive and Reader APIs** - Archive needs seekable stream, Reader doesn't
+2. **Solid archives (Rar, 7Zip)** - Use `ExtractAllEntries()` for best performance, not individual entry extraction
+3. **Stream disposal** - Always set `LeaveStreamOpen` explicitly when needed (default is to close)
+4. **Tar + non-seekable stream** - Must provide file size or it will throw
+5. **Multi-framework differences** - Some features differ between .NET Framework and modern .NET (e.g., Mono.Posix)
+6. **Format detection** - Use `ReaderFactory.Open()` for auto-detection, test with actual archive files
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 216d1de4e..bdb5dfb2d 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -1,20 +1,19 @@
-
+
-
-
-
+
+
+
-
+
+
-
-
-
+
diff --git a/FORMATS.md b/FORMATS.md
index 32dcc2885..13cff98ab 100644
--- a/FORMATS.md
+++ b/FORMATS.md
@@ -10,7 +10,10 @@
| Archive Format | Compression Format(s) | Compress/Decompress | Archive API | Reader API | Writer API |
| ---------------------- | ------------------------------------------------- | ------------------- | --------------- | ---------- | ------------- |
-| Rar | Rar | Decompress (1) | RarArchive | RarReader | N/A |
+| Ace | None | Decompress | N/A | AceReader | N/A |
+| Arc | None, Packed, Squeezed, Crunched | Decompress | N/A | ArcReader | N/A |
+| Arj | None | Decompress | N/A | ArjReader | N/A |
+| Rar | Rar | Decompress | RarArchive | RarReader | N/A |
| Zip (2) | None, Shrink, Reduce, Implode, DEFLATE, Deflate64, BZip2, LZMA/LZMA2, PPMd | Both | ZipArchive | ZipReader | ZipWriter |
| Tar | None | Both | TarArchive | TarReader | TarWriter (3) |
| Tar.GZip | DEFLATE | Both | TarArchive | TarReader | TarWriter (3) |
@@ -22,11 +25,28 @@
| 7Zip (4) | LZMA, LZMA2, BZip2, PPMd, BCJ, BCJ2, Deflate | Decompress | SevenZipArchive | N/A | N/A |
1. SOLID Rars are only supported in the RarReader API.
-2. Zip format supports pkware and WinzipAES encryption. However, encrypted LZMA is not supported. Zip64 reading/writing is supported but only with seekable streams as the Zip spec doesn't support Zip64 data in post data descriptors. Deflate64 is only supported for reading. SOZip (Seek-Optimized ZIP) detection is supported for reading.
+2. Zip format supports pkware and WinzipAES encryption. However, encrypted LZMA is not supported. Zip64 reading/writing is supported but only with seekable streams as the Zip spec doesn't support Zip64 data in post data descriptors. Deflate64 is only supported for reading. SOZip (Seek-Optimized ZIP) detection is supported for reading. See [Zip Format Notes](#zip-format-notes) for details on multi-volume archives and streaming behavior.
3. The Tar format requires a file size in the header. If no size is specified to the TarWriter and the stream is not seekable, then an exception will be thrown.
-4. The 7Zip format doesn't allow for reading as a forward-only stream so 7Zip is only supported through the Archive API
+4. The 7Zip format doesn't allow for reading as a forward-only stream so 7Zip is only supported through the Archive API. See [7Zip Format Notes](#7zip-format-notes) for details on async extraction behavior.
5. LZip has no support for extra data like the file name or timestamp. There is a default filename used when looking at the entry Key on the archive.
+### Zip Format Notes
+
+- Multi-volume/split ZIP archives require ZipArchive (seekable streams) as ZipReader cannot seek across volume files.
+- ZipReader processes entries from LocalEntry headers (which include directory entries ending with `/`) and intentionally skips DirectoryEntry headers from the central directory, as they are redundant in streaming mode - all entry data comes from LocalEntry headers which ZipReader has already processed.
+
+### 7Zip Format Notes
+
+- **Async Extraction Performance**: When using async extraction methods (e.g., `ExtractAllEntries()` with `MoveToNextEntryAsync()`), each file creates its own decompression stream to avoid state corruption in the LZMA decoder. This is less efficient than synchronous extraction, which can reuse a single decompression stream for multiple files in the same folder.
+
+ **Performance Impact**: For archives with many small files in the same compression folder, async extraction will be slower than synchronous extraction because it must:
+ 1. Create a new LZMA decoder for each file
+ 2. Skip through the decompressed data to reach each file's starting position
+
+ **Recommendation**: For best performance with 7Zip archives, use synchronous extraction methods (`MoveToNextEntry()` and `WriteEntryToDirectory()`) when possible. Use async methods only when you need to avoid blocking the thread (e.g., in UI applications or async-only contexts).
+
+ **Technical Details**: 7Zip archives group files into "folders" (compression units), where all files in a folder share one continuous LZMA-compressed stream. The LZMA decoder maintains internal state (dictionary window, decoder positions) that assumes sequential, non-interruptible processing. Async operations can yield control during awaits, which would corrupt this shared state. To avoid this, async extraction creates a fresh decoder stream for each file.
+
## Compression Streams
For those who want to directly compress/decompress bits. The single file formats are represented here as well. However, BZip2, LZip and XZ have no metadata (GZip has a little) so using them without something like a Tar file makes little sense.
diff --git a/README.md b/README.md
index f333d4972..172003c17 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# SharpCompress
-SharpCompress is a compression library in pure C# for .NET Framework 4.62, .NET Standard 2.1, .NET 6.0 and NET 8.0 that can unrar, un7zip, unzip, untar unbzip2, ungzip, unlzip, unzstd, unarc and unarj with forward-only reading and file random access APIs. Write support for zip/tar/bzip2/gzip/lzip are implemented.
+SharpCompress is a compression library in pure C# for .NET Framework 4.8, .NET 8.0 and .NET 10.0 that can unrar, un7zip, unzip, untar unbzip2, ungzip, unlzip, unzstd, unarc and unarj with forward-only reading and file random access APIs. Write support for zip/tar/bzip2/gzip/lzip are implemented.
The major feature is support for non-seekable streams so large files can be processed on the fly (i.e. download stream).
diff --git a/SharpCompress.sln b/SharpCompress.sln
index fc9b64b8c..ba04063bf 100644
--- a/SharpCompress.sln
+++ b/SharpCompress.sln
@@ -20,7 +20,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Config", "Config", "{CDB425
.editorconfig = .editorconfig
Directory.Packages.props = Directory.Packages.props
NuGet.config = NuGet.config
- .github\workflows\dotnetcore.yml = .github\workflows\dotnetcore.yml
+ .github\workflows\nuget-release.yml = .github\workflows\nuget-release.yml
USAGE.md = USAGE.md
README.md = README.md
FORMATS.md = FORMATS.md
diff --git a/USAGE.md b/USAGE.md
index a06d2e834..1e3a6c78f 100644
--- a/USAGE.md
+++ b/USAGE.md
@@ -87,20 +87,17 @@ memoryStream.Position = 0;
### Extract all files from a rar file to a directory using RarArchive
Note: Extracting a solid rar or 7z file needs to be done in sequential order to get acceptable decompression speed.
-It is explicitly recommended to use `ExtractAllEntries` when extracting an entire `IArchive` instead of iterating over all its `Entries`.
-Alternatively, use `IArchive.WriteToDirectory`.
+`ExtractAllEntries` is primarily intended for solid archives (like solid Rar) or 7Zip archives, where sequential extraction provides the best performance. For general/simple extraction with any supported archive type, use `archive.WriteToDirectory()` instead.
```C#
using (var archive = RarArchive.Open("Test.rar"))
{
- using (var reader = archive.ExtractAllEntries())
+ // Simple extraction with RarArchive; this WriteToDirectory pattern works for all archive types
+ archive.WriteToDirectory(@"D:\temp", new ExtractionOptions()
{
- reader.WriteAllToDirectory(@"D:\temp", new ExtractionOptions()
- {
- ExtractFullPath = true,
- Overwrite = true
- });
- }
+ ExtractFullPath = true,
+ Overwrite = true
+ });
}
```
@@ -116,6 +113,41 @@ using (var archive = RarArchive.Open("Test.rar"))
}
```
+### Extract solid Rar or 7Zip archives with manual progress reporting
+
+`ExtractAllEntries` only works for solid archives (Rar) or 7Zip archives. For optimal performance with these archive types, use this method:
+
+```C#
+using (var archive = RarArchive.Open("archive.rar")) // Must be solid Rar or 7Zip
+{
+ if (archive.IsSolid || archive.Type == ArchiveType.SevenZip)
+ {
+ // Calculate total size for progress reporting
+ double totalSize = archive.Entries.Where(e => !e.IsDirectory).Sum(e => e.Size);
+ long completed = 0;
+
+ using (var reader = archive.ExtractAllEntries())
+ {
+ while (reader.MoveToNextEntry())
+ {
+ if (!reader.Entry.IsDirectory)
+ {
+ reader.WriteEntryToDirectory(@"D:\output", new ExtractionOptions()
+ {
+ ExtractFullPath = true,
+ Overwrite = true
+ });
+
+ completed += reader.Entry.Size;
+ double progress = completed / totalSize;
+ Console.WriteLine($"Progress: {progress:P}");
+ }
+ }
+ }
+ }
+}
+```
+
### Use ReaderFactory to autodetect archive type and Open the entry stream
```C#
@@ -298,14 +330,12 @@ using (var writer = WriterFactory.Open(stream, ArchiveType.Zip, CompressionType.
```C#
using (var archive = ZipArchive.Open("archive.zip"))
{
- using (var reader = archive.ExtractAllEntries())
- {
- await reader.WriteAllToDirectoryAsync(
- @"C:\output",
- new ExtractionOptions() { ExtractFullPath = true, Overwrite = true },
- cancellationToken
- );
- }
+ // Simple async extraction - works for all archive types
+ await archive.WriteToDirectoryAsync(
+ @"C:\output",
+ new ExtractionOptions() { ExtractFullPath = true, Overwrite = true },
+ cancellationToken
+ );
}
```
diff --git a/build/Program.cs b/build/Program.cs
index b3bb2c47e..47a867459 100644
--- a/build/Program.cs
+++ b/build/Program.cs
@@ -1,7 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Runtime.InteropServices;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
using GlobExpressions;
using static Bullseye.Targets;
using static SimpleExec.Command;
@@ -11,7 +14,11 @@
const string Build = "build";
const string Test = "test";
const string Format = "format";
+const string CheckFormat = "check-format";
const string Publish = "publish";
+const string DetermineVersion = "determine-version";
+const string UpdateVersion = "update-version";
+const string PushToNuGet = "push-to-nuget";
Target(
Clean,
@@ -42,12 +49,20 @@ void RemoveDirectory(string d)
Target(
Format,
() =>
+ {
+ Run("dotnet", "tool restore");
+ Run("dotnet", "csharpier format .");
+ }
+);
+Target(
+ CheckFormat,
+ () =>
{
Run("dotnet", "tool restore");
Run("dotnet", "csharpier check .");
}
);
-Target(Restore, [Format], () => Run("dotnet", "restore"));
+Target(Restore, [CheckFormat], () => Run("dotnet", "restore"));
Target(
Build,
@@ -61,7 +76,7 @@ void RemoveDirectory(string d)
Target(
Test,
[Build],
- ["net8.0", "net48"],
+ ["net10.0", "net48"],
framework =>
{
IEnumerable GetFiles(string d)
@@ -90,6 +105,164 @@ IEnumerable GetFiles(string d)
}
);
+Target(
+ DetermineVersion,
+ async () =>
+ {
+ var (version, isPrerelease) = await GetVersion();
+ Console.WriteLine($"VERSION={version}");
+ Console.WriteLine($"PRERELEASE={isPrerelease.ToString().ToLower()}");
+
+ // Write to environment file for GitHub Actions
+ var githubOutput = Environment.GetEnvironmentVariable("GITHUB_OUTPUT");
+ if (!string.IsNullOrEmpty(githubOutput))
+ {
+ File.AppendAllText(githubOutput, $"version={version}\n");
+ File.AppendAllText(githubOutput, $"prerelease={isPrerelease.ToString().ToLower()}\n");
+ }
+ }
+);
+
+Target(
+ UpdateVersion,
+ async () =>
+ {
+ var version = Environment.GetEnvironmentVariable("VERSION");
+ if (string.IsNullOrEmpty(version))
+ {
+ var (detectedVersion, _) = await GetVersion();
+ version = detectedVersion;
+ }
+
+ Console.WriteLine($"Updating project file with version: {version}");
+
+ var projectPath = "src/SharpCompress/SharpCompress.csproj";
+ var content = File.ReadAllText(projectPath);
+
+ // Get base version (without prerelease suffix)
+ var baseVersion = version.Split('-')[0];
+
+ // Update VersionPrefix
+ content = Regex.Replace(
+ content,
+ @"[^<]*",
+ $"{version}"
+ );
+
+ // Update AssemblyVersion
+ content = Regex.Replace(
+ content,
+ @"[^<]*",
+ $"{baseVersion}"
+ );
+
+ // Update FileVersion
+ content = Regex.Replace(
+ content,
+ @"[^<]*",
+ $"{baseVersion}"
+ );
+
+ File.WriteAllText(projectPath, content);
+ Console.WriteLine($"Updated VersionPrefix to: {version}");
+ Console.WriteLine($"Updated AssemblyVersion and FileVersion to: {baseVersion}");
+ }
+);
+
+Target(
+ PushToNuGet,
+ () =>
+ {
+ var apiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY");
+ if (string.IsNullOrEmpty(apiKey))
+ {
+ Console.WriteLine(
+ "NUGET_API_KEY environment variable is not set. Skipping NuGet push."
+ );
+ return;
+ }
+
+ var packages = Directory.GetFiles("artifacts", "*.nupkg");
+ if (packages.Length == 0)
+ {
+ Console.WriteLine("No packages found in artifacts directory.");
+ return;
+ }
+
+ foreach (var package in packages)
+ {
+ Console.WriteLine($"Pushing {package} to NuGet.org");
+ try
+ {
+ // Note: API key is passed via command line argument which is standard practice for dotnet nuget push
+ // The key is already in an environment variable and not displayed in normal output
+ Run(
+ "dotnet",
+ $"nuget push \"{package}\" --api-key {apiKey} --source https://api.nuget.org/v3/index.json --skip-duplicate"
+ );
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to push {package}: {ex.Message}");
+ throw;
+ }
+ }
+ }
+);
+
Target("default", [Publish], () => Console.WriteLine("Done!"));
await RunTargetsAndExitAsync(args);
+
+static async Task<(string version, bool isPrerelease)> GetVersion()
+{
+ // Check if current commit has a version tag
+ var currentTag = (await GetGitOutput("tag", "--points-at HEAD"))
+ .Split('\n', StringSplitOptions.RemoveEmptyEntries)
+ .FirstOrDefault(tag => Regex.IsMatch(tag.Trim(), @"^\d+\.\d+\.\d+$"));
+
+ if (!string.IsNullOrEmpty(currentTag))
+ {
+ // Tagged release - use the tag as version
+ var version = currentTag.Trim();
+ Console.WriteLine($"Building tagged release version: {version}");
+ return (version, false);
+ }
+ else
+ {
+ // Not tagged - create prerelease version based on next minor version
+ var allTags = (await GetGitOutput("tag", "--list"))
+ .Split('\n', StringSplitOptions.RemoveEmptyEntries)
+ .Where(tag => Regex.IsMatch(tag.Trim(), @"^\d+\.\d+\.\d+$"))
+ .Select(tag => tag.Trim())
+ .ToList();
+
+ var lastTag = allTags.OrderBy(tag => Version.Parse(tag)).LastOrDefault() ?? "0.0.0";
+ var lastVersion = Version.Parse(lastTag);
+
+ // Increment minor version for next release
+ var nextVersion = new Version(lastVersion.Major, lastVersion.Minor + 1, 0);
+
+ // Use commit count since the last version tag if available; otherwise, fall back to total count
+ var revListArgs = allTags.Any() ? $"--count {lastTag}..HEAD" : "--count HEAD";
+ var commitCount = (await GetGitOutput("rev-list", revListArgs)).Trim();
+
+ var version = $"{nextVersion}-beta.{commitCount}";
+ Console.WriteLine($"Building prerelease version: {version}");
+ return (version, true);
+ }
+}
+
+static async Task GetGitOutput(string command, string args)
+{
+ try
+ {
+ // Use SimpleExec's Read to execute git commands in a cross-platform way
+ var (output, _) = await ReadAsync("git", $"{command} {args}");
+ return output;
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"Git command failed: git {command} {args}\n{ex.Message}", ex);
+ }
+}
diff --git a/build/build.csproj b/build/build.csproj
index 99e86377d..8f5b6f3c3 100644
--- a/build/build.csproj
+++ b/build/build.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net10.0
diff --git a/build/packages.lock.json b/build/packages.lock.json
index bc1f7953e..bfe9a5ca3 100644
--- a/build/packages.lock.json
+++ b/build/packages.lock.json
@@ -1,12 +1,12 @@
{
"version": 2,
"dependencies": {
- "net8.0": {
+ "net10.0": {
"Bullseye": {
"type": "Direct",
- "requested": "[6.0.0, )",
- "resolved": "6.0.0",
- "contentHash": "vgwwXfzs7jJrskWH7saHRMgPzziq/e86QZNWY1MnMxd7e+De7E7EX4K3C7yrvaK9y02SJoLxNxcLG/q5qUAghw=="
+ "requested": "[6.1.0, )",
+ "resolved": "6.1.0",
+ "contentHash": "fltnAJDe0BEX5eymXGUq+il2rSUA0pHqUonNDRH2TrvRu8SkU17mYG0IVpdmG2ibtfhdjNrv4CuTCxHOwcozCA=="
},
"Glob": {
"type": "Direct",
@@ -16,9 +16,9 @@
},
"SimpleExec": {
"type": "Direct",
- "requested": "[12.0.0, )",
- "resolved": "12.0.0",
- "contentHash": "ptxlWtxC8vM6Y6e3h9ZTxBBkOWnWrm/Sa1HT+2i1xcXY3Hx2hmKDZP5RShPf8Xr9D+ivlrXNy57ktzyH8kyt+Q=="
+ "requested": "[12.1.0, )",
+ "resolved": "12.1.0",
+ "contentHash": "PcCSAlMcKr5yTd571MgEMoGmoSr+omwziq2crB47lKP740lrmjuBocAUXHj+Q6LR6aUDFyhszot2wbtFJTClkA=="
}
}
}
diff --git a/global.json b/global.json
index 391ba3c2a..512142d2b 100644
--- a/global.json
+++ b/global.json
@@ -1,6 +1,6 @@
{
"sdk": {
- "version": "8.0.100",
+ "version": "10.0.100",
"rollForward": "latestFeature"
}
}
diff --git a/src/SharpCompress/Archives/AbstractArchive.cs b/src/SharpCompress/Archives/AbstractArchive.cs
index 712db4de1..672382ffc 100644
--- a/src/SharpCompress/Archives/AbstractArchive.cs
+++ b/src/SharpCompress/Archives/AbstractArchive.cs
@@ -8,7 +8,7 @@
namespace SharpCompress.Archives;
-public abstract class AbstractArchive : IArchive, IArchiveExtractionListener
+public abstract class AbstractArchive : IArchive
where TEntry : IArchiveEntry
where TVolume : IVolume
{
@@ -17,11 +17,6 @@ public abstract class AbstractArchive : IArchive, IArchiveExtra
private bool _disposed;
private readonly SourceStream? _sourceStream;
- public event EventHandler>? EntryExtractionBegin;
- public event EventHandler>? EntryExtractionEnd;
-
- public event EventHandler? CompressedBytesRead;
- public event EventHandler? FilePartExtractionBegin;
protected ReaderOptions ReaderOptions { get; }
internal AbstractArchive(ArchiveType type, SourceStream sourceStream)
@@ -43,12 +38,6 @@ internal AbstractArchive(ArchiveType type)
public ArchiveType Type { get; }
- void IArchiveExtractionListener.FireEntryExtractionBegin(IArchiveEntry entry) =>
- EntryExtractionBegin?.Invoke(this, new ArchiveExtractionEventArgs(entry));
-
- void IArchiveExtractionListener.FireEntryExtractionEnd(IArchiveEntry entry) =>
- EntryExtractionEnd?.Invoke(this, new ArchiveExtractionEventArgs(entry));
-
private static Stream CheckStreams(Stream stream)
{
if (!stream.CanSeek || !stream.CanRead)
@@ -99,38 +88,12 @@ public virtual void Dispose()
}
}
- void IArchiveExtractionListener.EnsureEntriesLoaded()
+ private void EnsureEntriesLoaded()
{
_lazyEntries.EnsureFullyLoaded();
_lazyVolumes.EnsureFullyLoaded();
}
- void IExtractionListener.FireCompressedBytesRead(
- long currentPartCompressedBytes,
- long compressedReadBytes
- ) =>
- CompressedBytesRead?.Invoke(
- this,
- new CompressedBytesReadEventArgs(
- currentFilePartCompressedBytesRead: currentPartCompressedBytes,
- compressedBytesRead: compressedReadBytes
- )
- );
-
- void IExtractionListener.FireFilePartExtractionBegin(
- string name,
- long size,
- long compressedSize
- ) =>
- FilePartExtractionBegin?.Invoke(
- this,
- new FilePartExtractionBeginEventArgs(
- compressedSize: compressedSize,
- size: size,
- name: name
- )
- );
-
///
/// Use this method to extract all entries in an archive in order.
/// This is primarily for SOLID Rar Archives or 7Zip Archives as they need to be
@@ -146,11 +109,11 @@ public IReader ExtractAllEntries()
{
if (!IsSolid && Type != ArchiveType.SevenZip)
{
- throw new InvalidOperationException(
+ throw new SharpCompressException(
"ExtractAllEntries can only be used on solid archives or 7Zip archives (which require random access)."
);
}
- ((IArchiveExtractionListener)this).EnsureEntriesLoaded();
+ EnsureEntriesLoaded();
return CreateReaderForSolidExtraction();
}
@@ -161,6 +124,11 @@ public IReader ExtractAllEntries()
///
public virtual bool IsSolid => false;
+ ///
+ /// Archive is ENCRYPTED (this means the Archive has password-protected files).
+ ///
+ public virtual bool IsEncrypted => false;
+
///
/// The archive can find all the parts of the archive needed to fully extract the archive. This forces the parsing of the entire archive.
///
@@ -168,7 +136,7 @@ public bool IsComplete
{
get
{
- ((IArchiveExtractionListener)this).EnsureEntriesLoaded();
+ EnsureEntriesLoaded();
return Entries.All(x => x.IsComplete);
}
}
diff --git a/src/SharpCompress/Archives/IArchive.cs b/src/SharpCompress/Archives/IArchive.cs
index 154529bfb..3ed7490d3 100644
--- a/src/SharpCompress/Archives/IArchive.cs
+++ b/src/SharpCompress/Archives/IArchive.cs
@@ -7,12 +7,6 @@ namespace SharpCompress.Archives;
public interface IArchive : IDisposable
{
- event EventHandler> EntryExtractionBegin;
- event EventHandler> EntryExtractionEnd;
-
- event EventHandler CompressedBytesRead;
- event EventHandler FilePartExtractionBegin;
-
IEnumerable Entries { get; }
IEnumerable Volumes { get; }
diff --git a/src/SharpCompress/Archives/IArchiveEntryExtensions.cs b/src/SharpCompress/Archives/IArchiveEntryExtensions.cs
index 6e76f7f90..af2c9be45 100644
--- a/src/SharpCompress/Archives/IArchiveEntryExtensions.cs
+++ b/src/SharpCompress/Archives/IArchiveEntryExtensions.cs
@@ -1,3 +1,4 @@
+using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -8,127 +9,153 @@ namespace SharpCompress.Archives;
public static class IArchiveEntryExtensions
{
- public static void WriteTo(this IArchiveEntry archiveEntry, Stream streamToWriteTo)
+ private const int BufferSize = 81920;
+
+ /// The archive entry to extract.
+ extension(IArchiveEntry archiveEntry)
{
- if (archiveEntry.IsDirectory)
+ ///
+ /// Extract entry to the specified stream.
+ ///
+ /// The stream to write the entry content to.
+ /// Optional progress reporter for tracking extraction progress.
+ public void WriteTo(Stream streamToWriteTo, IProgress? progress = null)
{
- throw new ExtractionException("Entry is a file directory and cannot be extracted.");
+ if (archiveEntry.IsDirectory)
+ {
+ throw new ExtractionException("Entry is a file directory and cannot be extracted.");
+ }
+
+ using var entryStream = archiveEntry.OpenEntryStream();
+ var sourceStream = WrapWithProgress(entryStream, archiveEntry, progress);
+ sourceStream.CopyTo(streamToWriteTo, BufferSize);
}
- var streamListener = (IArchiveExtractionListener)archiveEntry.Archive;
- streamListener.EnsureEntriesLoaded();
- streamListener.FireEntryExtractionBegin(archiveEntry);
- streamListener.FireFilePartExtractionBegin(
- archiveEntry.Key ?? "Key",
- archiveEntry.Size,
- archiveEntry.CompressedSize
- );
- var entryStream = archiveEntry.OpenEntryStream();
- using (entryStream)
+ ///
+ /// Extract entry to the specified stream asynchronously.
+ ///
+ /// The stream to write the entry content to.
+ /// Cancellation token.
+ /// Optional progress reporter for tracking extraction progress.
+ public async Task WriteToAsync(
+ Stream streamToWriteTo,
+ IProgress? progress = null,
+ CancellationToken cancellationToken = default
+ )
{
- using Stream s = new ListeningStream(streamListener, entryStream);
- s.CopyTo(streamToWriteTo);
+ if (archiveEntry.IsDirectory)
+ {
+ throw new ExtractionException("Entry is a file directory and cannot be extracted.");
+ }
+
+ using var entryStream = await archiveEntry.OpenEntryStreamAsync(cancellationToken);
+ var sourceStream = WrapWithProgress(entryStream, archiveEntry, progress);
+ await sourceStream
+ .CopyToAsync(streamToWriteTo, BufferSize, cancellationToken)
+ .ConfigureAwait(false);
}
- streamListener.FireEntryExtractionEnd(archiveEntry);
}
- public static async Task WriteToAsync(
- this IArchiveEntry archiveEntry,
- Stream streamToWriteTo,
- CancellationToken cancellationToken = default
+ private static Stream WrapWithProgress(
+ Stream source,
+ IArchiveEntry entry,
+ IProgress? progress
)
{
- if (archiveEntry.IsDirectory)
+ if (progress is null)
{
- throw new ExtractionException("Entry is a file directory and cannot be extracted.");
+ return source;
}
- var streamListener = (IArchiveExtractionListener)archiveEntry.Archive;
- streamListener.EnsureEntriesLoaded();
- streamListener.FireEntryExtractionBegin(archiveEntry);
- streamListener.FireFilePartExtractionBegin(
- archiveEntry.Key ?? "Key",
- archiveEntry.Size,
- archiveEntry.CompressedSize
+ var entryPath = entry.Key ?? string.Empty;
+ var totalBytes = GetEntrySizeSafe(entry);
+ return new ProgressReportingStream(
+ source,
+ progress,
+ entryPath,
+ totalBytes,
+ leaveOpen: true
);
- var entryStream = archiveEntry.OpenEntryStream();
- using (entryStream)
+ }
+
+ private static long? GetEntrySizeSafe(IArchiveEntry entry)
+ {
+ try
{
- using Stream s = new ListeningStream(streamListener, entryStream);
- await s.CopyToAsync(streamToWriteTo, 81920, cancellationToken).ConfigureAwait(false);
+ var size = entry.Size;
+ return size >= 0 ? size : null;
+ }
+ catch (NotImplementedException)
+ {
+ return null;
}
- streamListener.FireEntryExtractionEnd(archiveEntry);
}
- ///
- /// Extract to specific directory, retaining filename
- ///
- public static void WriteToDirectory(
- this IArchiveEntry entry,
- string destinationDirectory,
- ExtractionOptions? options = null
- ) =>
- ExtractionMethods.WriteEntryToDirectory(
- entry,
- destinationDirectory,
- options,
- entry.WriteToFile
- );
+ extension(IArchiveEntry entry)
+ {
+ ///
+ /// Extract to specific directory, retaining filename
+ ///
+ public void WriteToDirectory(
+ string destinationDirectory,
+ ExtractionOptions? options = null
+ ) =>
+ ExtractionMethods.WriteEntryToDirectory(
+ entry,
+ destinationDirectory,
+ options,
+ entry.WriteToFile
+ );
- ///
- /// Extract to specific directory asynchronously, retaining filename
- ///
- public static Task WriteToDirectoryAsync(
- this IArchiveEntry entry,
- string destinationDirectory,
- ExtractionOptions? options = null,
- CancellationToken cancellationToken = default
- ) =>
- ExtractionMethods.WriteEntryToDirectoryAsync(
- entry,
- destinationDirectory,
- options,
- (x, opt) => entry.WriteToFileAsync(x, opt, cancellationToken),
- cancellationToken
- );
+ ///
+ /// Extract to specific directory asynchronously, retaining filename
+ ///
+ public Task WriteToDirectoryAsync(
+ string destinationDirectory,
+ ExtractionOptions? options = null,
+ CancellationToken cancellationToken = default
+ ) =>
+ ExtractionMethods.WriteEntryToDirectoryAsync(
+ entry,
+ destinationDirectory,
+ options,
+ entry.WriteToFileAsync,
+ cancellationToken
+ );
- ///
- /// Extract to specific file
- ///
- public static void WriteToFile(
- this IArchiveEntry entry,
- string destinationFileName,
- ExtractionOptions? options = null
- ) =>
- ExtractionMethods.WriteEntryToFile(
- entry,
- destinationFileName,
- options,
- (x, fm) =>
- {
- using var fs = File.Open(destinationFileName, fm);
- entry.WriteTo(fs);
- }
- );
+ ///
+ /// Extract to specific file
+ ///
+ public void WriteToFile(string destinationFileName, ExtractionOptions? options = null) =>
+ ExtractionMethods.WriteEntryToFile(
+ entry,
+ destinationFileName,
+ options,
+ (x, fm) =>
+ {
+ using var fs = File.Open(destinationFileName, fm);
+ entry.WriteTo(fs);
+ }
+ );
- ///
- /// Extract to specific file asynchronously
- ///
- public static Task WriteToFileAsync(
- this IArchiveEntry entry,
- string destinationFileName,
- ExtractionOptions? options = null,
- CancellationToken cancellationToken = default
- ) =>
- ExtractionMethods.WriteEntryToFileAsync(
- entry,
- destinationFileName,
- options,
- async (x, fm) =>
- {
- using var fs = File.Open(destinationFileName, fm);
- await entry.WriteToAsync(fs, cancellationToken).ConfigureAwait(false);
- },
- cancellationToken
- );
+ ///
+ /// Extract to specific file asynchronously
+ ///
+ public Task WriteToFileAsync(
+ string destinationFileName,
+ ExtractionOptions? options = null,
+ CancellationToken cancellationToken = default
+ ) =>
+ ExtractionMethods.WriteEntryToFileAsync(
+ entry,
+ destinationFileName,
+ options,
+ async (x, fm, ct) =>
+ {
+ using var fs = File.Open(destinationFileName, fm);
+ await entry.WriteToAsync(fs, null, ct).ConfigureAwait(false);
+ },
+ cancellationToken
+ );
+ }
}
diff --git a/src/SharpCompress/Archives/IArchiveExtensions.cs b/src/SharpCompress/Archives/IArchiveExtensions.cs
index d9701da30..0d39c6e2c 100644
--- a/src/SharpCompress/Archives/IArchiveExtensions.cs
+++ b/src/SharpCompress/Archives/IArchiveExtensions.cs
@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
-using System.Linq;
using System.Threading;
+using System.Threading.Tasks;
using SharpCompress.Common;
using SharpCompress.Readers;
@@ -10,76 +10,159 @@ namespace SharpCompress.Archives;
public static class IArchiveExtensions
{
- ///
- /// Extract to specific directory, retaining filename
- ///
- public static void WriteToDirectory(
- this IArchive archive,
- string destinationDirectory,
- ExtractionOptions? options = null
- )
- {
- using var reader = archive.ExtractAllEntries();
- reader.WriteAllToDirectory(destinationDirectory, options);
- }
-
- ///
- /// Extracts the archive to the destination directory. Directories will be created as needed.
- ///
/// The archive to extract.
- /// The folder to extract into.
- /// Optional progress report callback.
- /// Optional cancellation token.
- public static void ExtractToDirectory(
- this IArchive archive,
- string destination,
- Action? progressReport = null,
- CancellationToken cancellationToken = default
- )
+ extension(IArchive archive)
{
- // Prepare for progress reporting
- var totalBytes = archive.TotalUncompressSize;
- var bytesRead = 0L;
-
- // Tracking for created directories.
- var seenDirectories = new HashSet();
+ ///
+ /// Extract to specific directory with progress reporting
+ ///
+ /// The folder to extract into.
+ /// Extraction options.
+ /// Optional progress reporter for tracking extraction progress.
+ public void WriteToDirectory(
+ string destinationDirectory,
+ ExtractionOptions? options = null,
+ IProgress? progress = null
+ )
+ {
+ // For solid archives (Rar, 7Zip), use the optimized reader-based approach
+ if (archive.IsSolid || archive.Type == ArchiveType.SevenZip)
+ {
+ using var reader = archive.ExtractAllEntries();
+ reader.WriteAllToDirectory(destinationDirectory, options);
+ }
+ else
+ {
+ // For non-solid archives, extract entries directly
+ archive.WriteToDirectoryInternal(destinationDirectory, options, progress);
+ }
+ }
- // Extract
- foreach (var entry in archive.Entries)
+ private void WriteToDirectoryInternal(
+ string destinationDirectory,
+ ExtractionOptions? options,
+ IProgress? progress
+ )
{
- cancellationToken.ThrowIfCancellationRequested();
+ // Prepare for progress reporting
+ var totalBytes = archive.TotalUncompressSize;
+ var bytesRead = 0L;
+
+ // Tracking for created directories.
+ var seenDirectories = new HashSet();
- if (entry.IsDirectory)
+ // Extract
+ foreach (var entry in archive.Entries)
{
- var dirPath = Path.Combine(destination, entry.Key.NotNull("Entry Key is null"));
- if (
- Path.GetDirectoryName(dirPath + "/") is { } emptyDirectory
- && seenDirectories.Add(dirPath)
- )
+ if (entry.IsDirectory)
{
- Directory.CreateDirectory(emptyDirectory);
+ var dirPath = Path.Combine(
+ destinationDirectory,
+ entry.Key.NotNull("Entry Key is null")
+ );
+ if (
+ Path.GetDirectoryName(dirPath + "/") is { } parentDirectory
+ && seenDirectories.Add(dirPath)
+ )
+ {
+ Directory.CreateDirectory(parentDirectory);
+ }
+ continue;
}
- continue;
+
+ // Use the entry's WriteToDirectory method which respects ExtractionOptions
+ entry.WriteToDirectory(destinationDirectory, options);
+
+ // Update progress
+ bytesRead += entry.Size;
+ progress?.Report(
+ new ProgressReport(entry.Key ?? string.Empty, bytesRead, totalBytes)
+ );
}
+ }
- // Create each directory if not already created
- var path = Path.Combine(destination, entry.Key.NotNull("Entry Key is null"));
- if (Path.GetDirectoryName(path) is { } directory)
+ ///
+ /// Extract to specific directory asynchronously with progress reporting and cancellation support
+ ///
+ /// The folder to extract into.
+ /// Extraction options.
+ /// Optional progress reporter for tracking extraction progress.
+ /// Optional cancellation token.
+ public async Task WriteToDirectoryAsync(
+ string destinationDirectory,
+ ExtractionOptions? options = null,
+ IProgress? progress = null,
+ CancellationToken cancellationToken = default
+ )
+ {
+ // For solid archives (Rar, 7Zip), use the optimized reader-based approach
+ if (archive.IsSolid || archive.Type == ArchiveType.SevenZip)
+ {
+ using var reader = archive.ExtractAllEntries();
+ await reader.WriteAllToDirectoryAsync(
+ destinationDirectory,
+ options,
+ cancellationToken
+ );
+ }
+ else
{
- if (!Directory.Exists(directory) && !seenDirectories.Contains(directory))
+ // For non-solid archives, extract entries directly
+ await archive.WriteToDirectoryAsyncInternal(
+ destinationDirectory,
+ options,
+ progress,
+ cancellationToken
+ );
+ }
+ }
+
+ private async Task WriteToDirectoryAsyncInternal(
+ string destinationDirectory,
+ ExtractionOptions? options,
+ IProgress? progress,
+ CancellationToken cancellationToken
+ )
+ {
+ // Prepare for progress reporting
+ var totalBytes = archive.TotalUncompressSize;
+ var bytesRead = 0L;
+
+ // Tracking for created directories.
+ var seenDirectories = new HashSet();
+
+ // Extract
+ foreach (var entry in archive.Entries)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (entry.IsDirectory)
{
- Directory.CreateDirectory(directory);
- seenDirectories.Add(directory);
+ var dirPath = Path.Combine(
+ destinationDirectory,
+ entry.Key.NotNull("Entry Key is null")
+ );
+ if (
+ Path.GetDirectoryName(dirPath + "/") is { } parentDirectory
+ && seenDirectories.Add(dirPath)
+ )
+ {
+ Directory.CreateDirectory(parentDirectory);
+ }
+ continue;
}
- }
- // Write file
- using var fs = File.OpenWrite(path);
- entry.WriteTo(fs);
+ // Use the entry's WriteToDirectoryAsync method which respects ExtractionOptions
+ await entry
+ .WriteToDirectoryAsync(destinationDirectory, options, cancellationToken)
+ .ConfigureAwait(false);
- // Update progress
- bytesRead += entry.Size;
- progressReport?.Invoke(bytesRead / (double)totalBytes);
+ // Update progress
+ bytesRead += entry.Size;
+ progress?.Report(
+ new ProgressReport(entry.Key ?? string.Empty, bytesRead, totalBytes)
+ );
+ }
}
}
}
diff --git a/src/SharpCompress/Archives/IArchiveExtractionListener.cs b/src/SharpCompress/Archives/IArchiveExtractionListener.cs
deleted file mode 100644
index 7bc2ef34e..000000000
--- a/src/SharpCompress/Archives/IArchiveExtractionListener.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using SharpCompress.Common;
-
-namespace SharpCompress.Archives;
-
-internal interface IArchiveExtractionListener : IExtractionListener
-{
- void EnsureEntriesLoaded();
- void FireEntryExtractionBegin(IArchiveEntry entry);
- void FireEntryExtractionEnd(IArchiveEntry entry);
-}
diff --git a/src/SharpCompress/Archives/Rar/RarArchive.cs b/src/SharpCompress/Archives/Rar/RarArchive.cs
index b3689a9f5..9acfdccc5 100644
--- a/src/SharpCompress/Archives/Rar/RarArchive.cs
+++ b/src/SharpCompress/Archives/Rar/RarArchive.cs
@@ -84,6 +84,8 @@ protected override IReader CreateReaderForSolidExtraction()
public override bool IsSolid => Volumes.First().IsSolidArchive;
+ public override bool IsEncrypted => Entries.First(x => !x.IsDirectory).IsEncrypted;
+
public virtual int MinVersion => Volumes.First().MinVersion;
public virtual int MaxVersion => Volumes.First().MaxVersion;
diff --git a/src/SharpCompress/Archives/Rar/RarArchiveEntry.cs b/src/SharpCompress/Archives/Rar/RarArchiveEntry.cs
index aaba6d1ec..69c54f310 100644
--- a/src/SharpCompress/Archives/Rar/RarArchiveEntry.cs
+++ b/src/SharpCompress/Archives/Rar/RarArchiveEntry.cs
@@ -76,7 +76,7 @@ public Stream OpenEntryStream()
stream = new RarStream(
archive.UnpackV1.Value,
FileHeader,
- new MultiVolumeReadOnlyStream(Parts.Cast(), archive)
+ new MultiVolumeReadOnlyStream(Parts.Cast())
);
}
else
@@ -84,7 +84,7 @@ public Stream OpenEntryStream()
stream = new RarStream(
archive.UnpackV2017.Value,
FileHeader,
- new MultiVolumeReadOnlyStream(Parts.Cast(), archive)
+ new MultiVolumeReadOnlyStream(Parts.Cast())
);
}
@@ -100,7 +100,7 @@ public async Task OpenEntryStreamAsync(CancellationToken cancellationTok
stream = new RarStream(
archive.UnpackV1.Value,
FileHeader,
- new MultiVolumeReadOnlyStream(Parts.Cast(), archive)
+ new MultiVolumeReadOnlyStream(Parts.Cast())
);
}
else
@@ -108,7 +108,7 @@ public async Task OpenEntryStreamAsync(CancellationToken cancellationTok
stream = new RarStream(
archive.UnpackV2017.Value,
FileHeader,
- new MultiVolumeReadOnlyStream(Parts.Cast(), archive)
+ new MultiVolumeReadOnlyStream(Parts.Cast())
);
}
diff --git a/src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs b/src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs
index ea763409d..d9b5ba1aa 100644
--- a/src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs
+++ b/src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs
@@ -2,6 +2,8 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
using SharpCompress.Common;
using SharpCompress.Common.SevenZip;
using SharpCompress.Compressors.LZMA.Utilites;
@@ -205,15 +207,15 @@ protected override IReader CreateReaderForSolidExtraction() =>
.GroupBy(x => x.FilePart.Folder)
.Any(folder => folder.Count() > 1);
+ public override bool IsEncrypted => Entries.First(x => !x.IsDirectory).IsEncrypted;
+
public override long TotalSize =>
_database?._packSizes.Aggregate(0L, (total, packSize) => total + packSize) ?? 0;
private sealed class SevenZipReader : AbstractReader
{
private readonly SevenZipArchive _archive;
- private CFolder? _currentFolder;
- private Stream? _currentStream;
- private CFileItem? _currentItem;
+ private SevenZipEntry? _currentEntry;
internal SevenZipReader(ReaderOptions readerOptions, SevenZipArchive archive)
: base(readerOptions, ArchiveType.SevenZip) => this._archive = archive;
@@ -226,40 +228,135 @@ protected override IEnumerable GetEntries(Stream stream)
stream.Position = 0;
foreach (var dir in entries.Where(x => x.IsDirectory))
{
+ _currentEntry = dir;
yield return dir;
}
- foreach (
- var group in entries.Where(x => !x.IsDirectory).GroupBy(x => x.FilePart.Folder)
- )
+ // For non-directory entries, yield them without creating shared streams
+ // Each call to GetEntryStream() will create a fresh decompression stream
+ // to avoid state corruption issues with async operations
+ foreach (var entry in entries.Where(x => !x.IsDirectory))
{
- _currentFolder = group.Key;
- if (group.Key is null)
- {
- _currentStream = Stream.Null;
- }
- else
- {
- _currentStream = _archive._database?.GetFolderStream(
- stream,
- _currentFolder,
- new PasswordProvider(Options.Password)
- );
- }
- foreach (var entry in group)
- {
- _currentItem = entry.FilePart.Header;
- yield return entry;
- }
+ _currentEntry = entry;
+ yield return entry;
}
}
- protected override EntryStream GetEntryStream() =>
- CreateEntryStream(
- new ReadOnlySubStream(
- _currentStream.NotNull("currentStream is not null"),
- _currentItem?.Size ?? 0
- )
- );
+ protected override EntryStream GetEntryStream()
+ {
+ // Create a fresh decompression stream for each file (no state sharing).
+ // However, the LZMA decoder has bugs in its async implementation that cause
+ // state corruption even on fresh streams. The SyncOnlyStream wrapper
+ // works around these bugs by forcing async operations to use sync equivalents.
+ //
+ // TODO: Fix the LZMA decoder async bugs (in LzmaStream, Decoder, OutWindow)
+ // so this wrapper is no longer necessary.
+ var entry = _currentEntry.NotNull("currentEntry is not null");
+ if (entry.IsDirectory)
+ {
+ return CreateEntryStream(Stream.Null);
+ }
+ return CreateEntryStream(new SyncOnlyStream(entry.FilePart.GetCompressedStream()));
+ }
+ }
+
+ ///
+ /// WORKAROUND: Forces async operations to use synchronous equivalents.
+ /// This is necessary because the LZMA decoder has bugs in its async implementation
+ /// that cause state corruption (IndexOutOfRangeException, DataErrorException).
+ ///
+ /// The proper fix would be to repair the LZMA decoder's async methods
+ /// (LzmaStream.ReadAsync, Decoder.CodeAsync, OutWindow async operations),
+ /// but that requires deep changes to the decoder state machine.
+ ///
+ private sealed class SyncOnlyStream : Stream
+ {
+ private readonly Stream _baseStream;
+
+ public SyncOnlyStream(Stream baseStream) => _baseStream = baseStream;
+
+ public override bool CanRead => _baseStream.CanRead;
+ public override bool CanSeek => _baseStream.CanSeek;
+ public override bool CanWrite => _baseStream.CanWrite;
+ public override long Length => _baseStream.Length;
+ public override long Position
+ {
+ get => _baseStream.Position;
+ set => _baseStream.Position = value;
+ }
+
+ public override void Flush() => _baseStream.Flush();
+
+ public override int Read(byte[] buffer, int offset, int count) =>
+ _baseStream.Read(buffer, offset, count);
+
+ public override long Seek(long offset, SeekOrigin origin) =>
+ _baseStream.Seek(offset, origin);
+
+ public override void SetLength(long value) => _baseStream.SetLength(value);
+
+ public override void Write(byte[] buffer, int offset, int count) =>
+ _baseStream.Write(buffer, offset, count);
+
+ // Force async operations to use sync equivalents to avoid LZMA decoder bugs
+ public override Task ReadAsync(
+ byte[] buffer,
+ int offset,
+ int count,
+ CancellationToken cancellationToken
+ )
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return Task.FromResult(_baseStream.Read(buffer, offset, count));
+ }
+
+ public override Task WriteAsync(
+ byte[] buffer,
+ int offset,
+ int count,
+ CancellationToken cancellationToken
+ )
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ _baseStream.Write(buffer, offset, count);
+ return Task.CompletedTask;
+ }
+
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ _baseStream.Flush();
+ return Task.CompletedTask;
+ }
+
+#if !NETFRAMEWORK && !NETSTANDARD2_0
+ public override ValueTask ReadAsync(
+ Memory buffer,
+ CancellationToken cancellationToken = default
+ )
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return new ValueTask(_baseStream.Read(buffer.Span));
+ }
+
+ public override ValueTask WriteAsync(
+ ReadOnlyMemory buffer,
+ CancellationToken cancellationToken = default
+ )
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ _baseStream.Write(buffer.Span);
+ return ValueTask.CompletedTask;
+ }
+#endif
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _baseStream.Dispose();
+ }
+ base.Dispose(disposing);
+ }
}
private class PasswordProvider : IPasswordProvider
diff --git a/src/SharpCompress/AssemblyInfo.cs b/src/SharpCompress/AssemblyInfo.cs
index e51d97fe0..c11eb8e02 100644
--- a/src/SharpCompress/AssemblyInfo.cs
+++ b/src/SharpCompress/AssemblyInfo.cs
@@ -1,7 +1,8 @@
using System;
using System.Runtime.CompilerServices;
-[assembly: CLSCompliant(true)]
+// CLSCompliant(false) is required because ZStandard integration uses unsafe code
+[assembly: CLSCompliant(false)]
[assembly: InternalsVisibleTo(
"SharpCompress.Test,PublicKey=0024000004800000940000000602000000240000525341310004000001000100158bebf1433f76dffc356733c138babea7a47536c65ed8009b16372c6f4edbb20554db74a62687f56b97c20a6ce8c4b123280279e33c894e7b3aa93ab3c573656fde4db576cfe07dba09619ead26375b25d2c4a8e43f7be257d712b0dd2eb546f67adb09281338618a58ac834fc038dd7e2740a7ab3591826252e4f4516306dc"
)]
diff --git a/src/SharpCompress/Common/Ace/AceCrc.cs b/src/SharpCompress/Common/Ace/AceCrc.cs
new file mode 100644
index 000000000..8ae43a2b0
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/AceCrc.cs
@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SharpCompress.Common.Ace
+{
+ public class AceCrc
+ {
+ // CRC-32 lookup table (standard polynomial 0xEDB88320, reflected)
+ private static readonly uint[] Crc32Table = GenerateTable();
+
+ private static uint[] GenerateTable()
+ {
+ var table = new uint[256];
+
+ for (int i = 0; i < 256; i++)
+ {
+ uint crc = (uint)i;
+
+ for (int j = 0; j < 8; j++)
+ {
+ if ((crc & 1) != 0)
+ crc = (crc >> 1) ^ 0xEDB88320u;
+ else
+ crc >>= 1;
+ }
+
+ table[i] = crc;
+ }
+
+ return table;
+ }
+
+ ///
+ /// Calculate ACE CRC-32 checksum.
+ /// ACE CRC-32 uses standard CRC-32 polynomial (0xEDB88320, reflected)
+ /// with init=0xFFFFFFFF but NO final XOR.
+ ///
+ public static uint AceCrc32(ReadOnlySpan data)
+ {
+ uint crc = 0xFFFFFFFFu;
+
+ foreach (byte b in data)
+ {
+ crc = (crc >> 8) ^ Crc32Table[(crc ^ b) & 0xFF];
+ }
+
+ return crc; // No final XOR for ACE
+ }
+
+ ///
+ /// ACE CRC-16 is the lower 16 bits of the ACE CRC-32.
+ ///
+ public static ushort AceCrc16(ReadOnlySpan data)
+ {
+ return (ushort)(AceCrc32(data) & 0xFFFF);
+ }
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/AceEntry.cs b/src/SharpCompress/Common/Ace/AceEntry.cs
new file mode 100644
index 000000000..a3dde1e7f
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/AceEntry.cs
@@ -0,0 +1,68 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using SharpCompress.Common.Ace.Headers;
+
+namespace SharpCompress.Common.Ace
+{
+ public class AceEntry : Entry
+ {
+ private readonly AceFilePart _filePart;
+
+ internal AceEntry(AceFilePart filePart)
+ {
+ _filePart = filePart;
+ }
+
+ public override long Crc
+ {
+ get
+ {
+ if (_filePart == null)
+ {
+ return 0;
+ }
+ return _filePart.Header.Crc32;
+ }
+ }
+
+ public override string? Key => _filePart?.Header.Filename;
+
+ public override string? LinkTarget => null;
+
+ public override long CompressedSize => _filePart?.Header.PackedSize ?? 0;
+
+ public override CompressionType CompressionType
+ {
+ get
+ {
+ if (_filePart.Header.CompressionType == Headers.CompressionType.Stored)
+ {
+ return CompressionType.None;
+ }
+ return CompressionType.AceLZ77;
+ }
+ }
+
+ public override long Size => _filePart?.Header.OriginalSize ?? 0;
+
+ public override DateTime? LastModifiedTime => _filePart.Header.DateTime;
+
+ public override DateTime? CreatedTime => null;
+
+ public override DateTime? LastAccessedTime => null;
+
+ public override DateTime? ArchivedTime => null;
+
+ public override bool IsEncrypted => _filePart.Header.IsFileEncrypted;
+
+ public override bool IsDirectory => _filePart.Header.IsDirectory;
+
+ public override bool IsSplitAfter => false;
+
+ internal override IEnumerable Parts => _filePart.Empty();
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/AceFilePart.cs b/src/SharpCompress/Common/Ace/AceFilePart.cs
new file mode 100644
index 000000000..6efefaf56
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/AceFilePart.cs
@@ -0,0 +1,52 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using SharpCompress.Common.Ace.Headers;
+using SharpCompress.IO;
+
+namespace SharpCompress.Common.Ace
+{
+ public class AceFilePart : FilePart
+ {
+ private readonly Stream _stream;
+ internal AceFileHeader Header { get; set; }
+
+ internal AceFilePart(AceFileHeader localAceHeader, Stream seekableStream)
+ : base(localAceHeader.ArchiveEncoding)
+ {
+ _stream = seekableStream;
+ Header = localAceHeader;
+ }
+
+ internal override string? FilePartName => Header.Filename;
+
+ internal override Stream GetCompressedStream()
+ {
+ if (_stream != null)
+ {
+ Stream compressedStream;
+ switch (Header.CompressionType)
+ {
+ case Headers.CompressionType.Stored:
+ compressedStream = new ReadOnlySubStream(
+ _stream,
+ Header.DataStartPosition,
+ Header.PackedSize
+ );
+ break;
+ default:
+ throw new NotSupportedException(
+ "CompressionMethod: " + Header.CompressionQuality
+ );
+ }
+ return compressedStream;
+ }
+ return _stream.NotNull();
+ }
+
+ internal override Stream? GetRawStream() => _stream;
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/AceVolume.cs b/src/SharpCompress/Common/Ace/AceVolume.cs
new file mode 100644
index 000000000..28456866b
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/AceVolume.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using SharpCompress.Common.Arj;
+using SharpCompress.Readers;
+
+namespace SharpCompress.Common.Ace
+{
+ public class AceVolume : Volume
+ {
+ public AceVolume(Stream stream, ReaderOptions readerOptions, int index = 0)
+ : base(stream, readerOptions, index) { }
+
+ public override bool IsFirstVolume
+ {
+ get { return true; }
+ }
+
+ ///
+ /// ArjArchive is part of a multi-part archive.
+ ///
+ public override bool IsMultiVolume
+ {
+ get { return false; }
+ }
+
+ internal IEnumerable GetVolumeFileParts()
+ {
+ return new List();
+ }
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/Headers/AceFileHeader.cs b/src/SharpCompress/Common/Ace/Headers/AceFileHeader.cs
new file mode 100644
index 000000000..9fd34c63d
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/Headers/AceFileHeader.cs
@@ -0,0 +1,171 @@
+using System;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using System.Xml.Linq;
+using SharpCompress.Common.Arc;
+
+namespace SharpCompress.Common.Ace.Headers
+{
+ ///
+ /// ACE file entry header
+ ///
+ public sealed class AceFileHeader : AceHeader
+ {
+ public long DataStartPosition { get; private set; }
+ public long PackedSize { get; set; }
+ public long OriginalSize { get; set; }
+ public DateTime DateTime { get; set; }
+ public int Attributes { get; set; }
+ public uint Crc32 { get; set; }
+ public CompressionType CompressionType { get; set; }
+ public CompressionQuality CompressionQuality { get; set; }
+ public ushort Parameters { get; set; }
+ public string Filename { get; set; } = string.Empty;
+ public List Comment { get; set; } = new();
+
+ ///
+ /// File data offset in the archive
+ ///
+ public ulong DataOffset { get; set; }
+
+ public bool IsDirectory => (Attributes & 0x10) != 0;
+
+ public bool IsContinuedFromPrev =>
+ (HeaderFlags & SharpCompress.Common.Ace.Headers.HeaderFlags.CONTINUED_PREV) != 0;
+
+ public bool IsContinuedToNext =>
+ (HeaderFlags & SharpCompress.Common.Ace.Headers.HeaderFlags.CONTINUED_NEXT) != 0;
+
+ public int DictionarySize
+ {
+ get
+ {
+ int bits = Parameters & 0x0F;
+ return bits < 10 ? 1024 : 1 << bits;
+ }
+ }
+
+ public AceFileHeader(ArchiveEncoding archiveEncoding)
+ : base(archiveEncoding, AceHeaderType.FILE) { }
+
+ ///
+ /// Reads the next file entry header from the stream.
+ /// Returns null if no more entries or end of archive.
+ /// Supports both ACE 1.0 and ACE 2.0 formats.
+ ///
+ public override AceHeader? Read(Stream stream)
+ {
+ var headerData = ReadHeader(stream);
+ if (headerData.Length == 0)
+ {
+ return null;
+ }
+ int offset = 0;
+
+ // Header type (1 byte)
+ HeaderType = headerData[offset++];
+
+ // Skip recovery record headers (ACE 2.0 feature)
+ if (HeaderType == (byte)SharpCompress.Common.Ace.Headers.AceHeaderType.RECOVERY32)
+ {
+ // Skip to next header
+ return null;
+ }
+
+ if (HeaderType != (byte)SharpCompress.Common.Ace.Headers.AceHeaderType.FILE)
+ {
+ // Unknown header type - skip
+ return null;
+ }
+
+ // Header flags (2 bytes)
+ HeaderFlags = BitConverter.ToUInt16(headerData, offset);
+ offset += 2;
+
+ // Packed size (4 bytes)
+ PackedSize = BitConverter.ToUInt32(headerData, offset);
+ offset += 4;
+
+ // Original size (4 bytes)
+ OriginalSize = BitConverter.ToUInt32(headerData, offset);
+ offset += 4;
+
+ // File date/time in DOS format (4 bytes)
+ var dosDateTime = BitConverter.ToUInt32(headerData, offset);
+ DateTime = ConvertDosDateTime(dosDateTime);
+ offset += 4;
+
+ // File attributes (4 bytes)
+ Attributes = (int)BitConverter.ToUInt32(headerData, offset);
+ offset += 4;
+
+ // CRC32 (4 bytes)
+ Crc32 = BitConverter.ToUInt32(headerData, offset);
+ offset += 4;
+
+ // Compression type (1 byte)
+ byte compressionType = headerData[offset++];
+ CompressionType = GetCompressionType(compressionType);
+
+ // Compression quality/parameter (1 byte)
+ byte compressionQuality = headerData[offset++];
+ CompressionQuality = GetCompressionQuality(compressionQuality);
+
+ // Parameters (2 bytes)
+ Parameters = BitConverter.ToUInt16(headerData, offset);
+ offset += 2;
+
+ // Reserved (2 bytes) - skip
+ offset += 2;
+
+ // Filename length (2 bytes)
+ var filenameLength = BitConverter.ToUInt16(headerData, offset);
+ offset += 2;
+
+ // Filename
+ if (offset + filenameLength <= headerData.Length)
+ {
+ Filename = ArchiveEncoding.Decode(headerData, offset, filenameLength);
+ offset += filenameLength;
+ }
+
+ // Handle comment if present
+ if ((HeaderFlags & SharpCompress.Common.Ace.Headers.HeaderFlags.COMMENT) != 0)
+ {
+ // Comment length (2 bytes)
+ if (offset + 2 <= headerData.Length)
+ {
+ ushort commentLength = BitConverter.ToUInt16(headerData, offset);
+ offset += 2 + commentLength; // Skip comment
+ }
+ }
+
+ // Store the data start position
+ DataStartPosition = stream.Position;
+
+ return this;
+ }
+
+ public CompressionType GetCompressionType(byte value) =>
+ value switch
+ {
+ 0 => CompressionType.Stored,
+ 1 => CompressionType.Lz77,
+ 2 => CompressionType.Blocked,
+ _ => CompressionType.Unknown,
+ };
+
+ public CompressionQuality GetCompressionQuality(byte value) =>
+ value switch
+ {
+ 0 => CompressionQuality.None,
+ 1 => CompressionQuality.Fastest,
+ 2 => CompressionQuality.Fast,
+ 3 => CompressionQuality.Normal,
+ 4 => CompressionQuality.Good,
+ 5 => CompressionQuality.Best,
+ _ => CompressionQuality.Unknown,
+ };
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/Headers/AceHeader.cs b/src/SharpCompress/Common/Ace/Headers/AceHeader.cs
new file mode 100644
index 000000000..0fa816e5b
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/Headers/AceHeader.cs
@@ -0,0 +1,153 @@
+using System;
+using System.IO;
+using SharpCompress.Common.Arj.Headers;
+using SharpCompress.Crypto;
+
+namespace SharpCompress.Common.Ace.Headers
+{
+ ///
+ /// Header type constants
+ ///
+ public enum AceHeaderType
+ {
+ MAIN = 0,
+ FILE = 1,
+ RECOVERY32 = 2,
+ RECOVERY64A = 3,
+ RECOVERY64B = 4,
+ }
+
+ public abstract class AceHeader
+ {
+ // ACE signature: bytes at offset 7 should be "**ACE**"
+ private static readonly byte[] AceSignature =
+ [
+ (byte)'*',
+ (byte)'*',
+ (byte)'A',
+ (byte)'C',
+ (byte)'E',
+ (byte)'*',
+ (byte)'*',
+ ];
+
+ public AceHeader(ArchiveEncoding archiveEncoding, AceHeaderType type)
+ {
+ AceHeaderType = type;
+ ArchiveEncoding = archiveEncoding;
+ }
+
+ public ArchiveEncoding ArchiveEncoding { get; }
+ public AceHeaderType AceHeaderType { get; }
+
+ public ushort HeaderFlags { get; set; }
+ public ushort HeaderCrc { get; set; }
+ public ushort HeaderSize { get; set; }
+ public byte HeaderType { get; set; }
+
+ public bool IsFileEncrypted =>
+ (HeaderFlags & SharpCompress.Common.Ace.Headers.HeaderFlags.FILE_ENCRYPTED) != 0;
+ public bool Is64Bit =>
+ (HeaderFlags & SharpCompress.Common.Ace.Headers.HeaderFlags.MEMORY_64BIT) != 0;
+
+ public bool IsSolid =>
+ (HeaderFlags & SharpCompress.Common.Ace.Headers.HeaderFlags.SOLID_MAIN) != 0;
+
+ public bool IsMultiVolume =>
+ (HeaderFlags & SharpCompress.Common.Ace.Headers.HeaderFlags.MULTIVOLUME) != 0;
+
+ public abstract AceHeader? Read(Stream reader);
+
+ public byte[] ReadHeader(Stream stream)
+ {
+ // Read header CRC (2 bytes) and header size (2 bytes)
+ var headerBytes = new byte[4];
+ if (stream.Read(headerBytes, 0, 4) != 4)
+ {
+ return Array.Empty();
+ }
+
+ HeaderCrc = BitConverter.ToUInt16(headerBytes, 0); // CRC for validation
+ HeaderSize = BitConverter.ToUInt16(headerBytes, 2);
+ if (HeaderSize == 0)
+ {
+ return Array.Empty();
+ }
+
+ // Read the header data
+ var body = new byte[HeaderSize];
+ if (stream.Read(body, 0, HeaderSize) != HeaderSize)
+ {
+ return Array.Empty();
+ }
+
+ // Verify crc
+ var checksum = AceCrc.AceCrc16(body);
+ if (checksum != HeaderCrc)
+ {
+ throw new InvalidDataException("Header checksum is invalid");
+ }
+ return body;
+ }
+
+ public static bool IsArchive(Stream stream)
+ {
+ // ACE files have a specific signature
+ // First two bytes are typically 0x60 0xEA (signature bytes)
+ // At offset 7, there should be "**ACE**" (7 bytes)
+ var bytes = new byte[14];
+ if (stream.Read(bytes, 0, 14) != 14)
+ {
+ return false;
+ }
+
+ // Check for "**ACE**" at offset 7
+ return CheckMagicBytes(bytes, 7);
+ }
+
+ protected static bool CheckMagicBytes(byte[] headerBytes, int offset)
+ {
+ // Check for "**ACE**" at specified offset
+ for (int i = 0; i < AceSignature.Length; i++)
+ {
+ if (headerBytes[offset + i] != AceSignature[i])
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ protected DateTime ConvertDosDateTime(uint dosDateTime)
+ {
+ try
+ {
+ int second = (int)(dosDateTime & 0x1F) * 2;
+ int minute = (int)((dosDateTime >> 5) & 0x3F);
+ int hour = (int)((dosDateTime >> 11) & 0x1F);
+ int day = (int)((dosDateTime >> 16) & 0x1F);
+ int month = (int)((dosDateTime >> 21) & 0x0F);
+ int year = (int)((dosDateTime >> 25) & 0x7F) + 1980;
+
+ if (
+ day < 1
+ || day > 31
+ || month < 1
+ || month > 12
+ || hour > 23
+ || minute > 59
+ || second > 59
+ )
+ {
+ return DateTime.MinValue;
+ }
+
+ return new DateTime(year, month, day, hour, minute, second);
+ }
+ catch
+ {
+ return DateTime.MinValue;
+ }
+ }
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/Headers/AceMainHeader.cs b/src/SharpCompress/Common/Ace/Headers/AceMainHeader.cs
new file mode 100644
index 000000000..c2fc68159
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/Headers/AceMainHeader.cs
@@ -0,0 +1,97 @@
+using System;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using SharpCompress.Common.Ace.Headers;
+using SharpCompress.Common.Zip.Headers;
+using SharpCompress.Crypto;
+
+namespace SharpCompress.Common.Ace.Headers
+{
+ ///
+ /// ACE main archive header
+ ///
+ public sealed class AceMainHeader : AceHeader
+ {
+ public byte ExtractVersion { get; set; }
+ public byte CreatorVersion { get; set; }
+ public HostOS HostOS { get; set; }
+ public byte VolumeNumber { get; set; }
+ public DateTime DateTime { get; set; }
+ public string Advert { get; set; } = string.Empty;
+ public List Comment { get; set; } = new();
+ public byte AceVersion { get; private set; }
+
+ public AceMainHeader(ArchiveEncoding archiveEncoding)
+ : base(archiveEncoding, AceHeaderType.MAIN) { }
+
+ ///
+ /// Reads the main archive header from the stream.
+ /// Returns header if this is a valid ACE archive.
+ /// Supports both ACE 1.0 and ACE 2.0 formats.
+ ///
+ public override AceHeader? Read(Stream stream)
+ {
+ var headerData = ReadHeader(stream);
+ if (headerData.Length == 0)
+ {
+ return null;
+ }
+ int offset = 0;
+
+ // Header type should be 0 for main header
+ if (headerData[offset++] != HeaderType)
+ {
+ return null;
+ }
+
+ // Header flags (2 bytes)
+ HeaderFlags = BitConverter.ToUInt16(headerData, offset);
+ offset += 2;
+
+ // Skip signature "**ACE**" (7 bytes)
+ if (!CheckMagicBytes(headerData, offset))
+ {
+ throw new InvalidDataException("Invalid ACE archive signature.");
+ }
+ offset += 7;
+
+ // ACE version (1 byte) - 10 for ACE 1.0, 20 for ACE 2.0
+ AceVersion = headerData[offset++];
+ ExtractVersion = headerData[offset++];
+
+ // Host OS (1 byte)
+ if (offset < headerData.Length)
+ {
+ var hostOsByte = headerData[offset++];
+ HostOS = hostOsByte <= 11 ? (HostOS)hostOsByte : HostOS.Unknown;
+ }
+ // Volume number (1 byte)
+ VolumeNumber = headerData[offset++];
+
+ // Creation date/time (4 bytes)
+ var dosDateTime = BitConverter.ToUInt32(headerData, offset);
+ DateTime = ConvertDosDateTime(dosDateTime);
+ offset += 4;
+
+ // Reserved fields (8 bytes)
+ if (offset + 8 <= headerData.Length)
+ {
+ offset += 8;
+ }
+
+ // Skip additional fields based on flags
+ // Handle comment if present
+ if ((HeaderFlags & SharpCompress.Common.Ace.Headers.HeaderFlags.COMMENT) != 0)
+ {
+ if (offset + 2 <= headerData.Length)
+ {
+ ushort commentLength = BitConverter.ToUInt16(headerData, offset);
+ offset += 2 + commentLength;
+ }
+ }
+
+ return this;
+ }
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/Headers/CompressionQuality.cs b/src/SharpCompress/Common/Ace/Headers/CompressionQuality.cs
new file mode 100644
index 000000000..57017b55f
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/Headers/CompressionQuality.cs
@@ -0,0 +1,16 @@
+namespace SharpCompress.Common.Ace.Headers
+{
+ ///
+ /// Compression quality
+ ///
+ public enum CompressionQuality
+ {
+ None,
+ Fastest,
+ Fast,
+ Normal,
+ Good,
+ Best,
+ Unknown,
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/Headers/CompressionType.cs b/src/SharpCompress/Common/Ace/Headers/CompressionType.cs
new file mode 100644
index 000000000..799e7929b
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/Headers/CompressionType.cs
@@ -0,0 +1,13 @@
+namespace SharpCompress.Common.Ace.Headers
+{
+ ///
+ /// Compression types
+ ///
+ public enum CompressionType
+ {
+ Stored,
+ Lz77,
+ Blocked,
+ Unknown,
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/Headers/HeaderFlags.cs b/src/SharpCompress/Common/Ace/Headers/HeaderFlags.cs
new file mode 100644
index 000000000..6a5f8926f
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/Headers/HeaderFlags.cs
@@ -0,0 +1,33 @@
+namespace SharpCompress.Common.Ace.Headers
+{
+ ///
+ /// Header flags (main + file, overlapping meanings)
+ ///
+ public static class HeaderFlags
+ {
+ // Shared / low bits
+ public const ushort ADDSIZE = 0x0001; // extra size field present
+ public const ushort COMMENT = 0x0002; // comment present
+ public const ushort MEMORY_64BIT = 0x0004;
+ public const ushort AV_STRING = 0x0008; // AV string present
+ public const ushort SOLID = 0x0010; // solid file
+ public const ushort LOCKED = 0x0020;
+ public const ushort PROTECTED = 0x0040;
+
+ // Main header specific
+ public const ushort V20FORMAT = 0x0100;
+ public const ushort SFX = 0x0200;
+ public const ushort LIMITSFXJR = 0x0400;
+ public const ushort MULTIVOLUME = 0x0800;
+ public const ushort ADVERT = 0x1000;
+ public const ushort RECOVERY = 0x2000;
+ public const ushort LOCKED_MAIN = 0x4000;
+ public const ushort SOLID_MAIN = 0x8000;
+
+ // File header specific (same bits, different meaning)
+ public const ushort NTSECURITY = 0x0400;
+ public const ushort CONTINUED_PREV = 0x1000;
+ public const ushort CONTINUED_NEXT = 0x2000;
+ public const ushort FILE_ENCRYPTED = 0x4000; // file encrypted (file header)
+ }
+}
diff --git a/src/SharpCompress/Common/Ace/Headers/HostOS.cs b/src/SharpCompress/Common/Ace/Headers/HostOS.cs
new file mode 100644
index 000000000..173d56eb8
--- /dev/null
+++ b/src/SharpCompress/Common/Ace/Headers/HostOS.cs
@@ -0,0 +1,22 @@
+namespace SharpCompress.Common.Ace.Headers
+{
+ ///
+ /// Host OS type
+ ///
+ public enum HostOS
+ {
+ MsDos = 0,
+ Os2,
+ Windows,
+ Unix,
+ MacOs,
+ WinNt,
+ Primos,
+ AppleGs,
+ Atari,
+ Vax,
+ Amiga,
+ Next,
+ Unknown,
+ }
+}
diff --git a/src/SharpCompress/Common/ArchiveExtractionEventArgs.cs b/src/SharpCompress/Common/ArchiveExtractionEventArgs.cs
deleted file mode 100644
index 808177489..000000000
--- a/src/SharpCompress/Common/ArchiveExtractionEventArgs.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using System;
-
-namespace SharpCompress.Common;
-
-public class ArchiveExtractionEventArgs : EventArgs
-{
- internal ArchiveExtractionEventArgs(T entry) => Item = entry;
-
- public T Item { get; }
-}
diff --git a/src/SharpCompress/Common/ArchiveType.cs b/src/SharpCompress/Common/ArchiveType.cs
index 9d9438955..5952f6459 100644
--- a/src/SharpCompress/Common/ArchiveType.cs
+++ b/src/SharpCompress/Common/ArchiveType.cs
@@ -9,4 +9,5 @@ public enum ArchiveType
GZip,
Arc,
Arj,
+ Ace,
}
diff --git a/src/SharpCompress/Common/Arj/Headers/ArjHeader.cs b/src/SharpCompress/Common/Arj/Headers/ArjHeader.cs
index 138f75e72..142aca5bb 100644
--- a/src/SharpCompress/Common/Arj/Headers/ArjHeader.cs
+++ b/src/SharpCompress/Common/Arj/Headers/ArjHeader.cs
@@ -34,14 +34,13 @@ public ArjHeader(ArjHeaderType type)
public byte[] ReadHeader(Stream stream)
{
// check for magic bytes
- Span magic = stackalloc byte[2];
+ var magic = new byte[2];
if (stream.Read(magic) != 2)
{
return Array.Empty();
}
- var magicValue = (ushort)(magic[0] | magic[1] << 8);
- if (magicValue != ARJ_MAGIC)
+ if (!CheckMagicBytes(magic))
{
throw new InvalidDataException("Not an ARJ file (wrong magic bytes)");
}
@@ -138,5 +137,22 @@ public static FileType FileTypeFromByte(byte value)
? (FileType)value
: Headers.FileType.Unknown;
}
+
+ public static bool IsArchive(Stream stream)
+ {
+ var bytes = new byte[2];
+ if (stream.Read(bytes, 0, 2) != 2)
+ {
+ return false;
+ }
+
+ return CheckMagicBytes(bytes);
+ }
+
+ protected static bool CheckMagicBytes(byte[] headerBytes)
+ {
+ var magicValue = (ushort)(headerBytes[0] | headerBytes[1] << 8);
+ return magicValue == ARJ_MAGIC;
+ }
}
}
diff --git a/src/SharpCompress/Common/CompressedBytesReadEventArgs.cs b/src/SharpCompress/Common/CompressedBytesReadEventArgs.cs
deleted file mode 100644
index 34ca461f1..000000000
--- a/src/SharpCompress/Common/CompressedBytesReadEventArgs.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-
-namespace SharpCompress.Common;
-
-public sealed class CompressedBytesReadEventArgs : EventArgs
-{
- public CompressedBytesReadEventArgs(
- long compressedBytesRead,
- long currentFilePartCompressedBytesRead
- )
- {
- CompressedBytesRead = compressedBytesRead;
- CurrentFilePartCompressedBytesRead = currentFilePartCompressedBytesRead;
- }
-
- ///
- /// Compressed bytes read for the current entry
- ///
- public long CompressedBytesRead { get; }
-
- ///
- /// Current file part read for Multipart files (e.g. Rar)
- ///
- public long CurrentFilePartCompressedBytesRead { get; }
-}
diff --git a/src/SharpCompress/Common/CompressionType.cs b/src/SharpCompress/Common/CompressionType.cs
index 7c50758a0..595834233 100644
--- a/src/SharpCompress/Common/CompressionType.cs
+++ b/src/SharpCompress/Common/CompressionType.cs
@@ -30,4 +30,5 @@ public enum CompressionType
Distilled,
ZStandard,
ArjLZ77,
+ AceLZ77,
}
diff --git a/src/SharpCompress/Common/ExtractionMethods.cs b/src/SharpCompress/Common/ExtractionMethods.cs
index 485fdf4d3..509524b15 100644
--- a/src/SharpCompress/Common/ExtractionMethods.cs
+++ b/src/SharpCompress/Common/ExtractionMethods.cs
@@ -128,7 +128,7 @@ public static async Task WriteEntryToDirectoryAsync(
IEntry entry,
string destinationDirectory,
ExtractionOptions? options,
- Func writeAsync,
+ Func writeAsync,
CancellationToken cancellationToken = default
)
{
@@ -189,7 +189,7 @@ public static async Task WriteEntryToDirectoryAsync(
"Entry is trying to write a file outside of the destination directory."
);
}
- await writeAsync(destinationFileName, options).ConfigureAwait(false);
+ await writeAsync(destinationFileName, options, cancellationToken).ConfigureAwait(false);
}
else if (options.ExtractFullPath && !Directory.Exists(destinationFileName))
{
@@ -201,7 +201,7 @@ public static async Task WriteEntryToFileAsync(
IEntry entry,
string destinationFileName,
ExtractionOptions? options,
- Func openAndWriteAsync,
+ Func openAndWriteAsync,
CancellationToken cancellationToken = default
)
{
@@ -225,7 +225,8 @@ public static async Task WriteEntryToFileAsync(
fm = FileMode.CreateNew;
}
- await openAndWriteAsync(destinationFileName, fm).ConfigureAwait(false);
+ await openAndWriteAsync(destinationFileName, fm, cancellationToken)
+ .ConfigureAwait(false);
entry.PreserveExtractionOptions(destinationFileName, options);
}
}
diff --git a/src/SharpCompress/Common/FilePartExtractionBeginEventArgs.cs b/src/SharpCompress/Common/FilePartExtractionBeginEventArgs.cs
deleted file mode 100644
index d5b8328cc..000000000
--- a/src/SharpCompress/Common/FilePartExtractionBeginEventArgs.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-
-namespace SharpCompress.Common;
-
-public sealed class FilePartExtractionBeginEventArgs : EventArgs
-{
- public FilePartExtractionBeginEventArgs(string name, long size, long compressedSize)
- {
- Name = name;
- Size = size;
- CompressedSize = compressedSize;
- }
-
- ///
- /// File name for the part for the current entry
- ///
- public string Name { get; }
-
- ///
- /// Uncompressed size of the current entry in the part
- ///
- public long Size { get; }
-
- ///
- /// Compressed size of the current entry in the part
- ///
- public long CompressedSize { get; }
-}
diff --git a/src/SharpCompress/Common/IExtractionListener.cs b/src/SharpCompress/Common/IExtractionListener.cs
deleted file mode 100644
index e1389810a..000000000
--- a/src/SharpCompress/Common/IExtractionListener.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace SharpCompress.Common;
-
-public interface IExtractionListener
-{
- void FireFilePartExtractionBegin(string name, long size, long compressedSize);
- void FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes);
-}
diff --git a/src/SharpCompress/Common/ProgressReport.cs b/src/SharpCompress/Common/ProgressReport.cs
new file mode 100644
index 000000000..2d8368674
--- /dev/null
+++ b/src/SharpCompress/Common/ProgressReport.cs
@@ -0,0 +1,43 @@
+namespace SharpCompress.Common;
+
+///
+/// Represents progress information for compression or extraction operations.
+///
+public sealed class ProgressReport
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The path of the entry being processed.
+ /// Number of bytes transferred so far.
+ /// Total bytes to be transferred, or null if unknown.
+ public ProgressReport(string entryPath, long bytesTransferred, long? totalBytes)
+ {
+ EntryPath = entryPath;
+ BytesTransferred = bytesTransferred;
+ TotalBytes = totalBytes;
+ }
+
+ ///
+ /// Gets the path of the entry being processed.
+ ///
+ public string EntryPath { get; }
+
+ ///
+ /// Gets the number of bytes transferred so far.
+ ///
+ public long BytesTransferred { get; }
+
+ ///
+ /// Gets the total number of bytes to be transferred, or null if unknown.
+ ///
+ public long? TotalBytes { get; }
+
+ ///
+ /// Gets the progress percentage (0-100), or null if total bytes is unknown.
+ ///
+ public double? PercentComplete =>
+ TotalBytes.HasValue && TotalBytes.Value > 0
+ ? (double)BytesTransferred / TotalBytes.Value * 100
+ : null;
+}
diff --git a/src/SharpCompress/Common/ReaderExtractionEventArgs.cs b/src/SharpCompress/Common/ReaderExtractionEventArgs.cs
deleted file mode 100644
index 7c4363e20..000000000
--- a/src/SharpCompress/Common/ReaderExtractionEventArgs.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System;
-using SharpCompress.Readers;
-
-namespace SharpCompress.Common;
-
-public sealed class ReaderExtractionEventArgs : EventArgs
-{
- internal ReaderExtractionEventArgs(T entry, ReaderProgress? readerProgress = null)
- {
- Item = entry;
- ReaderProgress = readerProgress;
- }
-
- public T Item { get; }
-
- public ReaderProgress? ReaderProgress { get; }
-}
diff --git a/src/SharpCompress/Common/Tar/Headers/TarHeader.cs b/src/SharpCompress/Common/Tar/Headers/TarHeader.cs
index 06a1f10a4..e6b7c265c 100644
--- a/src/SharpCompress/Common/Tar/Headers/TarHeader.cs
+++ b/src/SharpCompress/Common/Tar/Headers/TarHeader.cs
@@ -1,5 +1,6 @@
using System;
using System.Buffers.Binary;
+using System.Collections.Generic;
using System.IO;
using System.Text;
@@ -9,8 +10,16 @@ internal sealed class TarHeader
{
internal static readonly DateTime EPOCH = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
- public TarHeader(ArchiveEncoding archiveEncoding) => ArchiveEncoding = archiveEncoding;
+ public TarHeader(
+ ArchiveEncoding archiveEncoding,
+ TarHeaderWriteFormat writeFormat = TarHeaderWriteFormat.GNU_TAR_LONG_LINK
+ )
+ {
+ ArchiveEncoding = archiveEncoding;
+ WriteFormat = writeFormat;
+ }
+ internal TarHeaderWriteFormat WriteFormat { get; set; }
internal string? Name { get; set; }
internal string? LinkName { get; set; }
@@ -30,6 +39,114 @@ internal sealed class TarHeader
private const int MAX_LONG_NAME_SIZE = 32768;
internal void Write(Stream output)
+ {
+ switch (WriteFormat)
+ {
+ case TarHeaderWriteFormat.GNU_TAR_LONG_LINK:
+ WriteGnuTarLongLink(output);
+ break;
+ case TarHeaderWriteFormat.USTAR:
+ WriteUstar(output);
+ break;
+ default:
+ throw new Exception("This should be impossible...");
+ }
+ }
+
+ internal void WriteUstar(Stream output)
+ {
+ var buffer = new byte[BLOCK_SIZE];
+
+ WriteOctalBytes(511, buffer, 100, 8); // file mode
+ WriteOctalBytes(0, buffer, 108, 8); // owner ID
+ WriteOctalBytes(0, buffer, 116, 8); // group ID
+
+ //ArchiveEncoding.UTF8.GetBytes("magic").CopyTo(buffer, 257);
+ var nameByteCount = ArchiveEncoding
+ .GetEncoding()
+ .GetByteCount(Name.NotNull("Name is null"));
+
+ if (nameByteCount > 100)
+ {
+ // if name is longer, try to split it into name and namePrefix
+
+ string fullName = Name.NotNull("Name is null");
+
+ // find all directory separators
+ List dirSeps = new List();
+ for (int i = 0; i < fullName.Length; i++)
+ {
+ if (fullName[i] == Path.DirectorySeparatorChar)
+ {
+ dirSeps.Add(i);
+ }
+ }
+
+ // find the right place to split the name
+ int splitIndex = -1;
+ for (int i = 0; i < dirSeps.Count; i++)
+ {
+ int count = ArchiveEncoding
+ .GetEncoding()
+ .GetByteCount(fullName.Substring(0, dirSeps[i]));
+ if (count < 155)
+ {
+ splitIndex = dirSeps[i];
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ if (splitIndex == -1)
+ {
+ throw new Exception(
+ $"Tar header USTAR format can not fit file name \"{fullName}\" of length {nameByteCount}! Directory separator not found! Try using GNU Tar format instead!"
+ );
+ }
+
+ string namePrefix = fullName.Substring(0, splitIndex);
+ string name = fullName.Substring(splitIndex + 1);
+
+ if (this.ArchiveEncoding.GetEncoding().GetByteCount(namePrefix) >= 155)
+ throw new Exception(
+ $"Tar header USTAR format can not fit file name \"{fullName}\" of length {nameByteCount}! Try using GNU Tar format instead!"
+ );
+
+ if (this.ArchiveEncoding.GetEncoding().GetByteCount(name) >= 100)
+ throw new Exception(
+ $"Tar header USTAR format can not fit file name \"{fullName}\" of length {nameByteCount}! Try using GNU Tar format instead!"
+ );
+
+ // write name prefix
+ WriteStringBytes(ArchiveEncoding.Encode(namePrefix), buffer, 345, 100);
+ // write partial name
+ WriteStringBytes(ArchiveEncoding.Encode(name), buffer, 100);
+ }
+ else
+ {
+ WriteStringBytes(ArchiveEncoding.Encode(Name.NotNull("Name is null")), buffer, 100);
+ }
+
+ WriteOctalBytes(Size, buffer, 124, 12);
+ var time = (long)(LastModifiedTime.ToUniversalTime() - EPOCH).TotalSeconds;
+ WriteOctalBytes(time, buffer, 136, 12);
+ buffer[156] = (byte)EntryType;
+
+ // write ustar magic field
+ WriteStringBytes(Encoding.ASCII.GetBytes("ustar"), buffer, 257, 6);
+ // write ustar version "00"
+ buffer[263] = 0x30;
+ buffer[264] = 0x30;
+
+ var crc = RecalculateChecksum(buffer);
+ WriteOctalBytes(crc, buffer, 148, 8);
+
+ output.Write(buffer, 0, buffer.Length);
+ }
+
+ internal void WriteGnuTarLongLink(Stream output)
{
var buffer = new byte[BLOCK_SIZE];
@@ -85,7 +202,7 @@ internal void Write(Stream output)
0,
100 - ArchiveEncoding.GetEncoding().GetMaxByteCount(1)
);
- Write(output);
+ WriteGnuTarLongLink(output);
}
}
@@ -241,6 +358,18 @@ private static void WriteStringBytes(ReadOnlySpan name, Span buffer,
buffer.Slice(i, length - i).Clear();
}
+ private static void WriteStringBytes(
+ ReadOnlySpan name,
+ Span buffer,
+ int offset,
+ int length
+ )
+ {
+ name.CopyTo(buffer.Slice(offset));
+ var i = Math.Min(length, name.Length);
+ buffer.Slice(offset + i, length - i).Clear();
+ }
+
private static void WriteStringBytes(string name, byte[] buffer, int offset, int length)
{
int i;
diff --git a/src/SharpCompress/Common/Tar/Headers/TarHeaderWriteFormat.cs b/src/SharpCompress/Common/Tar/Headers/TarHeaderWriteFormat.cs
new file mode 100644
index 000000000..3a3a434ab
--- /dev/null
+++ b/src/SharpCompress/Common/Tar/Headers/TarHeaderWriteFormat.cs
@@ -0,0 +1,7 @@
+namespace SharpCompress.Common.Tar.Headers;
+
+public enum TarHeaderWriteFormat
+{
+ GNU_TAR_LONG_LINK,
+ USTAR,
+}
diff --git a/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs b/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs
index 31322019f..b91d72912 100644
--- a/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs
+++ b/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs
@@ -1,6 +1,7 @@
using System;
using System.Buffers.Binary;
using System.Security.Cryptography;
+using System.Text;
namespace SharpCompress.Common.Zip;
@@ -19,8 +20,24 @@ string password
{
_keySize = keySize;
-#if NETFRAMEWORK || NETSTANDARD2_0
+#if NETFRAMEWORK
var rfc2898 = new Rfc2898DeriveBytes(password, salt, RFC2898_ITERATIONS);
+ KeyBytes = rfc2898.GetBytes(KeySizeInBytes);
+ IvBytes = rfc2898.GetBytes(KeySizeInBytes);
+ var generatedVerifyValue = rfc2898.GetBytes(2);
+#elif NET10_0_OR_GREATER
+ var derivedKeySize = (KeySizeInBytes * 2) + 2;
+ var passwordBytes = Encoding.UTF8.GetBytes(password);
+ var derivedKey = Rfc2898DeriveBytes.Pbkdf2(
+ passwordBytes,
+ salt,
+ RFC2898_ITERATIONS,
+ HashAlgorithmName.SHA1,
+ derivedKeySize
+ );
+ KeyBytes = derivedKey.AsSpan(0, KeySizeInBytes).ToArray();
+ IvBytes = derivedKey.AsSpan(KeySizeInBytes, KeySizeInBytes).ToArray();
+ var generatedVerifyValue = derivedKey.AsSpan((KeySizeInBytes * 2), 2).ToArray();
#else
var rfc2898 = new Rfc2898DeriveBytes(
password,
@@ -28,11 +45,10 @@ string password
RFC2898_ITERATIONS,
HashAlgorithmName.SHA1
);
-#endif
-
- KeyBytes = rfc2898.GetBytes(KeySizeInBytes); // 16 or 24 or 32 ???
+ KeyBytes = rfc2898.GetBytes(KeySizeInBytes);
IvBytes = rfc2898.GetBytes(KeySizeInBytes);
var generatedVerifyValue = rfc2898.GetBytes(2);
+#endif
var verify = BinaryPrimitives.ReadInt16LittleEndian(passwordVerifyValue);
var generated = BinaryPrimitives.ReadInt16LittleEndian(generatedVerifyValue);
diff --git a/src/SharpCompress/Common/Zip/ZipFilePart.cs b/src/SharpCompress/Common/Zip/ZipFilePart.cs
index 77dc4abba..16eb8e1a9 100644
--- a/src/SharpCompress/Common/Zip/ZipFilePart.cs
+++ b/src/SharpCompress/Common/Zip/ZipFilePart.cs
@@ -13,8 +13,8 @@
using SharpCompress.Compressors.Reduce;
using SharpCompress.Compressors.Shrink;
using SharpCompress.Compressors.Xz;
+using SharpCompress.Compressors.ZStandard;
using SharpCompress.IO;
-using ZstdSharp;
namespace SharpCompress.Common.Zip;
diff --git a/src/SharpCompress/Compressors/BZip2/CBZip2OutputStream.cs b/src/SharpCompress/Compressors/BZip2/CBZip2OutputStream.cs
index db470ff26..7ee38b81a 100644
--- a/src/SharpCompress/Compressors/BZip2/CBZip2OutputStream.cs
+++ b/src/SharpCompress/Compressors/BZip2/CBZip2OutputStream.cs
@@ -544,6 +544,12 @@ private void InitBlock()
private void EndBlock()
{
+ // Skip block processing for empty input (no data written)
+ if (last < 0)
+ {
+ return;
+ }
+
blockCRC = mCrc.GetFinalCRC();
combinedCRC = (combinedCRC << 1) | (int)(((uint)combinedCRC) >> 31);
combinedCRC ^= blockCRC;
diff --git a/src/SharpCompress/Compressors/LZMA/LzmaStream.cs b/src/SharpCompress/Compressors/LZMA/LzmaStream.cs
index eaef5fd3b..e9d5877ff 100644
--- a/src/SharpCompress/Compressors/LZMA/LzmaStream.cs
+++ b/src/SharpCompress/Compressors/LZMA/LzmaStream.cs
@@ -428,7 +428,9 @@ private void DecodeChunkHeader()
private async Task DecodeChunkHeaderAsync(CancellationToken cancellationToken = default)
{
var controlBuffer = new byte[1];
- await _inputStream.ReadAsync(controlBuffer, 0, 1, cancellationToken).ConfigureAwait(false);
+ await _inputStream
+ .ReadExactlyAsync(controlBuffer, 0, 1, cancellationToken)
+ .ConfigureAwait(false);
var control = controlBuffer[0];
_inputPosition++;
@@ -455,11 +457,15 @@ private async Task DecodeChunkHeaderAsync(CancellationToken cancellationToken =
_availableBytes = (control & 0x1F) << 16;
var buffer = new byte[2];
- await _inputStream.ReadAsync(buffer, 0, 2, cancellationToken).ConfigureAwait(false);
+ await _inputStream
+ .ReadExactlyAsync(buffer, 0, 2, cancellationToken)
+ .ConfigureAwait(false);
_availableBytes += (buffer[0] << 8) + buffer[1] + 1;
_inputPosition += 2;
- await _inputStream.ReadAsync(buffer, 0, 2, cancellationToken).ConfigureAwait(false);
+ await _inputStream
+ .ReadExactlyAsync(buffer, 0, 2, cancellationToken)
+ .ConfigureAwait(false);
_rangeDecoderLimit = (buffer[0] << 8) + buffer[1] + 1;
_inputPosition += 2;
@@ -467,7 +473,7 @@ private async Task DecodeChunkHeaderAsync(CancellationToken cancellationToken =
{
_needProps = false;
await _inputStream
- .ReadAsync(controlBuffer, 0, 1, cancellationToken)
+ .ReadExactlyAsync(controlBuffer, 0, 1, cancellationToken)
.ConfigureAwait(false);
Properties[0] = controlBuffer[0];
_inputPosition++;
@@ -495,7 +501,9 @@ await _inputStream
{
_uncompressedChunk = true;
var buffer = new byte[2];
- await _inputStream.ReadAsync(buffer, 0, 2, cancellationToken).ConfigureAwait(false);
+ await _inputStream
+ .ReadExactlyAsync(buffer, 0, 2, cancellationToken)
+ .ConfigureAwait(false);
_availableBytes = (buffer[0] << 8) + buffer[1] + 1;
_inputPosition += 2;
}
diff --git a/src/SharpCompress/Compressors/LZMA/Registry.cs b/src/SharpCompress/Compressors/LZMA/Registry.cs
index eb3e3bdd6..d71abded2 100644
--- a/src/SharpCompress/Compressors/LZMA/Registry.cs
+++ b/src/SharpCompress/Compressors/LZMA/Registry.cs
@@ -7,7 +7,7 @@
using SharpCompress.Compressors.Filters;
using SharpCompress.Compressors.LZMA.Utilites;
using SharpCompress.Compressors.PPMd;
-using ZstdSharp;
+using SharpCompress.Compressors.ZStandard;
namespace SharpCompress.Compressors.LZMA;
diff --git a/src/SharpCompress/Compressors/Rar/MultiVolumeReadOnlyStream.cs b/src/SharpCompress/Compressors/Rar/MultiVolumeReadOnlyStream.cs
index d20fecd07..df1c59592 100644
--- a/src/SharpCompress/Compressors/Rar/MultiVolumeReadOnlyStream.cs
+++ b/src/SharpCompress/Compressors/Rar/MultiVolumeReadOnlyStream.cs
@@ -37,18 +37,8 @@ void IStreamStack.SetPosition(long position) { }
private IEnumerator filePartEnumerator;
private Stream currentStream;
- private readonly IExtractionListener streamListener;
-
- private long currentPartTotalReadBytes;
- private long currentEntryTotalReadBytes;
-
- internal MultiVolumeReadOnlyStream(
- IEnumerable parts,
- IExtractionListener streamListener
- )
+ internal MultiVolumeReadOnlyStream(IEnumerable parts)
{
- this.streamListener = streamListener;
-
filePartEnumerator = parts.GetEnumerator();
filePartEnumerator.MoveNext();
InitializeNextFilePart();
@@ -81,15 +71,7 @@ private void InitializeNextFilePart()
currentPosition = 0;
currentStream = filePartEnumerator.Current.GetCompressedStream();
- currentPartTotalReadBytes = 0;
-
CurrentCrc = filePartEnumerator.Current.FileHeader.FileCrc;
-
- streamListener.FireFilePartExtractionBegin(
- filePartEnumerator.Current.FilePartName,
- filePartEnumerator.Current.FileHeader.CompressedSize,
- filePartEnumerator.Current.FileHeader.UncompressedSize
- );
}
public override int Read(byte[] buffer, int offset, int count)
@@ -141,12 +123,6 @@ public override int Read(byte[] buffer, int offset, int count)
break;
}
}
- currentPartTotalReadBytes += totalRead;
- currentEntryTotalReadBytes += totalRead;
- streamListener.FireCompressedBytesRead(
- currentPartTotalReadBytes,
- currentEntryTotalReadBytes
- );
return totalRead;
}
@@ -206,12 +182,6 @@ System.Threading.CancellationToken cancellationToken
break;
}
}
- currentPartTotalReadBytes += totalRead;
- currentEntryTotalReadBytes += totalRead;
- streamListener.FireCompressedBytesRead(
- currentPartTotalReadBytes,
- currentEntryTotalReadBytes
- );
return totalRead;
}
@@ -270,12 +240,6 @@ public override async System.Threading.Tasks.ValueTask ReadAsync(
break;
}
}
- currentPartTotalReadBytes += totalRead;
- currentEntryTotalReadBytes += totalRead;
- streamListener.FireCompressedBytesRead(
- currentPartTotalReadBytes,
- currentEntryTotalReadBytes
- );
return totalRead;
}
#endif
diff --git a/src/SharpCompress/Compressors/Rar/RarStream.cs b/src/SharpCompress/Compressors/Rar/RarStream.cs
index ca718d616..a4869075a 100644
--- a/src/SharpCompress/Compressors/Rar/RarStream.cs
+++ b/src/SharpCompress/Compressors/Rar/RarStream.cs
@@ -134,7 +134,7 @@ public override int Read(byte[] buffer, int offset, int count)
fetch = false;
}
_position += outTotal;
- if (count > 0 && outTotal == 0 && _position != Length)
+ if (count > 0 && outTotal == 0 && _position < Length)
{
// sanity check, eg if we try to decompress a redir entry
throw new InvalidOperationException(
@@ -179,7 +179,7 @@ System.Threading.CancellationToken cancellationToken
fetch = false;
}
_position += outTotal;
- if (count > 0 && outTotal == 0 && _position != Length)
+ if (count > 0 && outTotal == 0 && _position < Length)
{
// sanity check, eg if we try to decompress a redir entry
throw new InvalidOperationException(
diff --git a/src/SharpCompress/Compressors/ZStandard/BitOperations.cs b/src/SharpCompress/Compressors/ZStandard/BitOperations.cs
new file mode 100644
index 000000000..fc8e3108d
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/BitOperations.cs
@@ -0,0 +1,311 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#if !NETCOREAPP3_0_OR_GREATER
+
+using System.Runtime.CompilerServices;
+using static SharpCompress.Compressors.ZStandard.UnsafeHelper;
+
+// Some routines inspired by the Stanford Bit Twiddling Hacks by Sean Eron Anderson:
+// http://graphics.stanford.edu/~seander/bithacks.html
+
+namespace System.Numerics
+{
+ ///
+ /// Utility methods for intrinsic bit-twiddling operations.
+ /// The methods use hardware intrinsics when available on the underlying platform,
+ /// otherwise they use optimized software fallbacks.
+ ///
+ public static unsafe class BitOperations
+ {
+ // hack: should be public because of inline
+ public static readonly byte* TrailingZeroCountDeBruijn = GetArrayPointer(
+ new byte[]
+ {
+ 00,
+ 01,
+ 28,
+ 02,
+ 29,
+ 14,
+ 24,
+ 03,
+ 30,
+ 22,
+ 20,
+ 15,
+ 25,
+ 17,
+ 04,
+ 08,
+ 31,
+ 27,
+ 13,
+ 23,
+ 21,
+ 19,
+ 16,
+ 07,
+ 26,
+ 12,
+ 18,
+ 06,
+ 11,
+ 05,
+ 10,
+ 09,
+ }
+ );
+
+ // hack: should be public because of inline
+ public static readonly byte* Log2DeBruijn = GetArrayPointer(
+ new byte[]
+ {
+ 00,
+ 09,
+ 01,
+ 10,
+ 13,
+ 21,
+ 02,
+ 29,
+ 11,
+ 14,
+ 16,
+ 18,
+ 22,
+ 25,
+ 03,
+ 30,
+ 08,
+ 12,
+ 20,
+ 28,
+ 15,
+ 17,
+ 24,
+ 07,
+ 19,
+ 27,
+ 23,
+ 06,
+ 26,
+ 05,
+ 04,
+ 31,
+ }
+ );
+
+ ///
+ /// Returns the integer (floor) log of the specified value, base 2.
+ /// Note that by convention, input value 0 returns 0 since log(0) is undefined.
+ ///
+ /// The value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int Log2(uint value)
+ {
+ // The 0->0 contract is fulfilled by setting the LSB to 1.
+ // Log(1) is 0, and setting the LSB for values > 1 does not change the log2 result.
+ value |= 1;
+
+ // value lzcnt actual expected
+ // ..0001 31 31-31 0
+ // ..0010 30 31-30 1
+ // 0010.. 2 31-2 29
+ // 0100.. 1 31-1 30
+ // 1000.. 0 31-0 31
+
+ // Fallback contract is 0->0
+ // No AggressiveInlining due to large method size
+ // Has conventional contract 0->0 (Log(0) is undefined)
+
+ // Fill trailing zeros with ones, eg 00010010 becomes 00011111
+ value |= value >> 01;
+ value |= value >> 02;
+ value |= value >> 04;
+ value |= value >> 08;
+ value |= value >> 16;
+
+ // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
+ return Log2DeBruijn[
+ // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u
+ (int)((value * 0x07C4ACDDu) >> 27)
+ ];
+ }
+
+ ///
+ /// Returns the integer (floor) log of the specified value, base 2.
+ /// Note that by convention, input value 0 returns 0 since log(0) is undefined.
+ ///
+ /// The value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int Log2(ulong value)
+ {
+ value |= 1;
+
+ uint hi = (uint)(value >> 32);
+
+ if (hi == 0)
+ {
+ return Log2((uint)value);
+ }
+
+ return 32 + Log2(hi);
+ }
+
+ ///
+ /// Count the number of trailing zero bits in an integer value.
+ /// Similar in behavior to the x86 instruction TZCNT.
+ ///
+ /// The value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int TrailingZeroCount(int value) => TrailingZeroCount((uint)value);
+
+ ///
+ /// Count the number of trailing zero bits in an integer value.
+ /// Similar in behavior to the x86 instruction TZCNT.
+ ///
+ /// The value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int TrailingZeroCount(uint value)
+ {
+ // Unguarded fallback contract is 0->0, BSF contract is 0->undefined
+ if (value == 0)
+ {
+ return 32;
+ }
+
+ // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
+ return TrailingZeroCountDeBruijn[
+ // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_0111_1100_1011_0101_0011_0001u
+ (int)(((value & (uint)-(int)value) * 0x077CB531u) >> 27)
+ ]; // Multi-cast mitigates redundant conv.u8
+ }
+
+ ///
+ /// Count the number of trailing zero bits in a mask.
+ /// Similar in behavior to the x86 instruction TZCNT.
+ ///
+ /// The value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int TrailingZeroCount(long value) => TrailingZeroCount((ulong)value);
+
+ ///
+ /// Count the number of trailing zero bits in a mask.
+ /// Similar in behavior to the x86 instruction TZCNT.
+ ///
+ /// The value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int TrailingZeroCount(ulong value)
+ {
+ uint lo = (uint)value;
+
+ if (lo == 0)
+ {
+ return 32 + TrailingZeroCount((uint)(value >> 32));
+ }
+
+ return TrailingZeroCount(lo);
+ }
+
+ ///
+ /// Rotates the specified value left by the specified number of bits.
+ /// Similar in behavior to the x86 instruction ROL.
+ ///
+ /// The value to rotate.
+ /// The number of bits to rotate by.
+ /// Any value outside the range [0..31] is treated as congruent mod 32.
+ /// The rotated value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static uint RotateLeft(uint value, int offset) =>
+ (value << offset) | (value >> (32 - offset));
+
+ ///
+ /// Rotates the specified value left by the specified number of bits.
+ /// Similar in behavior to the x86 instruction ROL.
+ ///
+ /// The value to rotate.
+ /// The number of bits to rotate by.
+ /// Any value outside the range [0..63] is treated as congruent mod 64.
+ /// The rotated value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ulong RotateLeft(ulong value, int offset) =>
+ (value << offset) | (value >> (64 - offset));
+
+ ///
+ /// Rotates the specified value right by the specified number of bits.
+ /// Similar in behavior to the x86 instruction ROR.
+ ///
+ /// The value to rotate.
+ /// The number of bits to rotate by.
+ /// Any value outside the range [0..31] is treated as congruent mod 32.
+ /// The rotated value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static uint RotateRight(uint value, int offset) =>
+ (value >> offset) | (value << (32 - offset));
+
+ ///
+ /// Rotates the specified value right by the specified number of bits.
+ /// Similar in behavior to the x86 instruction ROR.
+ ///
+ /// The value to rotate.
+ /// The number of bits to rotate by.
+ /// Any value outside the range [0..63] is treated as congruent mod 64.
+ /// The rotated value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ulong RotateRight(ulong value, int offset) =>
+ (value >> offset) | (value << (64 - offset));
+
+ ///
+ /// Count the number of leading zero bits in a mask.
+ /// Similar in behavior to the x86 instruction LZCNT.
+ ///
+ /// The value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int LeadingZeroCount(uint value)
+ {
+ // Unguarded fallback contract is 0->31, BSR contract is 0->undefined
+ if (value == 0)
+ {
+ return 32;
+ }
+
+ // No AggressiveInlining due to large method size
+ // Has conventional contract 0->0 (Log(0) is undefined)
+
+ // Fill trailing zeros with ones, eg 00010010 becomes 00011111
+ value |= value >> 01;
+ value |= value >> 02;
+ value |= value >> 04;
+ value |= value >> 08;
+ value |= value >> 16;
+
+ // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
+ return 31
+ ^ Log2DeBruijn[
+ // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here
+ (int)((value * 0x07C4ACDDu) >> 27)
+ ];
+ }
+
+ ///
+ /// Count the number of leading zero bits in a mask.
+ /// Similar in behavior to the x86 instruction LZCNT.
+ ///
+ /// The value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int LeadingZeroCount(ulong value)
+ {
+ uint hi = (uint)(value >> 32);
+
+ if (hi == 0)
+ {
+ return 32 + LeadingZeroCount((uint)value);
+ }
+
+ return LeadingZeroCount(hi);
+ }
+ }
+}
+
+#endif
diff --git a/src/SharpCompress/Compressors/ZStandard/CompressionStream.cs b/src/SharpCompress/Compressors/ZStandard/CompressionStream.cs
new file mode 100644
index 000000000..92de03b34
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/CompressionStream.cs
@@ -0,0 +1,301 @@
+using System;
+using System.Buffers;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using SharpCompress.Compressors.ZStandard.Unsafe;
+
+namespace SharpCompress.Compressors.ZStandard;
+
+public class CompressionStream : Stream
+{
+ private readonly Stream innerStream;
+ private readonly byte[] outputBuffer;
+ private readonly bool preserveCompressor;
+ private readonly bool leaveOpen;
+ private Compressor? compressor;
+ private ZSTD_outBuffer_s output;
+
+ public CompressionStream(
+ Stream stream,
+ int level = Compressor.DefaultCompressionLevel,
+ int bufferSize = 0,
+ bool leaveOpen = true
+ )
+ : this(stream, new Compressor(level), bufferSize, false, leaveOpen) { }
+
+ public CompressionStream(
+ Stream stream,
+ Compressor compressor,
+ int bufferSize = 0,
+ bool preserveCompressor = true,
+ bool leaveOpen = true
+ )
+ {
+ if (stream == null)
+ throw new ArgumentNullException(nameof(stream));
+
+ if (!stream.CanWrite)
+ throw new ArgumentException("Stream is not writable", nameof(stream));
+
+ if (bufferSize < 0)
+ throw new ArgumentOutOfRangeException(nameof(bufferSize));
+
+ innerStream = stream;
+ this.compressor = compressor;
+ this.preserveCompressor = preserveCompressor;
+ this.leaveOpen = leaveOpen;
+
+ var outputBufferSize =
+ bufferSize > 0
+ ? bufferSize
+ : (int)Unsafe.Methods.ZSTD_CStreamOutSize().EnsureZstdSuccess();
+ outputBuffer = ArrayPool.Shared.Rent(outputBufferSize);
+ output = new ZSTD_outBuffer_s { pos = 0, size = (nuint)outputBufferSize };
+ }
+
+ public void SetParameter(ZSTD_cParameter parameter, int value)
+ {
+ EnsureNotDisposed();
+ compressor.NotNull().SetParameter(parameter, value);
+ }
+
+ public int GetParameter(ZSTD_cParameter parameter)
+ {
+ EnsureNotDisposed();
+ return compressor.NotNull().GetParameter(parameter);
+ }
+
+ public void LoadDictionary(byte[] dict)
+ {
+ EnsureNotDisposed();
+ compressor.NotNull().LoadDictionary(dict);
+ }
+
+ ~CompressionStream() => Dispose(false);
+
+#if !NETSTANDARD2_0 && !NETFRAMEWORK
+ public override async ValueTask DisposeAsync()
+#else
+ public async Task DisposeAsync()
+#endif
+ {
+ if (compressor == null)
+ return;
+
+ try
+ {
+ await FlushInternalAsync(ZSTD_EndDirective.ZSTD_e_end).ConfigureAwait(false);
+ }
+ finally
+ {
+ ReleaseUnmanagedResources();
+ GC.SuppressFinalize(this);
+ }
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (compressor == null)
+ return;
+
+ try
+ {
+ if (disposing)
+ FlushInternal(ZSTD_EndDirective.ZSTD_e_end);
+ }
+ finally
+ {
+ ReleaseUnmanagedResources();
+ }
+ }
+
+ private void ReleaseUnmanagedResources()
+ {
+ if (!preserveCompressor)
+ {
+ compressor.NotNull().Dispose();
+ }
+ compressor = null;
+
+ if (outputBuffer != null)
+ {
+ ArrayPool.Shared.Return(outputBuffer);
+ }
+
+ if (!leaveOpen)
+ {
+ innerStream.Dispose();
+ }
+ }
+
+ public override void Flush() => FlushInternal(ZSTD_EndDirective.ZSTD_e_flush);
+
+ public override async Task FlushAsync(CancellationToken cancellationToken) =>
+ await FlushInternalAsync(ZSTD_EndDirective.ZSTD_e_flush, cancellationToken)
+ .ConfigureAwait(false);
+
+ private void FlushInternal(ZSTD_EndDirective directive) => WriteInternal(null, directive);
+
+ private async Task FlushInternalAsync(
+ ZSTD_EndDirective directive,
+ CancellationToken cancellationToken = default
+ ) => await WriteInternalAsync(null, directive, cancellationToken).ConfigureAwait(false);
+
+ public override void Write(byte[] buffer, int offset, int count) =>
+ Write(new ReadOnlySpan(buffer, offset, count));
+
+#if !NETSTANDARD2_0 && !NETFRAMEWORK
+ public override void Write(ReadOnlySpan buffer) =>
+ WriteInternal(buffer, ZSTD_EndDirective.ZSTD_e_continue);
+#else
+ public void Write(ReadOnlySpan buffer) =>
+ WriteInternal(buffer, ZSTD_EndDirective.ZSTD_e_continue);
+#endif
+
+ private void WriteInternal(ReadOnlySpan buffer, ZSTD_EndDirective directive)
+ {
+ EnsureNotDisposed();
+
+ var input = new ZSTD_inBuffer_s
+ {
+ pos = 0,
+ size = buffer != null ? (nuint)buffer.Length : 0,
+ };
+ nuint remaining;
+ do
+ {
+ output.pos = 0;
+ remaining = CompressStream(ref input, buffer, directive);
+
+ var written = (int)output.pos;
+ if (written > 0)
+ innerStream.Write(outputBuffer, 0, written);
+ } while (
+ directive == ZSTD_EndDirective.ZSTD_e_continue ? input.pos < input.size : remaining > 0
+ );
+ }
+
+#if !NETSTANDARD2_0 && !NETFRAMEWORK
+ private async ValueTask WriteInternalAsync(
+ ReadOnlyMemory? buffer,
+ ZSTD_EndDirective directive,
+ CancellationToken cancellationToken = default
+ )
+#else
+ private async Task WriteInternalAsync(
+ ReadOnlyMemory? buffer,
+ ZSTD_EndDirective directive,
+ CancellationToken cancellationToken = default
+ )
+#endif
+
+ {
+ EnsureNotDisposed();
+
+ var input = new ZSTD_inBuffer_s
+ {
+ pos = 0,
+ size = buffer.HasValue ? (nuint)buffer.Value.Length : 0,
+ };
+ nuint remaining;
+ do
+ {
+ output.pos = 0;
+ remaining = CompressStream(
+ ref input,
+ buffer.HasValue ? buffer.Value.Span : null,
+ directive
+ );
+
+ var written = (int)output.pos;
+ if (written > 0)
+ await innerStream
+ .WriteAsync(outputBuffer, 0, written, cancellationToken)
+ .ConfigureAwait(false);
+ } while (
+ directive == ZSTD_EndDirective.ZSTD_e_continue ? input.pos < input.size : remaining > 0
+ );
+ }
+
+#if !NETSTANDARD2_0 && !NETFRAMEWORK
+
+ public override Task WriteAsync(
+ byte[] buffer,
+ int offset,
+ int count,
+ CancellationToken cancellationToken
+ ) => WriteAsync(new ReadOnlyMemory(buffer, offset, count), cancellationToken).AsTask();
+
+ public override async ValueTask WriteAsync(
+ ReadOnlyMemory buffer,
+ CancellationToken cancellationToken = default
+ ) =>
+ await WriteInternalAsync(buffer, ZSTD_EndDirective.ZSTD_e_continue, cancellationToken)
+ .ConfigureAwait(false);
+#else
+
+ public override Task WriteAsync(
+ byte[] buffer,
+ int offset,
+ int count,
+ CancellationToken cancellationToken
+ ) => WriteAsync(new ReadOnlyMemory(buffer, offset, count), cancellationToken);
+
+ public async Task WriteAsync(
+ ReadOnlyMemory buffer,
+ CancellationToken cancellationToken = default
+ ) =>
+ await WriteInternalAsync(buffer, ZSTD_EndDirective.ZSTD_e_continue, cancellationToken)
+ .ConfigureAwait(false);
+#endif
+
+ internal unsafe nuint CompressStream(
+ ref ZSTD_inBuffer_s input,
+ ReadOnlySpan inputBuffer,
+ ZSTD_EndDirective directive
+ )
+ {
+ fixed (byte* inputBufferPtr = inputBuffer)
+ fixed (byte* outputBufferPtr = outputBuffer)
+ {
+ input.src = inputBufferPtr;
+ output.dst = outputBufferPtr;
+ return compressor
+ .NotNull()
+ .CompressStream(ref input, ref output, directive)
+ .EnsureZstdSuccess();
+ }
+ }
+
+ public override bool CanRead => false;
+ public override bool CanSeek => false;
+ public override bool CanWrite => true;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override int Read(byte[] buffer, int offset, int count) =>
+ throw new NotSupportedException();
+
+ private void EnsureNotDisposed()
+ {
+ if (compressor == null)
+ throw new ObjectDisposedException(nameof(CompressionStream));
+ }
+
+ public void SetPledgedSrcSize(ulong pledgedSrcSize)
+ {
+ EnsureNotDisposed();
+ compressor.NotNull().SetPledgedSrcSize(pledgedSrcSize);
+ }
+}
diff --git a/src/SharpCompress/Compressors/ZStandard/Compressor.cs b/src/SharpCompress/Compressors/ZStandard/Compressor.cs
new file mode 100644
index 000000000..668606016
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/Compressor.cs
@@ -0,0 +1,204 @@
+using System;
+using SharpCompress.Compressors.ZStandard.Unsafe;
+
+namespace SharpCompress.Compressors.ZStandard;
+
+public unsafe class Compressor : IDisposable
+{
+ ///
+ /// Minimum negative compression level allowed
+ ///
+ public static int MinCompressionLevel => Unsafe.Methods.ZSTD_minCLevel();
+
+ ///
+ /// Maximum compression level available
+ ///
+ public static int MaxCompressionLevel => Unsafe.Methods.ZSTD_maxCLevel();
+
+ ///
+ /// Default compression level
+ ///
+ ///
+ public const int DefaultCompressionLevel = 3;
+
+ private int level = DefaultCompressionLevel;
+
+ private readonly SafeCctxHandle handle;
+
+ public int Level
+ {
+ get => level;
+ set
+ {
+ if (level != value)
+ {
+ level = value;
+ SetParameter(ZSTD_cParameter.ZSTD_c_compressionLevel, value);
+ }
+ }
+ }
+
+ public void SetParameter(ZSTD_cParameter parameter, int value)
+ {
+ using var cctx = handle.Acquire();
+ Unsafe.Methods.ZSTD_CCtx_setParameter(cctx, parameter, value).EnsureZstdSuccess();
+ }
+
+ public int GetParameter(ZSTD_cParameter parameter)
+ {
+ using var cctx = handle.Acquire();
+ int value;
+ Unsafe.Methods.ZSTD_CCtx_getParameter(cctx, parameter, &value).EnsureZstdSuccess();
+ return value;
+ }
+
+ public void LoadDictionary(byte[] dict)
+ {
+ var dictReadOnlySpan = new ReadOnlySpan(dict);
+ LoadDictionary(dictReadOnlySpan);
+ }
+
+ public void LoadDictionary(ReadOnlySpan dict)
+ {
+ using var cctx = handle.Acquire();
+ fixed (byte* dictPtr = dict)
+ Unsafe
+ .Methods.ZSTD_CCtx_loadDictionary(cctx, dictPtr, (nuint)dict.Length)
+ .EnsureZstdSuccess();
+ }
+
+ public Compressor(int level = DefaultCompressionLevel)
+ {
+ handle = SafeCctxHandle.Create();
+ Level = level;
+ }
+
+ public static int GetCompressBound(int length) =>
+ (int)Unsafe.Methods.ZSTD_compressBound((nuint)length);
+
+ public static ulong GetCompressBoundLong(ulong length) =>
+ Unsafe.Methods.ZSTD_compressBound((nuint)length);
+
+ public Span Wrap(ReadOnlySpan src)
+ {
+ var dest = new byte[GetCompressBound(src.Length)];
+ var length = Wrap(src, dest);
+ return new Span(dest, 0, length);
+ }
+
+ public int Wrap(byte[] src, byte[] dest, int offset) =>
+ Wrap(src, new Span(dest, offset, dest.Length - offset));
+
+ public int Wrap(ReadOnlySpan src, Span dest)
+ {
+ fixed (byte* srcPtr = src)
+ fixed (byte* destPtr = dest)
+ {
+ using var cctx = handle.Acquire();
+ return (int)
+ Unsafe
+ .Methods.ZSTD_compress2(
+ cctx,
+ destPtr,
+ (nuint)dest.Length,
+ srcPtr,
+ (nuint)src.Length
+ )
+ .EnsureZstdSuccess();
+ }
+ }
+
+ public int Wrap(ArraySegment src, ArraySegment dest) =>
+ Wrap((ReadOnlySpan)src, dest);
+
+ public int Wrap(
+ byte[] src,
+ int srcOffset,
+ int srcLength,
+ byte[] dst,
+ int dstOffset,
+ int dstLength
+ ) =>
+ Wrap(
+ new ReadOnlySpan(src, srcOffset, srcLength),
+ new Span(dst, dstOffset, dstLength)
+ );
+
+ public bool TryWrap(byte[] src, byte[] dest, int offset, out int written) =>
+ TryWrap(src, new Span(dest, offset, dest.Length - offset), out written);
+
+ public bool TryWrap(ReadOnlySpan src, Span dest, out int written)
+ {
+ fixed (byte* srcPtr = src)
+ fixed (byte* destPtr = dest)
+ {
+ nuint returnValue;
+ using (var cctx = handle.Acquire())
+ {
+ returnValue = Unsafe.Methods.ZSTD_compress2(
+ cctx,
+ destPtr,
+ (nuint)dest.Length,
+ srcPtr,
+ (nuint)src.Length
+ );
+ }
+
+ if (returnValue == unchecked(0 - (nuint)ZSTD_ErrorCode.ZSTD_error_dstSize_tooSmall))
+ {
+ written = default;
+ return false;
+ }
+
+ returnValue.EnsureZstdSuccess();
+ written = (int)returnValue;
+ return true;
+ }
+ }
+
+ public bool TryWrap(ArraySegment src, ArraySegment dest, out int written) =>
+ TryWrap((ReadOnlySpan)src, dest, out written);
+
+ public bool TryWrap(
+ byte[] src,
+ int srcOffset,
+ int srcLength,
+ byte[] dst,
+ int dstOffset,
+ int dstLength,
+ out int written
+ ) =>
+ TryWrap(
+ new ReadOnlySpan(src, srcOffset, srcLength),
+ new Span(dst, dstOffset, dstLength),
+ out written
+ );
+
+ public void Dispose()
+ {
+ handle.Dispose();
+ GC.SuppressFinalize(this);
+ }
+
+ internal nuint CompressStream(
+ ref ZSTD_inBuffer_s input,
+ ref ZSTD_outBuffer_s output,
+ ZSTD_EndDirective directive
+ )
+ {
+ fixed (ZSTD_inBuffer_s* inputPtr = &input)
+ fixed (ZSTD_outBuffer_s* outputPtr = &output)
+ {
+ using var cctx = handle.Acquire();
+ return Unsafe
+ .Methods.ZSTD_compressStream2(cctx, outputPtr, inputPtr, directive)
+ .EnsureZstdSuccess();
+ }
+ }
+
+ public void SetPledgedSrcSize(ulong pledgedSrcSize)
+ {
+ using var cctx = handle.Acquire();
+ Unsafe.Methods.ZSTD_CCtx_setPledgedSrcSize(cctx, pledgedSrcSize).EnsureZstdSuccess();
+ }
+}
diff --git a/src/SharpCompress/Compressors/ZStandard/Constants.cs b/src/SharpCompress/Compressors/ZStandard/Constants.cs
new file mode 100644
index 000000000..cce84fc09
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/Constants.cs
@@ -0,0 +1,8 @@
+namespace SharpCompress.Compressors.ZStandard;
+
+internal class Constants
+{
+ //NOTE: https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element#remarks
+ //NOTE: https://github.com/dotnet/runtime/blob/v5.0.0-rtm.20519.4/src/libraries/System.Private.CoreLib/src/System/Array.cs#L27
+ public const ulong MaxByteArrayLength = 0x7FFFFFC7;
+}
diff --git a/src/SharpCompress/Compressors/ZStandard/DecompressionStream.cs b/src/SharpCompress/Compressors/ZStandard/DecompressionStream.cs
new file mode 100644
index 000000000..9864a8055
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/DecompressionStream.cs
@@ -0,0 +1,293 @@
+using System;
+using System.Buffers;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using SharpCompress.Compressors.ZStandard.Unsafe;
+
+namespace SharpCompress.Compressors.ZStandard;
+
+public class DecompressionStream : Stream
+{
+ private readonly Stream innerStream;
+ private readonly byte[] inputBuffer;
+ private readonly int inputBufferSize;
+ private readonly bool preserveDecompressor;
+ private readonly bool leaveOpen;
+ private readonly bool checkEndOfStream;
+ private Decompressor? decompressor;
+ private ZSTD_inBuffer_s input;
+ private nuint lastDecompressResult = 0;
+ private bool contextDrained = true;
+
+ public DecompressionStream(
+ Stream stream,
+ int bufferSize = 0,
+ bool checkEndOfStream = true,
+ bool leaveOpen = true
+ )
+ : this(stream, new Decompressor(), bufferSize, checkEndOfStream, false, leaveOpen) { }
+
+ public DecompressionStream(
+ Stream stream,
+ Decompressor decompressor,
+ int bufferSize = 0,
+ bool checkEndOfStream = true,
+ bool preserveDecompressor = true,
+ bool leaveOpen = true
+ )
+ {
+ if (stream == null)
+ throw new ArgumentNullException(nameof(stream));
+
+ if (!stream.CanRead)
+ throw new ArgumentException("Stream is not readable", nameof(stream));
+
+ if (bufferSize < 0)
+ throw new ArgumentOutOfRangeException(nameof(bufferSize));
+
+ innerStream = stream;
+ this.decompressor = decompressor;
+ this.preserveDecompressor = preserveDecompressor;
+ this.leaveOpen = leaveOpen;
+ this.checkEndOfStream = checkEndOfStream;
+
+ inputBufferSize =
+ bufferSize > 0
+ ? bufferSize
+ : (int)Unsafe.Methods.ZSTD_DStreamInSize().EnsureZstdSuccess();
+ inputBuffer = ArrayPool.Shared.Rent(inputBufferSize);
+ input = new ZSTD_inBuffer_s { pos = (nuint)inputBufferSize, size = (nuint)inputBufferSize };
+ }
+
+ public void SetParameter(ZSTD_dParameter parameter, int value)
+ {
+ EnsureNotDisposed();
+ decompressor.NotNull().SetParameter(parameter, value);
+ }
+
+ public int GetParameter(ZSTD_dParameter parameter)
+ {
+ EnsureNotDisposed();
+ return decompressor.NotNull().GetParameter(parameter);
+ }
+
+ public void LoadDictionary(byte[] dict)
+ {
+ EnsureNotDisposed();
+ decompressor.NotNull().LoadDictionary(dict);
+ }
+
+ ~DecompressionStream() => Dispose(false);
+
+ protected override void Dispose(bool disposing)
+ {
+ if (decompressor == null)
+ return;
+
+ if (!preserveDecompressor)
+ {
+ decompressor.Dispose();
+ }
+ decompressor = null;
+
+ if (inputBuffer != null)
+ {
+ ArrayPool.Shared.Return(inputBuffer);
+ }
+
+ if (!leaveOpen)
+ {
+ innerStream.Dispose();
+ }
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) =>
+ Read(new Span(buffer, offset, count));
+
+#if !NETSTANDARD2_0 && !NETFRAMEWORK
+ public override int Read(Span buffer)
+#else
+ public int Read(Span buffer)
+#endif
+ {
+ EnsureNotDisposed();
+
+ // Guard against infinite loop (output.pos would never become non-zero)
+ if (buffer.Length == 0)
+ {
+ return 0;
+ }
+
+ var output = new ZSTD_outBuffer_s { pos = 0, size = (nuint)buffer.Length };
+ while (true)
+ {
+ // If there is still input available, or there might be data buffered in the decompressor context, flush that out
+ while (input.pos < input.size || !contextDrained)
+ {
+ nuint oldInputPos = input.pos;
+ nuint result = DecompressStream(ref output, buffer);
+ if (output.pos > 0 || oldInputPos != input.pos)
+ {
+ // Keep result from last decompress call that made some progress, so we known if we're at end of frame
+ lastDecompressResult = result;
+ }
+ // If decompression filled the output buffer, there might still be data buffered in the decompressor context
+ contextDrained = output.pos < output.size;
+ // If we have data to return, return it immediately, so we won't stall on Read
+ if (output.pos > 0)
+ {
+ return (int)output.pos;
+ }
+ }
+
+ // Otherwise, read some more input
+ int bytesRead;
+ if ((bytesRead = innerStream.Read(inputBuffer, 0, inputBufferSize)) == 0)
+ {
+ if (checkEndOfStream && lastDecompressResult != 0)
+ {
+ throw new EndOfStreamException("Premature end of stream");
+ }
+
+ return 0;
+ }
+
+ input.size = (nuint)bytesRead;
+ input.pos = 0;
+ }
+ }
+
+#if !NETSTANDARD2_0 && !NETFRAMEWORK
+ public override Task ReadAsync(
+ byte[] buffer,
+ int offset,
+ int count,
+ CancellationToken cancellationToken
+ ) => ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask();
+
+ public override async ValueTask ReadAsync(
+ Memory buffer,
+ CancellationToken cancellationToken = default
+ )
+#else
+
+ public override Task ReadAsync(
+ byte[] buffer,
+ int offset,
+ int count,
+ CancellationToken cancellationToken
+ ) => ReadAsync(new Memory(buffer, offset, count), cancellationToken);
+
+ public async Task ReadAsync(
+ Memory buffer,
+ CancellationToken cancellationToken = default
+ )
+#endif
+ {
+ EnsureNotDisposed();
+
+ // Guard against infinite loop (output.pos would never become non-zero)
+ if (buffer.Length == 0)
+ {
+ return 0;
+ }
+
+ var output = new ZSTD_outBuffer_s { pos = 0, size = (nuint)buffer.Length };
+ while (true)
+ {
+ // If there is still input available, or there might be data buffered in the decompressor context, flush that out
+ while (input.pos < input.size || !contextDrained)
+ {
+ nuint oldInputPos = input.pos;
+ nuint result = DecompressStream(ref output, buffer.Span);
+ if (output.pos > 0 || oldInputPos != input.pos)
+ {
+ // Keep result from last decompress call that made some progress, so we known if we're at end of frame
+ lastDecompressResult = result;
+ }
+ // If decompression filled the output buffer, there might still be data buffered in the decompressor context
+ contextDrained = output.pos < output.size;
+ // If we have data to return, return it immediately, so we won't stall on Read
+ if (output.pos > 0)
+ {
+ return (int)output.pos;
+ }
+ }
+
+ // Otherwise, read some more input
+ int bytesRead;
+ if (
+ (
+ bytesRead = await innerStream
+ .ReadAsync(inputBuffer, 0, inputBufferSize, cancellationToken)
+ .ConfigureAwait(false)
+ ) == 0
+ )
+ {
+ if (checkEndOfStream && lastDecompressResult != 0)
+ {
+ throw new EndOfStreamException("Premature end of stream");
+ }
+
+ return 0;
+ }
+
+ input.size = (nuint)bytesRead;
+ input.pos = 0;
+ }
+ }
+
+ private unsafe nuint DecompressStream(ref ZSTD_outBuffer_s output, Span outputBuffer)
+ {
+ fixed (byte* inputBufferPtr = inputBuffer)
+ fixed (byte* outputBufferPtr = outputBuffer)
+ {
+ input.src = inputBufferPtr;
+ output.dst = outputBufferPtr;
+ return decompressor.NotNull().DecompressStream(ref input, ref output);
+ }
+ }
+
+ public override bool CanRead => true;
+ public override bool CanSeek => false;
+ public override bool CanWrite => false;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ public override void Flush() => throw new NotSupportedException();
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) =>
+ throw new NotSupportedException();
+
+ private void EnsureNotDisposed()
+ {
+ if (decompressor == null)
+ throw new ObjectDisposedException(nameof(DecompressionStream));
+ }
+
+#if NETSTANDARD2_0 || NETFRAMEWORK
+ public virtual Task DisposeAsync()
+ {
+ try
+ {
+ Dispose();
+ return Task.CompletedTask;
+ }
+ catch (Exception exc)
+ {
+ return Task.FromException(exc);
+ }
+ }
+#endif
+}
diff --git a/src/SharpCompress/Compressors/ZStandard/Decompressor.cs b/src/SharpCompress/Compressors/ZStandard/Decompressor.cs
new file mode 100644
index 000000000..8a63c4d9d
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/Decompressor.cs
@@ -0,0 +1,176 @@
+using System;
+using SharpCompress.Compressors.ZStandard.Unsafe;
+
+namespace SharpCompress.Compressors.ZStandard;
+
+public unsafe class Decompressor : IDisposable
+{
+ private readonly SafeDctxHandle handle;
+
+ public Decompressor()
+ {
+ handle = SafeDctxHandle.Create();
+ }
+
+ public void SetParameter(ZSTD_dParameter parameter, int value)
+ {
+ using var dctx = handle.Acquire();
+ Unsafe.Methods.ZSTD_DCtx_setParameter(dctx, parameter, value).EnsureZstdSuccess();
+ }
+
+ public int GetParameter(ZSTD_dParameter parameter)
+ {
+ using var dctx = handle.Acquire();
+ int value;
+ Unsafe.Methods.ZSTD_DCtx_getParameter(dctx, parameter, &value).EnsureZstdSuccess();
+ return value;
+ }
+
+ public void LoadDictionary(byte[] dict)
+ {
+ var dictReadOnlySpan = new ReadOnlySpan(dict);
+ this.LoadDictionary(dictReadOnlySpan);
+ }
+
+ public void LoadDictionary(ReadOnlySpan dict)
+ {
+ using var dctx = handle.Acquire();
+ fixed (byte* dictPtr = dict)
+ Unsafe
+ .Methods.ZSTD_DCtx_loadDictionary(dctx, dictPtr, (nuint)dict.Length)
+ .EnsureZstdSuccess();
+ }
+
+ public static ulong GetDecompressedSize(ReadOnlySpan src)
+ {
+ fixed (byte* srcPtr = src)
+ return Unsafe
+ .Methods.ZSTD_decompressBound(srcPtr, (nuint)src.Length)
+ .EnsureContentSizeOk();
+ }
+
+ public static ulong GetDecompressedSize(ArraySegment src) =>
+ GetDecompressedSize((ReadOnlySpan)src);
+
+ public static ulong GetDecompressedSize(byte[] src, int srcOffset, int srcLength) =>
+ GetDecompressedSize(new ReadOnlySpan(src, srcOffset, srcLength));
+
+ public Span Unwrap(ReadOnlySpan src, int maxDecompressedSize = int.MaxValue)
+ {
+ var expectedDstSize = GetDecompressedSize(src);
+ if (expectedDstSize > (ulong)maxDecompressedSize)
+ throw new ZstdException(
+ ZSTD_ErrorCode.ZSTD_error_dstSize_tooSmall,
+ $"Decompressed content size {expectedDstSize} is greater than {nameof(maxDecompressedSize)} {maxDecompressedSize}"
+ );
+ if (expectedDstSize > Constants.MaxByteArrayLength)
+ throw new ZstdException(
+ ZSTD_ErrorCode.ZSTD_error_dstSize_tooSmall,
+ $"Decompressed content size {expectedDstSize} is greater than max possible byte array size {Constants.MaxByteArrayLength}"
+ );
+
+ var dest = new byte[expectedDstSize];
+ var length = Unwrap(src, dest);
+ return new Span(dest, 0, length);
+ }
+
+ public int Unwrap(byte[] src, byte[] dest, int offset) =>
+ Unwrap(src, new Span(dest, offset, dest.Length - offset));
+
+ public int Unwrap(ReadOnlySpan src, Span dest)
+ {
+ fixed (byte* srcPtr = src)
+ fixed (byte* destPtr = dest)
+ {
+ using var dctx = handle.Acquire();
+ return (int)
+ Unsafe
+ .Methods.ZSTD_decompressDCtx(
+ dctx,
+ destPtr,
+ (nuint)dest.Length,
+ srcPtr,
+ (nuint)src.Length
+ )
+ .EnsureZstdSuccess();
+ }
+ }
+
+ public int Unwrap(
+ byte[] src,
+ int srcOffset,
+ int srcLength,
+ byte[] dst,
+ int dstOffset,
+ int dstLength
+ ) =>
+ Unwrap(
+ new ReadOnlySpan(src, srcOffset, srcLength),
+ new Span(dst, dstOffset, dstLength)
+ );
+
+ public bool TryUnwrap(byte[] src, byte[] dest, int offset, out int written) =>
+ TryUnwrap(src, new Span(dest, offset, dest.Length - offset), out written);
+
+ public bool TryUnwrap(ReadOnlySpan src, Span dest, out int written)
+ {
+ fixed (byte* srcPtr = src)
+ fixed (byte* destPtr = dest)
+ {
+ nuint returnValue;
+ using (var dctx = handle.Acquire())
+ {
+ returnValue = Unsafe.Methods.ZSTD_decompressDCtx(
+ dctx,
+ destPtr,
+ (nuint)dest.Length,
+ srcPtr,
+ (nuint)src.Length
+ );
+ }
+
+ if (returnValue == unchecked(0 - (nuint)ZSTD_ErrorCode.ZSTD_error_dstSize_tooSmall))
+ {
+ written = default;
+ return false;
+ }
+
+ returnValue.EnsureZstdSuccess();
+ written = (int)returnValue;
+ return true;
+ }
+ }
+
+ public bool TryUnwrap(
+ byte[] src,
+ int srcOffset,
+ int srcLength,
+ byte[] dst,
+ int dstOffset,
+ int dstLength,
+ out int written
+ ) =>
+ TryUnwrap(
+ new ReadOnlySpan(src, srcOffset, srcLength),
+ new Span(dst, dstOffset, dstLength),
+ out written
+ );
+
+ public void Dispose()
+ {
+ handle.Dispose();
+ GC.SuppressFinalize(this);
+ }
+
+ internal nuint DecompressStream(ref ZSTD_inBuffer_s input, ref ZSTD_outBuffer_s output)
+ {
+ fixed (ZSTD_inBuffer_s* inputPtr = &input)
+ fixed (ZSTD_outBuffer_s* outputPtr = &output)
+ {
+ using var dctx = handle.Acquire();
+ return Unsafe
+ .Methods.ZSTD_decompressStream(dctx, outputPtr, inputPtr)
+ .EnsureZstdSuccess();
+ }
+ }
+}
diff --git a/src/SharpCompress/Compressors/ZStandard/JobThreadPool.cs b/src/SharpCompress/Compressors/ZStandard/JobThreadPool.cs
new file mode 100644
index 000000000..e783940dc
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/JobThreadPool.cs
@@ -0,0 +1,141 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace SharpCompress.Compressors.ZStandard;
+
+internal unsafe class JobThreadPool : IDisposable
+{
+ private int numThreads;
+ private readonly List threads;
+ private readonly BlockingCollection queue;
+
+ private struct Job
+ {
+ public void* function;
+ public void* opaque;
+ }
+
+ private class JobThread
+ {
+ private Thread Thread { get; }
+ public CancellationTokenSource CancellationTokenSource { get; }
+
+ public JobThread(Thread thread)
+ {
+ CancellationTokenSource = new CancellationTokenSource();
+ Thread = thread;
+ }
+
+ public void Start()
+ {
+ Thread.Start(this);
+ }
+
+ public void Cancel()
+ {
+ CancellationTokenSource.Cancel();
+ }
+
+ public void Join()
+ {
+ Thread.Join();
+ }
+ }
+
+ private void Worker(object? obj)
+ {
+ if (obj is not JobThread poolThread)
+ return;
+
+ var cancellationToken = poolThread.CancellationTokenSource.Token;
+ while (!queue.IsCompleted && !cancellationToken.IsCancellationRequested)
+ {
+ try
+ {
+ if (queue.TryTake(out var job, -1, cancellationToken))
+ ((delegate* managed)job.function)(job.opaque);
+ }
+ catch (InvalidOperationException) { }
+ catch (OperationCanceledException) { }
+ }
+ }
+
+ public JobThreadPool(int num, int queueSize)
+ {
+ numThreads = num;
+ queue = new BlockingCollection(queueSize + 1);
+ threads = new List(num);
+ for (var i = 0; i < numThreads; i++)
+ CreateThread();
+ }
+
+ private void CreateThread()
+ {
+ var poolThread = new JobThread(new Thread(Worker));
+ threads.Add(poolThread);
+ poolThread.Start();
+ }
+
+ public void Resize(int num)
+ {
+ lock (threads)
+ {
+ if (num < numThreads)
+ {
+ for (var i = numThreads - 1; i >= num; i--)
+ {
+ threads[i].Cancel();
+ threads.RemoveAt(i);
+ }
+ }
+ else
+ {
+ for (var i = numThreads; i < num; i++)
+ CreateThread();
+ }
+ }
+
+ numThreads = num;
+ }
+
+ public void Add(void* function, void* opaque)
+ {
+ queue.Add(new Job { function = function, opaque = opaque });
+ }
+
+ public bool TryAdd(void* function, void* opaque)
+ {
+ return queue.TryAdd(new Job { function = function, opaque = opaque });
+ }
+
+ public void Join(bool cancel = true)
+ {
+ queue.CompleteAdding();
+ List jobThreads;
+ lock (threads)
+ jobThreads = new List(threads);
+
+ if (cancel)
+ {
+ foreach (var thread in jobThreads)
+ thread.Cancel();
+ }
+
+ foreach (var thread in jobThreads)
+ thread.Join();
+ }
+
+ public void Dispose()
+ {
+ queue.Dispose();
+ }
+
+ public int Size()
+ {
+ // todo not implemented
+ // https://github.com/dotnet/runtime/issues/24200
+ return 0;
+ }
+}
diff --git a/src/SharpCompress/Compressors/ZStandard/SafeHandles.cs b/src/SharpCompress/Compressors/ZStandard/SafeHandles.cs
new file mode 100644
index 000000000..3b49bdcec
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/SafeHandles.cs
@@ -0,0 +1,163 @@
+using System;
+using System.Runtime.InteropServices;
+using SharpCompress.Compressors.ZStandard.Unsafe;
+
+namespace SharpCompress.Compressors.ZStandard;
+
+///
+/// Provides the base class for ZstdSharp implementations.
+///
+///
+/// Even though ZstdSharp is a managed library, its internals are using unmanaged
+/// memory and we are using safe handles in the library's high-level API to ensure
+/// proper disposal of unmanaged resources and increase safety.
+///
+///
+///
+internal abstract unsafe class SafeZstdHandle : SafeHandle
+{
+ ///
+ /// Parameterless constructor is hidden. Use the static Create factory
+ /// method to create a new safe handle instance.
+ ///
+ protected SafeZstdHandle()
+ : base(IntPtr.Zero, true) { }
+
+ public sealed override bool IsInvalid => handle == IntPtr.Zero;
+}
+
+///
+/// Safely wraps an unmanaged Zstd compression context.
+///
+internal sealed unsafe class SafeCctxHandle : SafeZstdHandle
+{
+ ///
+ private SafeCctxHandle() { }
+
+ ///
+ /// Creates a new instance of .
+ ///
+ ///
+ /// Creation failed.
+ public static SafeCctxHandle Create()
+ {
+ var safeHandle = new SafeCctxHandle();
+ bool success = false;
+ try
+ {
+ var cctx = Unsafe.Methods.ZSTD_createCCtx();
+ if (cctx == null)
+ throw new ZstdException(ZSTD_ErrorCode.ZSTD_error_GENERIC, "Failed to create cctx");
+ safeHandle.SetHandle((IntPtr)cctx);
+ success = true;
+ }
+ finally
+ {
+ if (!success)
+ {
+ safeHandle.SetHandleAsInvalid();
+ }
+ }
+ return safeHandle;
+ }
+
+ ///
+ /// Acquires a reference to the safe handle.
+ ///
+ ///
+ /// A instance that can be implicitly converted to a pointer
+ /// to .
+ ///
+ public SafeHandleHolder Acquire() => new(this);
+
+ protected override bool ReleaseHandle()
+ {
+ return Unsafe.Methods.ZSTD_freeCCtx((ZSTD_CCtx_s*)handle) == 0;
+ }
+}
+
+///
+/// Safely wraps an unmanaged Zstd compression context.
+///
+internal sealed unsafe class SafeDctxHandle : SafeZstdHandle
+{
+ ///
+ private SafeDctxHandle() { }
+
+ ///
+ /// Creates a new instance of .
+ ///
+ ///
+ /// Creation failed.
+ public static SafeDctxHandle Create()
+ {
+ var safeHandle = new SafeDctxHandle();
+ bool success = false;
+ try
+ {
+ var dctx = Unsafe.Methods.ZSTD_createDCtx();
+ if (dctx == null)
+ throw new ZstdException(ZSTD_ErrorCode.ZSTD_error_GENERIC, "Failed to create dctx");
+ safeHandle.SetHandle((IntPtr)dctx);
+ success = true;
+ }
+ finally
+ {
+ if (!success)
+ {
+ safeHandle.SetHandleAsInvalid();
+ }
+ }
+ return safeHandle;
+ }
+
+ ///
+ /// Acquires a reference to the safe handle.
+ ///
+ ///
+ /// A instance that can be implicitly converted to a pointer
+ /// to .
+ ///
+ public SafeHandleHolder Acquire() => new(this);
+
+ protected override bool ReleaseHandle()
+ {
+ return Unsafe.Methods.ZSTD_freeDCtx((ZSTD_DCtx_s*)handle) == 0;
+ }
+}
+
+///
+/// Provides a convenient interface to safely acquire pointers of a specific type
+/// from a , by utilizing blocks.
+///
+/// The type of pointers to return.
+///
+/// Safe handle holders can be d to decrement the safe handle's
+/// reference count, and can be implicitly converted to pointers to .
+///
+internal unsafe ref struct SafeHandleHolder
+ where T : unmanaged
+{
+ private readonly SafeHandle _handle;
+
+ private bool _refAdded;
+
+ public SafeHandleHolder(SafeHandle safeHandle)
+ {
+ _handle = safeHandle;
+ _refAdded = false;
+ safeHandle.DangerousAddRef(ref _refAdded);
+ }
+
+ public static implicit operator T*(SafeHandleHolder holder) =>
+ (T*)holder._handle.DangerousGetHandle();
+
+ public void Dispose()
+ {
+ if (_refAdded)
+ {
+ _handle.DangerousRelease();
+ _refAdded = false;
+ }
+ }
+}
diff --git a/src/SharpCompress/Compressors/ZStandard/SynchronizationWrapper.cs b/src/SharpCompress/Compressors/ZStandard/SynchronizationWrapper.cs
new file mode 100644
index 000000000..406cacd43
--- /dev/null
+++ b/src/SharpCompress/Compressors/ZStandard/SynchronizationWrapper.cs
@@ -0,0 +1,22 @@
+using System.Threading;
+
+namespace SharpCompress.Compressors.ZStandard;
+
+internal static unsafe class SynchronizationWrapper
+{
+ private static object UnwrapObject(void** obj) => UnmanagedObject.Unwrap