Merge branch 'master' into fixes-zstd

This commit is contained in:
Adam Hathcock
2023-06-12 09:45:35 +01:00
committed by GitHub
118 changed files with 796 additions and 243 deletions

View File

@@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"csharpier": {
"version": "0.21.0",
"version": "0.23.0",
"commands": [
"dotnet-csharpier"
]

View File

@@ -18,6 +18,13 @@ jobs:
- uses: actions/setup-dotnet@v3
with:
dotnet-version: 7.0.x
- name: NuGet Caching
uses: actions/cache@v3
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('packages.lock.json', '*/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget-
- run: dotnet run --project build/build.csproj
- uses: actions/upload-artifact@v3
with:

View File

@@ -5,7 +5,7 @@ SharpCompress is a compression library in pure C# for .NET Standard 2.0, 2.1, .N
The major feature is support for non-seekable streams so large files can be processed on the fly (i.e. download stream).
GitHub Actions Build -
[![GitHubActions](https://github.com/adamhathcock/sharpcompress/workflows/SharpCompress/badge.svg)](https://circleci.com/gh/adamhathcock/sharpcompress)
[![SharpCompress](https://github.com/adamhathcock/sharpcompress/actions/workflows/dotnetcore.yml/badge.svg)](https://github.com/adamhathcock/sharpcompress/actions/workflows/dotnetcore.yml)
## Need Help?

View File

@@ -3,8 +3,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26430.6
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F18F1765-4A02-42FD-9BEF-F0E2FCBD9D17}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{3C5BE746-03E5-4895-9988-0B57F162F86C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0F0901FF-E8D9-426A-B5A2-17C7F47C1529}"
@@ -15,6 +13,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpCompress.Test", "tests
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "build", "build\build.csproj", "{D4D613CB-5E94-47FB-85BE-B8423D20C545}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Config", "Config", "{CDB42573-7D22-4490-BA12-1B7FB99CE7FB}"
ProjectSection(SolutionItems) = preProject
Directory.Build.props = Directory.Build.props
global.json = global.json
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU

View File

@@ -33,6 +33,18 @@ If using Compression Stream classes directly and you don't want the wrapped stre
Also, look over the tests for more thorough [examples](https://github.com/adamhathcock/sharpcompress/tree/master/tests/SharpCompress.Test)
### Create Zip Archive from multiple files
```C#
using(var archive = ZipArchive.Create())
{
archive.AddEntry("file01.txt", "C:\\file01.txt");
archive.AddEntry("file02.txt", "C:\\file02.txt");
...
archive.SaveTo("C:\\temp.zip", CompressionType.Deflate);
}
```
### Create Zip Archive from all files in a directory to a file
```C#
@@ -143,4 +155,4 @@ foreach(var entry in tr.Entries)
{
Console.WriteLine($"{entry.Key}");
}
```
```

View File

@@ -7,8 +7,10 @@ using static Bullseye.Targets;
using static SimpleExec.Command;
const string Clean = "clean";
const string Restore = "restore";
const string Build = "build";
const string Test = "test";
const string Format = "format";
const string Publish = "publish";
Target(
@@ -38,10 +40,21 @@ Target(
);
Target(
Build,
Format,
() =>
{
Run("dotnet", "build src/SharpCompress/SharpCompress.csproj -c Release");
Run("dotnet", "tool restore");
Run("dotnet", "csharpier --check .");
}
);
Target(Restore, DependsOn(Format), () => Run("dotnet", "restore"));
Target(
Build,
DependsOn(Restore),
() =>
{
Run("dotnet", "build src/SharpCompress/SharpCompress.csproj -c Release --no-restore");
}
);
@@ -63,7 +76,7 @@ Target(
foreach (var file in GetFiles("**/*.Test.csproj"))
{
Run("dotnet", $"test {file} -c Release -f {framework}");
Run("dotnet", $"test {file} -c Release -f {framework} --no-restore --verbosity=normal");
}
}
);

View File

@@ -6,7 +6,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Bullseye" Version="4.2.0" />
<PackageReference Include="Bullseye" Version="4.2.1" />
<PackageReference Include="Glob" Version="1.1.9" />
<PackageReference Include="SimpleExec" Version="11.0.0" />
</ItemGroup>

View File

@@ -38,7 +38,8 @@ public abstract class AbstractWritableArchive<TEntry, TVolume>
private bool hasModifications;
private bool pauseRebuilding;
internal AbstractWritableArchive(ArchiveType type) : base(type) { }
internal AbstractWritableArchive(ArchiveType type)
: base(type) { }
internal AbstractWritableArchive(ArchiveType type, SourceStream srcStream)
: base(type, srcStream) { }

View File

@@ -128,14 +128,16 @@ public static class ArchiveFactory
}
}
private static T FindFactory<T>(FileInfo finfo) where T : IFactory
private static T FindFactory<T>(FileInfo finfo)
where T : IFactory
{
finfo.CheckNotNull(nameof(finfo));
using Stream stream = finfo.OpenRead();
return FindFactory<T>(stream);
}
private static T FindFactory<T>(Stream stream) where T : IFactory
private static T FindFactory<T>(Stream stream)
where T : IFactory
{
stream.CheckNotNull(nameof(stream));
if (!stream.CanRead || !stream.CanSeek)
@@ -173,7 +175,7 @@ public static class ArchiveFactory
return IsArchive(s, out type);
}
private static bool IsArchive(Stream stream, out ArchiveType? type)
public static bool IsArchive(Stream stream, out ArchiveType? type)
{
type = null;
stream.CheckNotNull(nameof(stream));

View File

@@ -101,7 +101,8 @@ public class GZipArchive : AbstractWritableArchive<GZipArchiveEntry, GZipVolume>
/// </summary>
/// <param name="srcStream"></param>
/// <param name="options"></param>
internal GZipArchive(SourceStream srcStream) : base(ArchiveType.Tar, srcStream) { }
internal GZipArchive(SourceStream srcStream)
: base(ArchiveType.Tar, srcStream) { }
protected override IEnumerable<GZipVolume> LoadVolumes(SourceStream srcStream)
{
@@ -150,7 +151,8 @@ public class GZipArchive : AbstractWritableArchive<GZipArchiveEntry, GZipVolume>
return true;
}
internal GZipArchive() : base(ArchiveType.GZip) { }
internal GZipArchive()
: base(ArchiveType.GZip) { }
protected override GZipArchiveEntry CreateEntryInternal(
string filePath,

View File

@@ -6,8 +6,8 @@ namespace SharpCompress.Archives.GZip;
public class GZipArchiveEntry : GZipEntry, IArchiveEntry
{
internal GZipArchiveEntry(GZipArchive archive, GZipFilePart part) : base(part) =>
Archive = archive;
internal GZipArchiveEntry(GZipArchive archive, GZipFilePart part)
: base(part) => Archive = archive;
public virtual Stream OpenEntryStream()
{

View File

@@ -20,7 +20,8 @@ internal sealed class GZipWritableArchiveEntry : GZipArchiveEntry, IWritableArch
long size,
DateTime? lastModified,
bool closeStream
) : base(archive, null)
)
: base(archive, null)
{
this.stream = stream;
Key = path;

View File

@@ -11,7 +11,8 @@ internal sealed class FileInfoRarFilePart : SeekableFilePart
MarkHeader mh,
FileHeader fh,
FileInfo fi
) : base(mh, fh, volume.Index, volume.Stream, password) => FileInfo = fi;
)
: base(mh, fh, volume.Index, volume.Stream, password) => FileInfo = fi;
internal FileInfo FileInfo { get; }

View File

@@ -23,7 +23,8 @@ public class RarArchive : AbstractArchive<RarArchiveEntry, RarVolume>
/// </summary>
/// <param name="srcStream"></param>
/// <param name="options"></param>
internal RarArchive(SourceStream srcStream) : base(ArchiveType.Rar, srcStream) { }
internal RarArchive(SourceStream srcStream)
: base(ArchiveType.Rar, srcStream) { }
protected override IEnumerable<RarArchiveEntry> LoadEntries(IEnumerable<RarVolume> volumes) =>
RarArchiveEntryFactory.GetEntries(this, volumes, ReaderOptions);

View File

@@ -26,7 +26,7 @@ internal static class RarArchiveVolumeFactory
else
{
//old style - ...rar, .r00, .r01 ...
m = Regex.Match(part1.Name, @"^(.*\.r)(ar|[0-9]+)$", RegexOptions.IgnoreCase);
m = Regex.Match(part1.Name, @"^(.*\.)([r-z{])(ar|[0-9]+)$", RegexOptions.IgnoreCase);
if (m.Success)
item = new FileInfo(
Path.Combine(
@@ -34,8 +34,9 @@ internal static class RarArchiveVolumeFactory
String.Concat(
m.Groups[1].Value,
index == 0
? "ar"
: (index - 1).ToString().PadLeft(m.Groups[2].Value.Length, '0')
? m.Groups[2].Value + m.Groups[3].Value
: (char)(m.Groups[2].Value[0] + ((index - 1) / 100))
+ (index - 1).ToString("D4").Substring(2)
)
)
);

View File

@@ -15,7 +15,8 @@ internal class SeekableFilePart : RarFilePart
int index,
Stream stream,
string? password
) : base(mh, fh, index)
)
: base(mh, fh, index)
{
this.stream = stream;
this.password = password;

View File

@@ -104,7 +104,8 @@ public class SevenZipArchive : AbstractArchive<SevenZipArchiveEntry, SevenZipVol
/// </summary>
/// <param name="srcStream"></param>
/// <param name="options"></param>
internal SevenZipArchive(SourceStream srcStream) : base(ArchiveType.SevenZip, srcStream) { }
internal SevenZipArchive(SourceStream srcStream)
: base(ArchiveType.SevenZip, srcStream) { }
protected override IEnumerable<SevenZipVolume> LoadVolumes(SourceStream srcStream)
{
@@ -125,7 +126,8 @@ public class SevenZipArchive : AbstractArchive<SevenZipArchiveEntry, SevenZipVol
return IsSevenZipFile(stream);
}
internal SevenZipArchive() : base(ArchiveType.SevenZip) { }
internal SevenZipArchive()
: base(ArchiveType.SevenZip) { }
protected override IEnumerable<SevenZipArchiveEntry> LoadEntries(
IEnumerable<SevenZipVolume> volumes

View File

@@ -5,8 +5,8 @@ namespace SharpCompress.Archives.SevenZip;
public class SevenZipArchiveEntry : SevenZipEntry, IArchiveEntry
{
internal SevenZipArchiveEntry(SevenZipArchive archive, SevenZipFilePart part) : base(part) =>
Archive = archive;
internal SevenZipArchiveEntry(SevenZipArchive archive, SevenZipFilePart part)
: base(part) => Archive = archive;
public Stream OpenEntryStream() => FilePart.GetCompressedStream();

View File

@@ -135,9 +135,11 @@ public class TarArchive : AbstractWritableArchive<TarArchiveEntry, TarVolume>
/// </summary>
/// <param name="srcStream"></param>
/// <param name="options"></param>
internal TarArchive(SourceStream srcStream) : base(ArchiveType.Tar, srcStream) { }
internal TarArchive(SourceStream srcStream)
: base(ArchiveType.Tar, srcStream) { }
internal TarArchive() : base(ArchiveType.Tar) { }
internal TarArchive()
: base(ArchiveType.Tar) { }
protected override IEnumerable<TarArchiveEntry> LoadEntries(IEnumerable<TarVolume> volumes)
{

View File

@@ -21,7 +21,8 @@ internal sealed class TarWritableArchiveEntry : TarArchiveEntry, IWritableArchiv
long size,
DateTime? lastModified,
bool closeStream
) : base(archive, null, compressionType)
)
: base(archive, null, compressionType)
{
this.stream = stream;
Key = path;

View File

@@ -32,7 +32,8 @@ public class ZipArchive : AbstractWritableArchive<ZipArchiveEntry, ZipVolume>
/// </summary>
/// <param name="srcStream"></param>
/// <param name="options"></param>
internal ZipArchive(SourceStream srcStream) : base(ArchiveType.Zip, srcStream) =>
internal ZipArchive(SourceStream srcStream)
: base(ArchiveType.Zip, srcStream) =>
headerFactory = new SeekableZipHeaderFactory(
srcStream.ReaderOptions.Password,
srcStream.ReaderOptions.ArchiveEncoding
@@ -133,7 +134,7 @@ public class ZipArchive : AbstractWritableArchive<ZipArchiveEntry, ZipVolume>
public static bool IsZipFile(Stream stream, string? password = null)
{
var headerFactory = new StreamingZipHeaderFactory(password, new ArchiveEncoding());
var headerFactory = new StreamingZipHeaderFactory(password, new ArchiveEncoding(), null);
try
{
var header = headerFactory
@@ -157,7 +158,7 @@ public class ZipArchive : AbstractWritableArchive<ZipArchiveEntry, ZipVolume>
public static bool IsZipMulti(Stream stream, string? password = null)
{
var headerFactory = new StreamingZipHeaderFactory(password, new ArchiveEncoding());
var headerFactory = new StreamingZipHeaderFactory(password, new ArchiveEncoding(), null);
try
{
var header = headerFactory
@@ -217,7 +218,8 @@ public class ZipArchive : AbstractWritableArchive<ZipArchiveEntry, ZipVolume>
return new ZipVolume(SrcStream, ReaderOptions, idx++).AsEnumerable();
}
internal ZipArchive() : base(ArchiveType.Zip) { }
internal ZipArchive()
: base(ArchiveType.Zip) { }
protected override IEnumerable<ZipArchiveEntry> LoadEntries(IEnumerable<ZipVolume> volumes)
{
@@ -298,6 +300,6 @@ public class ZipArchive : AbstractWritableArchive<ZipArchiveEntry, ZipVolume>
{
var stream = Volumes.Single().Stream;
stream.Position = 0;
return ZipReader.Open(stream, ReaderOptions);
return ZipReader.Open(stream, ReaderOptions, Entries);
}
}

View File

@@ -6,8 +6,8 @@ namespace SharpCompress.Archives.Zip;
public class ZipArchiveEntry : ZipEntry, IArchiveEntry
{
internal ZipArchiveEntry(ZipArchive archive, SeekableZipFilePart? part) : base(part) =>
Archive = archive;
internal ZipArchiveEntry(ZipArchive archive, SeekableZipFilePart? part)
: base(part) => Archive = archive;
public virtual Stream OpenEntryStream() => Parts.Single().GetCompressedStream();

View File

@@ -19,7 +19,8 @@ internal class ZipWritableArchiveEntry : ZipArchiveEntry, IWritableArchiveEntry
long size,
DateTime? lastModified,
bool closeStream
) : base(archive, null)
)
: base(archive, null)
{
this.stream = stream;
Key = path;

View File

@@ -26,7 +26,8 @@ public class ArchiveEncoding
/// <returns>string Func(bytes, index, length)</returns>
public Func<byte[], int, int, string>? CustomDecoder { get; set; }
public ArchiveEncoding() : this(Encoding.Default, Encoding.Default) { }
public ArchiveEncoding()
: this(Encoding.Default, Encoding.Default) { }
public ArchiveEncoding(Encoding def, Encoding password)
{

View File

@@ -4,5 +4,6 @@ namespace SharpCompress.Common;
public class ArchiveException : Exception
{
public ArchiveException(string message) : base(message) { }
public ArchiveException(string message)
: base(message) { }
}

View File

@@ -4,5 +4,6 @@ namespace SharpCompress.Common;
public class CryptographicException : Exception
{
public CryptographicException(string message) : base(message) { }
public CryptographicException(string message)
: base(message) { }
}

View File

@@ -4,7 +4,9 @@ namespace SharpCompress.Common;
public class ExtractionException : Exception
{
public ExtractionException(string message) : base(message) { }
public ExtractionException(string message)
: base(message) { }
public ExtractionException(string message, Exception inner) : base(message, inner) { }
public ExtractionException(string message, Exception inner)
: base(message, inner) { }
}

View File

@@ -12,8 +12,8 @@ internal static class FlagUtility
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to test</param>
/// <returns></returns>
public static bool HasFlag<T>(long bitField, T flag) where T : struct =>
HasFlag(bitField, flag);
public static bool HasFlag<T>(long bitField, T flag)
where T : struct => HasFlag(bitField, flag);
/// <summary>
/// Returns true if the flag is set on the specified bit field.
@@ -23,8 +23,8 @@ internal static class FlagUtility
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to test</param>
/// <returns></returns>
public static bool HasFlag<T>(ulong bitField, T flag) where T : struct =>
HasFlag(bitField, flag);
public static bool HasFlag<T>(ulong bitField, T flag)
where T : struct => HasFlag(bitField, flag);
/// <summary>
/// Returns true if the flag is set on the specified bit field.
@@ -45,8 +45,8 @@ internal static class FlagUtility
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to test</param>
/// <returns></returns>
public static bool HasFlag<T>(T bitField, T flag) where T : struct =>
HasFlag(Convert.ToInt64(bitField), Convert.ToInt64(flag));
public static bool HasFlag<T>(T bitField, T flag)
where T : struct => HasFlag(Convert.ToInt64(bitField), Convert.ToInt64(flag));
/// <summary>
/// Returns true if the flag is set on the specified bit field.
@@ -81,6 +81,6 @@ internal static class FlagUtility
/// <param name="flag">Flag to change</param>
/// <param name="on">bool</param>
/// <returns>The flagged variable with the flag changed</returns>
public static long SetFlag<T>(T bitField, T flag, bool on) where T : struct =>
SetFlag(Convert.ToInt64(bitField), Convert.ToInt64(flag), on);
public static long SetFlag<T>(T bitField, T flag, bool on)
where T : struct => SetFlag(Convert.ToInt64(bitField), Convert.ToInt64(flag), on);
}

View File

@@ -13,7 +13,8 @@ internal sealed class GZipFilePart : FilePart
private string? _name;
private readonly Stream _stream;
internal GZipFilePart(Stream stream, ArchiveEncoding archiveEncoding) : base(archiveEncoding)
internal GZipFilePart(Stream stream, ArchiveEncoding archiveEncoding)
: base(archiveEncoding)
{
_stream = stream;
ReadAndValidateGzipHeader();

View File

@@ -2,5 +2,6 @@ namespace SharpCompress.Common;
public class IncompleteArchiveException : ArchiveException
{
public IncompleteArchiveException(string message) : base(message) { }
public IncompleteArchiveException(string message)
: base(message) { }
}

View File

@@ -4,7 +4,9 @@ namespace SharpCompress.Common;
public class InvalidFormatException : ExtractionException
{
public InvalidFormatException(string message) : base(message) { }
public InvalidFormatException(string message)
: base(message) { }
public InvalidFormatException(string message, Exception inner) : base(message, inner) { }
public InvalidFormatException(string message, Exception inner)
: base(message, inner) { }
}

View File

@@ -4,8 +4,9 @@ namespace SharpCompress.Common;
public class MultiVolumeExtractionException : ExtractionException
{
public MultiVolumeExtractionException(string message) : base(message) { }
public MultiVolumeExtractionException(string message)
: base(message) { }
public MultiVolumeExtractionException(string message, Exception inner) : base(message, inner)
{ }
public MultiVolumeExtractionException(string message, Exception inner)
: base(message, inner) { }
}

View File

@@ -2,5 +2,6 @@ namespace SharpCompress.Common;
public class MultipartStreamRequiredException : ExtractionException
{
public MultipartStreamRequiredException(string message) : base(message) { }
public MultipartStreamRequiredException(string message)
: base(message) { }
}

View File

@@ -4,7 +4,9 @@ namespace SharpCompress.Common;
public class PasswordProtectedException : ExtractionException
{
public PasswordProtectedException(string message) : base(message) { }
public PasswordProtectedException(string message)
: base(message) { }
public PasswordProtectedException(string message, Exception inner) : base(message, inner) { }
public PasswordProtectedException(string message, Exception inner)
: base(message, inner) { }
}

View File

@@ -8,7 +8,8 @@ internal class RarCrcBinaryReader : MarkingBinaryReader
{
private uint _currentCrc;
public RarCrcBinaryReader(Stream stream) : base(stream) { }
public RarCrcBinaryReader(Stream stream)
: base(stream) { }
public uint GetCrc32() => ~_currentCrc;

View File

@@ -11,7 +11,8 @@ internal sealed class RarCryptoBinaryReader : RarCrcBinaryReader
private readonly Queue<byte> _data = new Queue<byte>();
private long _readCount;
public RarCryptoBinaryReader(Stream stream, string password) : base(stream)
public RarCryptoBinaryReader(Stream stream, string password)
: base(stream)
{
_password = password;

View File

@@ -15,7 +15,7 @@ internal sealed class RarCryptoWrapper : Stream
{
_actualStream = actualStream;
_salt = salt;
_rijndael = RarRijndael.InitializeFrom(password, salt);
_rijndael = RarRijndael.InitializeFrom(password ?? "", salt);
}
public override void Flush() => throw new NotSupportedException();

View File

@@ -1,4 +1,4 @@
using System;
using System;
using SharpCompress.Common.Rar.Headers;
namespace SharpCompress.Common.Rar;
@@ -11,7 +11,8 @@ public abstract class RarEntry : Entry
/// As the V2017 port isn't complete, add this check to use the legacy Rar code.
/// </summary>
internal bool IsRarV3 =>
FileHeader.CompressionAlgorithm == 20
FileHeader.CompressionAlgorithm == 15
|| FileHeader.CompressionAlgorithm == 20
|| FileHeader.CompressionAlgorithm == 26
|| FileHeader.CompressionAlgorithm == 29
|| FileHeader.CompressionAlgorithm == 36; //Nanook - Added 20+26 as Test arc from WinRar2.8 (algo 20) was failing with 2017 code

View File

@@ -8,7 +8,8 @@ namespace SharpCompress.Common.Rar;
/// </summary>
internal abstract class RarFilePart : FilePart
{
internal RarFilePart(MarkHeader mh, FileHeader fh, int index) : base(fh.ArchiveEncoding)
internal RarFilePart(MarkHeader mh, FileHeader fh, int index)
: base(fh.ArchiveEncoding)
{
MarkHeader = mh;
FileHeader = fh;

View File

@@ -17,7 +17,8 @@ internal class SevenZipFilePart : FilePart
int index,
CFileItem fileEntry,
ArchiveEncoding archiveEncoding
) : base(archiveEncoding)
)
: base(archiveEncoding)
{
_stream = stream;
_database = database;

View File

@@ -72,6 +72,10 @@ public class TarEntry : Entry
yield return new TarEntry(new TarFilePart(h, null), compressionType);
}
}
else
{
throw new IncompleteArchiveException("Unexpected EOF reading tar file");
}
}
}
}

View File

@@ -7,7 +7,8 @@ internal sealed class TarFilePart : FilePart
{
private readonly Stream _seekableStream;
internal TarFilePart(TarHeader header, Stream seekableStream) : base(header.ArchiveEncoding)
internal TarFilePart(TarHeader header, Stream seekableStream)
: base(header.ArchiveEncoding)
{
_seekableStream = seekableStream;
Header = header;

View File

@@ -4,7 +4,8 @@ namespace SharpCompress.Common.Zip.Headers;
internal class DirectoryEndHeader : ZipHeader
{
public DirectoryEndHeader() : base(ZipHeaderType.DirectoryEnd) { }
public DirectoryEndHeader()
: base(ZipHeaderType.DirectoryEnd) { }
internal override void Read(BinaryReader reader)
{

View File

@@ -4,7 +4,8 @@ namespace SharpCompress.Common.Zip.Headers;
internal class IgnoreHeader : ZipHeader
{
public IgnoreHeader(ZipHeaderType type) : base(type) { }
public IgnoreHeader(ZipHeaderType type)
: base(type) { }
internal override void Read(BinaryReader reader) { }
}

View File

@@ -5,7 +5,8 @@ namespace SharpCompress.Common.Zip.Headers;
internal class SplitHeader : ZipHeader
{
public SplitHeader() : base(ZipHeaderType.Split) { }
public SplitHeader()
: base(ZipHeaderType.Split) { }
internal override void Read(BinaryReader reader) => throw new NotImplementedException();
}

View File

@@ -4,7 +4,8 @@ namespace SharpCompress.Common.Zip.Headers;
internal class Zip64DirectoryEndHeader : ZipHeader
{
public Zip64DirectoryEndHeader() : base(ZipHeaderType.Zip64DirectoryEnd) { }
public Zip64DirectoryEndHeader()
: base(ZipHeaderType.Zip64DirectoryEnd) { }
internal override void Read(BinaryReader reader)
{

View File

@@ -4,7 +4,8 @@ namespace SharpCompress.Common.Zip.Headers;
internal class Zip64DirectoryEndLocatorHeader : ZipHeader
{
public Zip64DirectoryEndLocatorHeader() : base(ZipHeaderType.Zip64DirectoryEndLocator) { }
public Zip64DirectoryEndLocatorHeader()
: base(ZipHeaderType.Zip64DirectoryEndLocator) { }
internal override void Read(BinaryReader reader)
{

View File

@@ -9,7 +9,8 @@ namespace SharpCompress.Common.Zip.Headers;
internal abstract class ZipFileEntry : ZipHeader
{
protected ZipFileEntry(ZipHeaderType type, ArchiveEncoding archiveEncoding) : base(type)
protected ZipFileEntry(ZipHeaderType type, ArchiveEncoding archiveEncoding)
: base(type)
{
Extra = new List<ExtraData>();
ArchiveEncoding = archiveEncoding;

View File

@@ -14,7 +14,8 @@ internal class SeekableZipFilePart : ZipFilePart
SeekableZipHeaderFactory headerFactory,
DirectoryEntryHeader header,
Stream stream
) : base(header, stream)
)
: base(header, stream)
{
_headerFactory = headerFactory;
_directoryEntryHeader = header;

View File

@@ -1,4 +1,5 @@
using System.IO;
using System.Net.Sockets;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.Compressors.Deflate;
using SharpCompress.IO;
@@ -9,7 +10,8 @@ internal sealed class StreamingZipFilePart : ZipFilePart
{
private Stream? _decompressionStream;
internal StreamingZipFilePart(ZipFileEntry header, Stream stream) : base(header, stream) { }
internal StreamingZipFilePart(ZipFileEntry header, Stream stream)
: base(header, stream) { }
protected override Stream CreateBaseStream() => Header.PackedStream;
@@ -36,57 +38,19 @@ internal sealed class StreamingZipFilePart : ZipFilePart
{
return new BinaryReader(rewindableStream);
}
if (Header.HasData && !Skipped)
{
_decompressionStream ??= GetCompressedStream();
if (Header.CompressionMethod != ZipCompressionMethod.None)
_decompressionStream.Skip();
// If we had TotalIn / TotalOut we could have used them
Header.CompressedSize = _decompressionStream.Position;
if (_decompressionStream is DeflateStream deflateStream)
{
_decompressionStream.Skip();
// If we had TotalIn / TotalOut we could have used them
Header.CompressedSize = _decompressionStream.Position;
if (_decompressionStream is DeflateStream deflateStream)
{
rewindableStream.Rewind(deflateStream.InputBuffer);
}
}
else
{
// We would need to search for the magic word
rewindableStream.Position -= 4;
var pos = rewindableStream.Position;
while (Utility.Find(rewindableStream, new byte[] { 0x50, 0x4b, 0x07, 0x08 }))
{
// We should probably check CRC32 for positive matching as well
var size = rewindableStream.Position - pos;
var br = new BinaryReader(rewindableStream);
br.ReadUInt32();
br.ReadUInt32(); // CRC32
var compressed_size = br.ReadUInt32();
var uncompressed_size = br.ReadUInt32();
var uncompressed_64bit = br.ReadInt64();
var test_64bit = ((long)uncompressed_size << 32) | compressed_size;
if (test_64bit == size && test_64bit == uncompressed_64bit)
{
Header.CompressedSize = test_64bit;
Header.UncompressedSize = uncompressed_64bit;
rewindableStream.Position -= 24;
break;
}
if (compressed_size == size && compressed_size == uncompressed_size)
{
Header.CompressedSize = compressed_size;
Header.UncompressedSize = uncompressed_size;
rewindableStream.Position -= 24;
break;
}
rewindableStream.Position -= 20;
}
rewindableStream.Rewind(deflateStream.InputBuffer);
}
Skipped = true;

View File

@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.IO;
@@ -7,8 +8,17 @@ namespace SharpCompress.Common.Zip;
internal class StreamingZipHeaderFactory : ZipHeaderFactory
{
internal StreamingZipHeaderFactory(string? password, ArchiveEncoding archiveEncoding)
: base(StreamingMode.Streaming, password, archiveEncoding) { }
private IEnumerable<ZipEntry>? _entries;
internal StreamingZipHeaderFactory(
string? password,
ArchiveEncoding archiveEncoding,
IEnumerable<ZipEntry>? entries
)
: base(StreamingMode.Streaming, password, archiveEncoding)
{
_entries = entries;
}
internal IEnumerable<ZipHeader> ReadStreamHeader(Stream stream)
{
@@ -87,6 +97,21 @@ internal class StreamingZipHeaderFactory : ZipHeaderFactory
if (header.ZipHeaderType == ZipHeaderType.LocalEntry)
{
var local_header = ((LocalEntryHeader)header);
var dir_header = _entries?.FirstOrDefault(
entry =>
entry.Key == local_header.Name
&& local_header.CompressedSize == 0
&& local_header.UncompressedSize == 0
&& local_header.Crc == 0
&& local_header.IsDirectory == false
);
if (dir_header != null)
{
local_header.UncompressedSize = dir_header.Size;
local_header.CompressedSize = dir_header.CompressedSize;
local_header.Crc = (uint)dir_header.Crc;
}
// If we have CompressedSize, there is data to be read
if (local_header.CompressedSize > 0)

View File

@@ -17,7 +17,8 @@ namespace SharpCompress.Common.Zip;
internal abstract class ZipFilePart : FilePart
{
internal ZipFilePart(ZipFileEntry header, Stream stream) : base(header.ArchiveEncoding)
internal ZipFilePart(ZipFileEntry header, Stream stream)
: base(header.ArchiveEncoding)
{
Header = header;
header.Part = this;
@@ -66,7 +67,17 @@ internal abstract class ZipFilePart : FilePart
{
case ZipCompressionMethod.None:
{
return stream;
if (stream is ReadOnlySubStream)
{
return stream;
}
if (Header.CompressedSize > 0)
{
return new ReadOnlySubStream(stream, Header.CompressedSize);
}
return new DataDescriptorStream(stream);
}
case ZipCompressionMethod.Deflate:
{

View File

@@ -319,7 +319,8 @@ internal sealed class CBZip2OutputStream : Stream
private int currentChar = -1;
private int runLength;
public CBZip2OutputStream(Stream inStream) : this(inStream, 9) { }
public CBZip2OutputStream(Stream inStream)
: this(inStream, 9) { }
public CBZip2OutputStream(Stream inStream, int inBlockSize)
{

View File

@@ -189,7 +189,8 @@ public class ZlibException : Exception
/// This ctor collects a message attached to the exception.
/// </summary>
/// <param name="s"></param>
public ZlibException(string s) : base(s) { }
public ZlibException(string s)
: base(s) { }
}
internal class SharedUtils

View File

@@ -21,8 +21,8 @@ internal class BCJFilter : Filter
private int _pos;
private int _prevMask;
public BCJFilter(bool isEncoder, Stream baseStream) : base(isEncoder, baseStream, 5) =>
_pos = 5;
public BCJFilter(bool isEncoder, Stream baseStream)
: base(isEncoder, baseStream, 5) => _pos = 5;
private static bool Test86MsByte(byte b) => b == 0x00 || b == 0xFF;

View File

@@ -34,7 +34,17 @@ public sealed class BranchExecFilter
//The previous version of the code would corrupt 2 bytes in the Test.exe at 0x6CF9 (3D6D - should be 4000) - Test zip: WinZip27.Xz.zipx
public static void X86Converter(byte[] buf, uint ip, ref uint state)
{
bool[] mask_to_allowed_status = new[] { true, true, true, false, true, false, false, false };
bool[] mask_to_allowed_status = new[]
{
true,
true,
true,
false,
true,
false,
false,
false
};
byte[] mask_to_bit_num = new byte[] { 0, 1, 2, 2, 3, 3, 3, 3 };
@@ -69,8 +79,7 @@ public sealed class BranchExecFilter
if (prev_mask != 0)
{
b = buf[i + 4 - mask_to_bit_num[prev_mask]];
if (!mask_to_allowed_status[prev_mask]
|| X86TestByte(b))
if (!mask_to_allowed_status[prev_mask] || X86TestByte(b))
{
prev_pos = i;
prev_mask = (prev_mask << 1) | 1;
@@ -83,7 +92,8 @@ public sealed class BranchExecFilter
if (X86TestByte(buf[i + 4]))
{
src = ((uint)buf[i + 4] << 24)
src =
((uint)buf[i + 4] << 24)
| ((uint)buf[i + 3] << 16)
| ((uint)buf[i + 2] << 8)
| buf[i + 1];

View File

@@ -0,0 +1,37 @@
using System;
using System.IO;
namespace SharpCompress.Compressors.Filters
{
internal class DeltaFilter : Filter
{
private const int DISTANCE_MIN = 1;
private const int DISTANCE_MAX = 256;
private const int DISTANCE_MASK = DISTANCE_MAX - 1;
private int _distance;
private byte[] _history;
private int _position;
public DeltaFilter(bool isEncoder, Stream baseStream, byte[] info)
: base(isEncoder, baseStream, 1)
{
_distance = info[0];
_history = new byte[DISTANCE_MAX];
_position = 0;
}
protected override int Transform(byte[] buffer, int offset, int count)
{
int end = offset + count;
for (int i = offset; i < end; i++)
{
buffer[i] += _history[(_distance + _position--) & DISTANCE_MASK];
_history[_position & DISTANCE_MASK] = buffer[i];
}
return count;
}
}
}

View File

@@ -28,7 +28,8 @@ internal class BitVector
}
}
public BitVector(List<bool> bits) : this(bits.Count)
public BitVector(List<bool> bits)
: this(bits.Count)
{
for (var i = 0; i < bits.Count; i++)
{

View File

@@ -8,7 +8,8 @@ namespace SharpCompress.Compressors.LZMA;
/// </summary>
internal class DataErrorException : Exception
{
public DataErrorException() : base("Data Error") { }
public DataErrorException()
: base("Data Error") { }
}
/// <summary>
@@ -16,7 +17,8 @@ internal class DataErrorException : Exception
/// </summary>
internal class InvalidParamException : Exception
{
public InvalidParamException() : base("Invalid Parameter") { }
public InvalidParamException()
: base("Invalid Parameter") { }
}
public interface ICodeProgress

View File

@@ -1725,7 +1725,10 @@ internal class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties
return -1;
}
public void SetCoderProperties(ReadOnlySpan<CoderPropId> propIDs, ReadOnlySpan<object> properties)
public void SetCoderProperties(
ReadOnlySpan<CoderPropId> propIDs,
ReadOnlySpan<object> properties
)
{
for (int i = 0; i < properties.Length; i++)
{

View File

@@ -12,11 +12,14 @@ public class LzmaEncoderProperties
internal ReadOnlySpan<object> Properties => _properties;
private readonly object[] _properties;
public LzmaEncoderProperties() : this(false) { }
public LzmaEncoderProperties()
: this(false) { }
public LzmaEncoderProperties(bool eos) : this(eos, 1 << 20) { }
public LzmaEncoderProperties(bool eos)
: this(eos, 1 << 20) { }
public LzmaEncoderProperties(bool eos, int dictionary) : this(eos, dictionary, 32) { }
public LzmaEncoderProperties(bool eos, int dictionary)
: this(eos, dictionary, 32) { }
public LzmaEncoderProperties(bool eos, int dictionary, int numFastBytes)
{

View File

@@ -14,6 +14,7 @@ namespace SharpCompress.Compressors.LZMA;
internal static class DecoderRegistry
{
private const uint K_COPY = 0x0;
private const uint K_DELTA = 0x3;
private const uint K_LZMA2 = 0x21;
private const uint K_LZMA = 0x030101;
private const uint K_PPMD = 0x030401;
@@ -39,6 +40,8 @@ internal static class DecoderRegistry
throw new NotSupportedException();
}
return inStreams.Single();
case K_DELTA:
return new DeltaFilter(false, inStreams.Single(), info);
case K_LZMA:
case K_LZMA2:
return new LzmaStream(info, inStreams.Single(), -1, limit);

View File

@@ -14,7 +14,8 @@ internal class FreqData : Pointer
// STATE _PACK_ATTR * Stats;
// };
internal FreqData(byte[] memory) : base(memory) { }
internal FreqData(byte[] memory)
: base(memory) { }
internal int SummFreq
{

View File

@@ -82,7 +82,8 @@ internal class PpmContext : Pointer
//UPGRADE_NOTE: Final was removed from the declaration of 'ps '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
internal int[] _ps = new int[256];
public PpmContext(byte[] memory) : base(memory)
public PpmContext(byte[] memory)
: base(memory)
{
_oneState = new State(memory);
_freqData = new FreqData(memory);

View File

@@ -13,7 +13,8 @@ internal abstract class Pointer
internal virtual int Address { get; set; }
protected T Initialize<T>(byte[] mem) where T : Pointer
protected T Initialize<T>(byte[] mem)
where T : Pointer
{
Memory = mem;
Address = 0;

View File

@@ -13,7 +13,8 @@ internal class RarMemBlock : Pointer
private int _next,
_prev; // Pointer RarMemBlock
public RarMemBlock(byte[] memory) : base(memory) { }
public RarMemBlock(byte[] memory)
: base(memory) { }
internal int Stamp
{

View File

@@ -10,7 +10,8 @@ internal class RarNode : Pointer
public const int SIZE = 4;
public RarNode(byte[] memory) : base(memory) { }
public RarNode(byte[] memory)
: base(memory) { }
internal int GetNext()
{

View File

@@ -8,7 +8,8 @@ internal sealed class State : Pointer
{
internal const int SIZE = 6;
internal State(byte[]? memory) : base(memory) { }
internal State(byte[]? memory)
: base(memory) { }
internal int Symbol
{

View File

@@ -9,7 +9,8 @@ public class PpmdProperties
private int _allocatorSize;
internal Allocator? _allocator;
public PpmdProperties() : this(16 << 20, 6) { }
public PpmdProperties()
: this(16 << 20, 6) { }
public PpmdProperties(int allocatorSize, int modelOrder)
: this(allocatorSize, modelOrder, ModelRestorationMethod.Restart) { }
@@ -29,7 +30,8 @@ public class PpmdProperties
public PpmdVersion Version { get; } = PpmdVersion.I1;
internal ModelRestorationMethod RestorationMethod { get; }
public PpmdProperties(byte[] properties) : this(properties.AsSpan()) { }
public PpmdProperties(byte[] properties)
: this(properties.AsSpan()) { }
public PpmdProperties(ReadOnlySpan<byte> properties)
{

View File

@@ -12,7 +12,8 @@ internal class RarCrcStream : RarStream
IRarUnpack unpack,
FileHeader fileHeader,
MultiVolumeReadOnlyStream readStream
) : base(unpack, fileHeader, readStream)
)
: base(unpack, fileHeader, readStream)
{
this.readStream = readStream;
ResetCrc();

View File

@@ -2,5 +2,6 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode;
internal class BitDecode : Decode
{
internal BitDecode() : base(new int[PackDef.BC]) { }
internal BitDecode()
: base(new int[PackDef.BC]) { }
}

View File

@@ -2,7 +2,8 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode;
internal class Decode
{
internal Decode() : this(new int[2]) { }
internal Decode()
: this(new int[2]) { }
protected Decode(int[] customDecodeNum)
{

View File

@@ -2,5 +2,6 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode;
internal class DistDecode : Decode
{
internal DistDecode() : base(new int[PackDef.DC]) { }
internal DistDecode()
: base(new int[PackDef.DC]) { }
}

View File

@@ -2,5 +2,6 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode;
internal class LitDecode : Decode
{
internal LitDecode() : base(new int[PackDef.NC]) { }
internal LitDecode()
: base(new int[PackDef.NC]) { }
}

View File

@@ -2,5 +2,6 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode;
internal class LowDistDecode : Decode
{
internal LowDistDecode() : base(new int[PackDef.LDC]) { }
internal LowDistDecode()
: base(new int[PackDef.LDC]) { }
}

View File

@@ -2,5 +2,6 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode;
internal class MultDecode : Decode
{
internal MultDecode() : base(new int[PackDef.MC20]) { }
internal MultDecode()
: base(new int[PackDef.MC20]) { }
}

View File

@@ -2,5 +2,6 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode;
internal class RepDecode : Decode
{
internal RepDecode() : base(new int[PackDef.RC]) { }
internal RepDecode()
: base(new int[PackDef.RC]) { }
}

View File

@@ -6,32 +6,29 @@ namespace SharpCompress.Compressors.Xz.Filters;
public abstract class BlockFilter : ReadOnlyStream
{
[CLSCompliant(false)]
public enum FilterTypes : ulong
private enum FilterTypes : ulong
{
DELTA = 0x03,
ARCH_x86_FILTER = 0x04,
ARCH_PowerPC_FILTER = 0x05,
ARCH_IA64_FILTER = 0x06,
ARCH_ARM_FILTER = 0x07,
ARCH_ARMTHUMB_FILTER = 0x08,
ARCH_SPARC_FILTER = 0x09,
LZMA2 = 0x21
//Delta = 0x03,
ArchX86Filter = 0x04,
ArchPowerPcFilter = 0x05,
ArchIa64Filter = 0x06,
ArchArmFilter = 0x07,
ArchArmThumbFilter = 0x08,
ArchSparcFilter = 0x09,
Lzma2 = 0x21
}
private static readonly Dictionary<FilterTypes, Func<BlockFilter>> FilterMap = new Dictionary<
FilterTypes,
Func<BlockFilter>
>
{
{ FilterTypes.ARCH_x86_FILTER, () => new X86Filter() },
{ FilterTypes.ARCH_PowerPC_FILTER, () => new PowerPCFilter() },
{ FilterTypes.ARCH_IA64_FILTER, () => new IA64Filter() },
{ FilterTypes.ARCH_ARM_FILTER, () => new ArmFilter() },
{ FilterTypes.ARCH_ARMTHUMB_FILTER, () => new ArmThumbFilter() },
{ FilterTypes.ARCH_SPARC_FILTER, () => new SparcFilter() },
{ FilterTypes.LZMA2, () => new Lzma2Filter() }
};
private static readonly Dictionary<FilterTypes, Func<BlockFilter>> FILTER_MAP =
new()
{
{ FilterTypes.ArchX86Filter, () => new X86Filter() },
{ FilterTypes.ArchPowerPcFilter, () => new PowerPCFilter() },
{ FilterTypes.ArchIa64Filter, () => new IA64Filter() },
{ FilterTypes.ArchArmFilter, () => new ArmFilter() },
{ FilterTypes.ArchArmThumbFilter, () => new ArmThumbFilter() },
{ FilterTypes.ArchSparcFilter, () => new SparcFilter() },
{ FilterTypes.Lzma2, () => new Lzma2Filter() }
};
public abstract bool AllowAsLast { get; }
public abstract bool AllowAsNonLast { get; }
@@ -43,12 +40,12 @@ public abstract class BlockFilter : ReadOnlyStream
public static BlockFilter Read(BinaryReader reader)
{
var filterType = (FilterTypes)reader.ReadXZInteger();
if (!FilterMap.ContainsKey(filterType))
if (!FILTER_MAP.ContainsKey(filterType))
{
throw new NotImplementedException($"Filter {filterType} has not yet been implemented");
}
var filter = FilterMap[filterType]()!;
var filter = FILTER_MAP[filterType]();
var sizeOfProperties = reader.ReadXZInteger();
if (sizeOfProperties > int.MaxValue)

View File

@@ -27,7 +27,8 @@ public sealed class XZBlock : XZReadOnlyStream
private bool _crcChecked;
private ulong _bytesRead;
public XZBlock(Stream stream, CheckType checkType, int checkSize) : base(stream)
public XZBlock(Stream stream, CheckType checkType, int checkSize)
: base(stream)
{
_checkType = checkType;
_checkSize = checkSize;

View File

@@ -45,7 +45,8 @@ public sealed class XZStream : XZReadOnlyStream
private bool _endOfStream;
public XZStream(Stream stream) : base(stream) { }
public XZStream(Stream stream)
: base(stream) { }
public override int Read(byte[] buffer, int offset, int count)
{

View File

@@ -18,7 +18,8 @@ public sealed class Crc32Stream : Stream
private readonly Stream stream;
public Crc32Stream(Stream stream) : this(stream, DefaultPolynomial, DefaultSeed) { }
public Crc32Stream(Stream stream)
: this(stream, DefaultPolynomial, DefaultSeed) { }
public Crc32Stream(Stream stream, uint polynomial, uint seed)
{

View File

@@ -6,7 +6,9 @@ public class CryptoException : Exception
{
public CryptoException() { }
public CryptoException(string message) : base(message) { }
public CryptoException(string message)
: base(message) { }
public CryptoException(string message, Exception exception) : base(message, exception) { }
public CryptoException(string message, Exception exception)
: base(message, exception) { }
}

View File

@@ -16,7 +16,9 @@ public class DataLengthException : CryptoException
* @param message the message to be carried with the exception.
*/
public DataLengthException(string message) : base(message) { }
public DataLengthException(string message)
: base(message) { }
public DataLengthException(string message, Exception exception) : base(message, exception) { }
public DataLengthException(string message, Exception exception)
: base(message, exception) { }
}

View File

@@ -1697,7 +1697,8 @@ public sealed class RijndaelEngine : IBlockCipher
* default constructor - 128 bit block size.
*/
public RijndaelEngine() : this(128) { }
public RijndaelEngine()
: this(128) { }
/**
* basic constructor - set the cipher up for a given blocksize

View File

@@ -5,7 +5,8 @@ namespace SharpCompress.IO;
internal class CountingWritableSubStream : NonDisposingStream
{
internal CountingWritableSubStream(Stream stream) : base(stream, throwOnDispose: false) { }
internal CountingWritableSubStream(Stream stream)
: base(stream, throwOnDispose: false) { }
public ulong Count { get; private set; }

View File

@@ -0,0 +1,154 @@
using System;
using System.IO;
using System.Runtime.CompilerServices;
namespace SharpCompress.IO;
public class DataDescriptorStream : Stream
{
private readonly Stream _stream;
private long _start;
private int _search_position;
private bool _isDisposed;
private bool _done;
private static byte[] DataDescriptorMarker = new byte[] { 0x50, 0x4b, 0x07, 0x08 };
private static long DataDescriptorSize = 24;
public DataDescriptorStream(Stream stream)
{
_stream = stream;
_start = _stream.Position;
_search_position = 0;
_done = false;
}
internal bool IsRecording { get; private set; }
protected override void Dispose(bool disposing)
{
if (_isDisposed)
{
return;
}
_isDisposed = true;
base.Dispose(disposing);
if (disposing)
{
_stream.Dispose();
}
}
public override bool CanRead => true;
public override bool CanSeek => _stream.CanSeek;
public override bool CanWrite => false;
public override void Flush() => throw new NotSupportedException();
public override long Length => _stream.Length;
public override long Position
{
get => _stream.Position;
set => _stream.Position = value;
}
private bool validate_data_descriptor(Stream stream, long size)
{
var br = new BinaryReader(stream);
br.ReadUInt32();
br.ReadUInt32(); // CRC32 can be checked if we calculate it
var compressed_size = br.ReadUInt32();
var uncompressed_size = br.ReadUInt32();
var uncompressed_64bit = br.ReadInt64();
stream.Position -= DataDescriptorSize;
var test_64bit = ((long)uncompressed_size << 32) | compressed_size;
if (test_64bit == size && test_64bit == uncompressed_64bit)
{
return true;
}
if (compressed_size == size && compressed_size == uncompressed_size)
{
return true;
}
return false;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (count == 0 || _done)
{
return 0;
}
int read = _stream.Read(buffer, offset, count);
for (int i = 0; i < read; i++)
{
if (buffer[offset + i] == DataDescriptorMarker[_search_position])
{
_search_position++;
if (_search_position == 4)
{
_search_position = 0;
if (read - i > DataDescriptorSize)
{
var check = new MemoryStream(
buffer,
offset + i - 3,
(int)DataDescriptorSize
);
_done = validate_data_descriptor(
check,
_stream.Position - read + i - 3 - _start
);
if (_done)
{
_stream.Position = _stream.Position - read + i - 3;
return i - 3;
}
}
else
{
_stream.Position = _stream.Position - read + i - 3;
_done = validate_data_descriptor(_stream, _stream.Position - _start);
return i - 3;
}
}
}
else
{
_search_position = 0;
}
}
if (_search_position > 0)
{
read -= _search_position;
_stream.Position -= _search_position;
_search_position = 0;
}
return read;
}
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();
}

View File

@@ -6,7 +6,8 @@ namespace SharpCompress.IO;
internal class MarkingBinaryReader : BinaryReader
{
public MarkingBinaryReader(Stream stream) : base(stream) { }
public MarkingBinaryReader(Stream stream)
: base(stream) { }
public virtual long CurrentReadByteCount { get; protected set; }

View File

@@ -2,11 +2,13 @@ using System;
using System.IO;
namespace SharpCompress.IO;
internal class ReadOnlySubStream : NonDisposingStream
{
private long _position;
public ReadOnlySubStream(Stream stream, long bytesToRead) : this(stream, null, bytesToRead) { }
public ReadOnlySubStream(Stream stream, long bytesToRead)
: this(stream, null, bytesToRead) { }
public ReadOnlySubStream(Stream stream, long? origin, long bytesToRead)
: base(stream, throwOnDispose: false)
@@ -75,6 +77,7 @@ internal class ReadOnlySubStream : NonDisposingStream
if (read > 0)
{
BytesLeftToRead -= read;
_position += read;
}
return read;
}

View File

@@ -9,10 +9,10 @@ namespace SharpCompress.IO;
public class SourceStream : Stream
{
private long _prevSize;
private List<FileInfo> _files;
private List<Stream> _streams;
private Func<int, FileInfo?> _getFilePart;
private Func<int, Stream?> _getStreamPart;
private readonly List<FileInfo> _files;
private readonly List<Stream> _streams;
private readonly Func<int, FileInfo?> _getFilePart;
private readonly Func<int, Stream?> _getStreamPart;
private int _stream;
public SourceStream(FileInfo file, Func<int, FileInfo?> getPart, ReaderOptions options)
@@ -39,10 +39,10 @@ public class SourceStream : Stream
{
_streams.Add(stream!);
_getStreamPart = getStreamPart!;
_getFilePart = new Func<int, FileInfo>(a => null!);
if (stream is FileStream)
_getFilePart = _ => null!;
if (stream is FileStream fileStream)
{
_files.Add(new FileInfo(((FileStream)stream!).Name));
_files.Add(new FileInfo(fileStream.Name));
}
}
else
@@ -50,7 +50,7 @@ public class SourceStream : Stream
_files.Add(file!);
_streams.Add(_files[0].OpenRead());
_getFilePart = getFilePart!;
_getStreamPart = new Func<int, Stream>(a => null!);
_getStreamPart = _ => null!;
}
_stream = 0;
_prevSize = 0;
@@ -98,9 +98,9 @@ public class SourceStream : Stream
}
//throw new Exception($"Stream part {idx} not available.");
_streams.Add(s);
if (s is FileStream)
if (s is FileStream stream)
{
_files.Add(new FileInfo(((FileStream)s).Name));
_files.Add(new FileInfo(stream.Name));
}
}
}
@@ -123,11 +123,11 @@ public class SourceStream : Stream
public override bool CanWrite => false;
public override long Length => (!IsVolumes ? _streams.Sum(a => a.Length) : Current.Length);
public override long Length => !IsVolumes ? _streams.Sum(a => a.Length) : Current.Length;
public override long Position
{
get => _prevSize + Current.Position; //_prevSize is 0 for multivolume
get => _prevSize + Current.Position; //_prevSize is 0 for multi-volume
set => Seek(value, SeekOrigin.Begin);
}
@@ -167,7 +167,7 @@ public class SourceStream : Stream
// Add length of previous stream
_prevSize += length;
Current.Seek(0, SeekOrigin.Begin);
r = -1; //BugFix: reset to allow loop if count is still not 0 - was breaking split zipx (lzma xz etc)
r = -1; //BugFix: reset to allow loop if count is still not 0 - was breaking split zipx (lzma xz etc)
}
}
@@ -222,9 +222,12 @@ public class SourceStream : Stream
{
try
{
stream?.Dispose();
stream.Dispose();
}
catch
{
// ignored
}
catch { }
}
_streams.Clear();
_files.Clear();

View File

@@ -129,7 +129,7 @@ public abstract class AbstractReader<TEntry, TVolume> : IReader, IReaderExtracti
{
var part = Entry.Parts.First();
if (ArchiveType != ArchiveType.Rar && !Entry.IsSolid && Entry.CompressedSize > 0)
if (!Entry.IsSolid && Entry.CompressedSize > 0)
{
//not solid and has a known compressed size then we can skip raw bytes.
var rawStream = part.GetRawStream();

View File

@@ -7,8 +7,8 @@ namespace SharpCompress.Readers.GZip;
public class GZipReader : AbstractReader<GZipEntry, GZipVolume>
{
internal GZipReader(Stream stream, ReaderOptions options) : base(options, ArchiveType.GZip) =>
Volume = new GZipVolume(stream, options);
internal GZipReader(Stream stream, ReaderOptions options)
: base(options, ArchiveType.GZip) => Volume = new GZipVolume(stream, options);
public override GZipVolume Volume { get; }

View File

@@ -11,5 +11,7 @@ internal class NonSeekableStreamFilePart : RarFilePart
internal override Stream GetCompressedStream() => FileHeader.PackedStream;
internal override Stream? GetRawStream() => FileHeader.PackedStream;
internal override string FilePartName => "Unknown Stream - File Entry: " + FileHeader.FileName;
}

View File

@@ -18,7 +18,8 @@ public abstract class RarReader : AbstractReader<RarReaderEntry, RarVolume>
internal Lazy<IRarUnpack> UnpackV1 { get; } =
new Lazy<IRarUnpack>(() => new Compressors.Rar.UnpackV1.Unpack());
internal RarReader(ReaderOptions options) : base(options, ArchiveType.Rar) { }
internal RarReader(ReaderOptions options)
: base(options, ArchiveType.Rar) { }
internal abstract void ValidateArchive(RarVolume archive);

View File

@@ -8,8 +8,8 @@ internal class SingleVolumeRarReader : RarReader
{
private readonly Stream stream;
internal SingleVolumeRarReader(Stream stream, ReaderOptions options) : base(options) =>
this.stream = stream;
internal SingleVolumeRarReader(Stream stream, ReaderOptions options)
: base(options) => this.stream = stream;
internal override void ValidateArchive(RarVolume archive)
{

View File

@@ -10,10 +10,26 @@ public class ZipReader : AbstractReader<ZipEntry, ZipVolume>
{
private readonly StreamingZipHeaderFactory _headerFactory;
private ZipReader(Stream stream, ReaderOptions options) : base(options, ArchiveType.Zip)
private ZipReader(Stream stream, ReaderOptions options)
: base(options, ArchiveType.Zip)
{
Volume = new ZipVolume(stream, options);
_headerFactory = new StreamingZipHeaderFactory(options.Password, options.ArchiveEncoding);
_headerFactory = new StreamingZipHeaderFactory(
options.Password,
options.ArchiveEncoding,
null
);
}
private ZipReader(Stream stream, ReaderOptions options, IEnumerable<ZipEntry> entries)
: base(options, ArchiveType.Zip)
{
Volume = new ZipVolume(stream, options);
_headerFactory = new StreamingZipHeaderFactory(
options.Password,
options.ArchiveEncoding,
entries
);
}
public override ZipVolume Volume { get; }
@@ -32,6 +48,16 @@ public class ZipReader : AbstractReader<ZipEntry, ZipVolume>
return new ZipReader(stream, options ?? new ReaderOptions());
}
public static ZipReader Open(
Stream stream,
ReaderOptions? options,
IEnumerable<ZipEntry> entries
)
{
stream.CheckNotNull(nameof(stream));
return new ZipReader(stream, options ?? new ReaderOptions(), entries);
}
#endregion Open
protected override IEnumerable<ZipEntry> GetEntries(Stream stream)

View File

@@ -5,9 +5,11 @@ namespace SharpCompress.Writers.GZip;
public class GZipWriterOptions : WriterOptions
{
public GZipWriterOptions() : base(CompressionType.GZip) { }
public GZipWriterOptions()
: base(CompressionType.GZip) { }
internal GZipWriterOptions(WriterOptions options) : base(options.CompressionType)
internal GZipWriterOptions(WriterOptions options)
: base(options.CompressionType)
{
LeaveStreamOpen = options.LeaveStreamOpen;
ArchiveEncoding = options.ArchiveEncoding;

View File

@@ -14,7 +14,8 @@ public class TarWriter : AbstractWriter
{
private readonly bool finalizeArchiveOnClose;
public TarWriter(Stream destination, TarWriterOptions options) : base(ArchiveType.Tar, options)
public TarWriter(Stream destination, TarWriterOptions options)
: base(ArchiveType.Tar, options)
{
finalizeArchiveOnClose = options.FinalizeArchiveOnClose;

View File

@@ -12,6 +12,6 @@ public class TarWriterOptions : WriterOptions
public TarWriterOptions(CompressionType compressionType, bool finalizeArchiveOnClose)
: base(compressionType) => FinalizeArchiveOnClose = finalizeArchiveOnClose;
internal TarWriterOptions(WriterOptions options) : this(options.CompressionType, true) =>
ArchiveEncoding = options.ArchiveEncoding;
internal TarWriterOptions(WriterOptions options)
: this(options.CompressionType, true) => ArchiveEncoding = options.ArchiveEncoding;
}

View File

@@ -5,9 +5,11 @@ namespace SharpCompress.Writers.Zip;
public class ZipWriterOptions : WriterOptions
{
public ZipWriterOptions(CompressionType compressionType) : base(compressionType) { }
public ZipWriterOptions(CompressionType compressionType)
: base(compressionType) { }
internal ZipWriterOptions(WriterOptions options) : base(options.CompressionType)
internal ZipWriterOptions(WriterOptions options)
: base(options.CompressionType)
{
LeaveStreamOpen = options.LeaveStreamOpen;
ArchiveEncoding = options.ArchiveEncoding;

View File

@@ -282,4 +282,29 @@ public class ArchiveTests : ReaderTests
}
VerifyFilesEx();
}
protected void ArchiveDeltaDistanceRead(string testArchive)
{
testArchive = Path.Combine(TEST_ARCHIVES_PATH, testArchive);
using (var archive = Archives.ArchiveFactory.Open(testArchive, null))
using (var reader = archive.ExtractAllEntries())
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
var memory = new MemoryStream();
reader.WriteEntryTo(memory);
memory.Position = 0;
for (int y = 0; y < 9; y++)
for (int x = 0; x < 256; x++)
{
Assert.Equal(x, memory.ReadByte());
}
Assert.Equal((int)-1, memory.ReadByte());
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More