diff --git a/build/Program.cs b/build/Program.cs index f3c38336..7c97ed0f 100644 --- a/build/Program.cs +++ b/build/Program.cs @@ -13,7 +13,7 @@ class Program private const string Build = "build"; private const string Test = "test"; private const string Publish = "publish"; - + static void Main(string[] args) { Target(Clean, @@ -46,17 +46,17 @@ class Program Run("dotnet", "format --check"); }); - Target(Build, DependsOn(Format), ForEach("net46", "netstandard2.0", "netstandard2.1"), + Target(Build, DependsOn(Format), ForEach("net46", "netstandard2.0", "netstandard2.1"), framework => { - if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && framework == "net46") - { - return; - } - Run("dotnet", "build src/SharpCompress/SharpCompress.csproj -c Release"); - }); + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && framework == "net46") + { + return; + } + Run("dotnet", "build src/SharpCompress/SharpCompress.csproj -c Release"); + }); - Target(Test, DependsOn(Build), ForEach("netcoreapp3.1"), + Target(Test, DependsOn(Build), ForEach("netcoreapp3.1"), framework => { IEnumerable GetFiles(string d) @@ -69,7 +69,7 @@ class Program Run("dotnet", $"test {file} -c Release -f {framework}"); } }); - + Target(Publish, DependsOn(Test), () => { @@ -77,7 +77,7 @@ class Program }); Target("default", DependsOn(Publish), () => Console.WriteLine("Done!")); - + RunTargetsAndExit(args); } } \ No newline at end of file diff --git a/src/SharpCompress/Archives/AbstractArchive.cs b/src/SharpCompress/Archives/AbstractArchive.cs index 38b71ba3..38e47ade 100644 --- a/src/SharpCompress/Archives/AbstractArchive.cs +++ b/src/SharpCompress/Archives/AbstractArchive.cs @@ -132,9 +132,9 @@ namespace SharpCompress.Archives void IExtractionListener.FireFilePartExtractionBegin(string name, long size, long compressedSize) { FilePartExtractionBegin?.Invoke(this, new FilePartExtractionBeginEventArgs( - compressedSize : compressedSize, - size : size, - name : name + compressedSize: compressedSize, + size: size, + name: name )); } diff --git a/src/SharpCompress/Archives/AbstractWritableArchive.cs b/src/SharpCompress/Archives/AbstractWritableArchive.cs index 1419f0bf..e81a9924 100644 --- a/src/SharpCompress/Archives/AbstractWritableArchive.cs +++ b/src/SharpCompress/Archives/AbstractWritableArchive.cs @@ -12,7 +12,7 @@ namespace SharpCompress.Archives where TEntry : IArchiveEntry where TVolume : IVolume { - private class RebuildPauseDisposable: IDisposable + private class RebuildPauseDisposable : IDisposable { private readonly AbstractWritableArchive archive; diff --git a/src/SharpCompress/Archives/IArchiveEntryExtensions.cs b/src/SharpCompress/Archives/IArchiveEntryExtensions.cs index 0e9e4041..829b8bbd 100644 --- a/src/SharpCompress/Archives/IArchiveEntryExtensions.cs +++ b/src/SharpCompress/Archives/IArchiveEntryExtensions.cs @@ -31,7 +31,7 @@ namespace SharpCompress.Archives } streamListener.FireEntryExtractionEnd(archiveEntry); } - + /// /// Extract to specific directory, retaining filename /// @@ -45,11 +45,11 @@ namespace SharpCompress.Archives /// /// Extract to specific file /// - public static void WriteToFile(this IArchiveEntry entry, + public static void WriteToFile(this IArchiveEntry entry, string destinationFileName, ExtractionOptions? options = null) { - + ExtractionMethods.WriteEntryToFile(entry, destinationFileName, options, (x, fm) => { diff --git a/src/SharpCompress/Archives/Rar/RarArchive.cs b/src/SharpCompress/Archives/Rar/RarArchive.cs index 73ab04d3..b71b2147 100644 --- a/src/SharpCompress/Archives/Rar/RarArchive.cs +++ b/src/SharpCompress/Archives/Rar/RarArchive.cs @@ -120,7 +120,7 @@ namespace SharpCompress.Archives.Rar return IsRarFile(stream); } } - + public static bool IsRarFile(Stream stream, ReaderOptions? options = null) { try diff --git a/src/SharpCompress/Archives/Rar/RarArchiveEntry.cs b/src/SharpCompress/Archives/Rar/RarArchiveEntry.cs index cb4fb169..eee9d996 100644 --- a/src/SharpCompress/Archives/Rar/RarArchiveEntry.cs +++ b/src/SharpCompress/Archives/Rar/RarArchiveEntry.cs @@ -61,16 +61,16 @@ namespace SharpCompress.Archives.Rar { return new RarStream(archive.UnpackV1.Value, FileHeader, new MultiVolumeReadOnlyStream(Parts.Cast(), archive)); } - + return new RarStream(archive.UnpackV2017.Value, FileHeader, new MultiVolumeReadOnlyStream(Parts.Cast(), archive)); } - public bool IsComplete - { - get - { - return parts.Select(fp => fp.FileHeader).Any(fh => !fh.IsSplitAfter); - } + public bool IsComplete + { + get + { + return parts.Select(fp => fp.FileHeader).Any(fh => !fh.IsSplitAfter); + } } private void CheckIncomplete() diff --git a/src/SharpCompress/Archives/Rar/RarArchiveVolumeFactory.cs b/src/SharpCompress/Archives/Rar/RarArchiveVolumeFactory.cs index 882135e0..7f42c89a 100644 --- a/src/SharpCompress/Archives/Rar/RarArchiveVolumeFactory.cs +++ b/src/SharpCompress/Archives/Rar/RarArchiveVolumeFactory.cs @@ -23,7 +23,7 @@ namespace SharpCompress.Archives.Rar yield return part; } } - + internal static IEnumerable GetParts(FileInfo fileInfo, ReaderOptions options) { FileInfoRarArchiveVolume part = new FileInfoRarArchiveVolume(fileInfo, options); diff --git a/src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs b/src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs index 3e21c01b..e4adc151 100644 --- a/src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs +++ b/src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs @@ -131,7 +131,7 @@ namespace SharpCompress.Archives.SevenZip } } - private static ReadOnlySpan SIGNATURE => new byte[] {(byte)'7', (byte)'z', 0xBC, 0xAF, 0x27, 0x1C}; + private static ReadOnlySpan SIGNATURE => new byte[] { (byte)'7', (byte)'z', 0xBC, 0xAF, 0x27, 0x1C }; private static bool SignatureMatch(Stream stream) { diff --git a/src/SharpCompress/Archives/Tar/TarArchive.cs b/src/SharpCompress/Archives/Tar/TarArchive.cs index 9a680738..73607f29 100644 --- a/src/SharpCompress/Archives/Tar/TarArchive.cs +++ b/src/SharpCompress/Archives/Tar/TarArchive.cs @@ -79,7 +79,7 @@ namespace SharpCompress.Archives.Tar } return false; } - + /// /// Constructor with a FileInfo object to an existing file. /// diff --git a/src/SharpCompress/Archives/Zip/ZipArchive.cs b/src/SharpCompress/Archives/Zip/ZipArchive.cs index 88d4219b..9994ccdd 100644 --- a/src/SharpCompress/Archives/Zip/ZipArchive.cs +++ b/src/SharpCompress/Archives/Zip/ZipArchive.cs @@ -24,7 +24,7 @@ namespace SharpCompress.Archives.Zip /// if the compression method is set to deflate /// public CompressionLevel DeflateCompressionLevel { get; set; } - + /// /// Constructor expects a filepath to an existing file. /// @@ -57,7 +57,7 @@ namespace SharpCompress.Archives.Zip stream.CheckNotNull(nameof(stream)); return new ZipArchive(stream, readerOptions ?? new ReaderOptions()); } - + public static bool IsZipFile(string filePath, string? password = null) { return IsZipFile(new FileInfo(filePath), password); @@ -97,7 +97,7 @@ namespace SharpCompress.Archives.Zip return false; } } - + /// /// Constructor with a FileInfo object to an existing file. /// diff --git a/src/SharpCompress/Common/EntryStream.cs b/src/SharpCompress/Common/EntryStream.cs index fe7fd3e7..43ca0537 100644 --- a/src/SharpCompress/Common/EntryStream.cs +++ b/src/SharpCompress/Common/EntryStream.cs @@ -47,7 +47,8 @@ namespace SharpCompress.Common public override bool CanWrite => false; - public override void Flush() { + public override void Flush() + { } public override long Length => _stream.Length; diff --git a/src/SharpCompress/Common/ExtractionMethods.cs b/src/SharpCompress/Common/ExtractionMethods.cs index 0e3492be..738e3f39 100644 --- a/src/SharpCompress/Common/ExtractionMethods.cs +++ b/src/SharpCompress/Common/ExtractionMethods.cs @@ -8,9 +8,9 @@ namespace SharpCompress.Common /// /// Extract to specific directory, retaining filename /// - public static void WriteEntryToDirectory(IEntry entry, + public static void WriteEntryToDirectory(IEntry entry, string destinationDirectory, - ExtractionOptions? options, + ExtractionOptions? options, Action write) { string destinationFileName; @@ -18,9 +18,9 @@ namespace SharpCompress.Common string fullDestinationDirectoryPath = Path.GetFullPath(destinationDirectory); options ??= new ExtractionOptions() - { - Overwrite = true - }; + { + Overwrite = true + }; if (options.ExtractFullPath) { @@ -39,7 +39,7 @@ namespace SharpCompress.Common destinationFileName = Path.Combine(destdir, file); } else - { + { destinationFileName = Path.Combine(fullDestinationDirectoryPath, file); } @@ -59,7 +59,7 @@ namespace SharpCompress.Common Directory.CreateDirectory(destinationFileName); } } - + public static void WriteEntryToFile(IEntry entry, string destinationFileName, ExtractionOptions? options, Action openAndWrite) @@ -76,9 +76,9 @@ namespace SharpCompress.Common { FileMode fm = FileMode.Create; options ??= new ExtractionOptions() - { - Overwrite = true - }; + { + Overwrite = true + }; if (!options.Overwrite) { diff --git a/src/SharpCompress/Common/ExtractionOptions.cs b/src/SharpCompress/Common/ExtractionOptions.cs index ef9848af..54dbe79f 100644 --- a/src/SharpCompress/Common/ExtractionOptions.cs +++ b/src/SharpCompress/Common/ExtractionOptions.cs @@ -7,7 +7,7 @@ namespace SharpCompress.Common /// /// overwrite target if it exists /// - public bool Overwrite {get; set; } + public bool Overwrite { get; set; } /// /// extract with internal directory structure diff --git a/src/SharpCompress/Common/Rar/Headers/AVHeader.cs b/src/SharpCompress/Common/Rar/Headers/AVHeader.cs index eb89804c..44d2b15a 100644 --- a/src/SharpCompress/Common/Rar/Headers/AVHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/AVHeader.cs @@ -4,8 +4,8 @@ namespace SharpCompress.Common.Rar.Headers { internal class AvHeader : RarHeader { - public AvHeader(RarHeader header, RarCrcBinaryReader reader) - : base(header, reader, HeaderType.Av) + public AvHeader(RarHeader header, RarCrcBinaryReader reader) + : base(header, reader, HeaderType.Av) { if (IsRar5) { diff --git a/src/SharpCompress/Common/Rar/Headers/ArchiveCryptHeader.cs b/src/SharpCompress/Common/Rar/Headers/ArchiveCryptHeader.cs index 0d74d678..51cf05b2 100644 --- a/src/SharpCompress/Common/Rar/Headers/ArchiveCryptHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/ArchiveCryptHeader.cs @@ -6,7 +6,7 @@ namespace SharpCompress.Common.Rar.Headers { internal class ArchiveCryptHeader : RarHeader { - + private const int CRYPT_VERSION = 0; // Supported encryption version. private const int SIZE_SALT50 = 16; private const int SIZE_SALT30 = 8; @@ -15,14 +15,14 @@ namespace SharpCompress.Common.Rar.Headers private const int SIZE_PSWCHECK_CSUM = 4; private const int CRYPT5_KDF_LG2_COUNT = 15; // LOG2 of PDKDF2 iteration count. private const int CRYPT5_KDF_LG2_COUNT_MAX = 24; // LOG2 of maximum accepted iteration count. - - + + private bool _usePswCheck; private uint _lg2Count; // Log2 of PBKDF2 repetition count. private byte[] _salt; private byte[] _pswCheck; private byte[] _pswCheckCsm; - + public ArchiveCryptHeader(RarHeader header, RarCrcBinaryReader reader) : base(header, reader, HeaderType.Crypt) { @@ -35,12 +35,12 @@ namespace SharpCompress.Common.Rar.Headers { //error? return; - } + } var encryptionFlags = reader.ReadRarVIntUInt32(); _usePswCheck = FlagUtility.HasFlag(encryptionFlags, EncryptionFlagsV5.CHFL_CRYPT_PSWCHECK); _lg2Count = reader.ReadRarVIntByte(1); - + //UsePswCheck = HasHeaderFlag(EncryptionFlagsV5.CHFL_CRYPT_PSWCHECK); if (_lg2Count > CRYPT5_KDF_LG2_COUNT_MAX) { diff --git a/src/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs b/src/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs index e781bfc2..39249656 100644 --- a/src/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs @@ -4,14 +4,14 @@ namespace SharpCompress.Common.Rar.Headers { internal sealed class ArchiveHeader : RarHeader { - public ArchiveHeader(RarHeader header, RarCrcBinaryReader reader) - : base(header, reader, HeaderType.Archive) + public ArchiveHeader(RarHeader header, RarCrcBinaryReader reader) + : base(header, reader, HeaderType.Archive) { } protected override void ReadFinish(MarkingBinaryReader reader) { - if (IsRar5) + if (IsRar5) { Flags = reader.ReadRarVIntUInt16(); if (HasFlag(ArchiveFlagsV5.HAS_VOLUME_NUMBER)) @@ -22,8 +22,8 @@ namespace SharpCompress.Common.Rar.Headers //if (ExtraSize != 0) { // ReadLocator(reader); //} - } - else + } + else { Flags = HeaderFlags; HighPosAv = reader.ReadInt16(); @@ -35,7 +35,8 @@ namespace SharpCompress.Common.Rar.Headers } } - private void ReadLocator(MarkingBinaryReader reader) { + private void ReadLocator(MarkingBinaryReader reader) + { var size = reader.ReadRarVIntUInt16(); var type = reader.ReadRarVIntUInt16(); if (type != 1) @@ -47,18 +48,20 @@ namespace SharpCompress.Common.Rar.Headers const ushort hasQuickOpenOffset = 0x01; const ushort hasRecoveryOffset = 0x02; ulong quickOpenOffset = 0; - if ((flags & hasQuickOpenOffset) == hasQuickOpenOffset) { + if ((flags & hasQuickOpenOffset) == hasQuickOpenOffset) + { quickOpenOffset = reader.ReadRarVInt(); } ulong recoveryOffset = 0; - if ((flags & hasRecoveryOffset) == hasRecoveryOffset) { + if ((flags & hasRecoveryOffset) == hasRecoveryOffset) + { recoveryOffset = reader.ReadRarVInt(); } } - private ushort Flags { get; set; } + private ushort Flags { get; set; } - private bool HasFlag(ushort flag) + private bool HasFlag(ushort flag) { return (Flags & flag) == flag; } diff --git a/src/SharpCompress/Common/Rar/Headers/CommentHeader.cs b/src/SharpCompress/Common/Rar/Headers/CommentHeader.cs index e03d46a5..00a9cc25 100644 --- a/src/SharpCompress/Common/Rar/Headers/CommentHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/CommentHeader.cs @@ -5,8 +5,8 @@ namespace SharpCompress.Common.Rar.Headers internal class CommentHeader : RarHeader { protected CommentHeader(RarHeader header, RarCrcBinaryReader reader) - : base(header, reader, HeaderType.Comment) - { + : base(header, reader, HeaderType.Comment) + { if (IsRar5) { throw new InvalidFormatException("unexpected rar5 record"); diff --git a/src/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs b/src/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs index 926a8dfe..d993f1d9 100644 --- a/src/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs @@ -4,14 +4,14 @@ namespace SharpCompress.Common.Rar.Headers { internal class EndArchiveHeader : RarHeader { - public EndArchiveHeader(RarHeader header, RarCrcBinaryReader reader) - : base(header, reader, HeaderType.EndArchive) + public EndArchiveHeader(RarHeader header, RarCrcBinaryReader reader) + : base(header, reader, HeaderType.EndArchive) { } protected override void ReadFinish(MarkingBinaryReader reader) { - if (IsRar5) + if (IsRar5) { Flags = reader.ReadRarVIntUInt16(); } @@ -31,7 +31,7 @@ namespace SharpCompress.Common.Rar.Headers private ushort Flags { get; set; } - private bool HasFlag(ushort flag) + private bool HasFlag(ushort flag) { return (Flags & flag) == flag; } diff --git a/src/SharpCompress/Common/Rar/Headers/FileHeader.cs b/src/SharpCompress/Common/Rar/Headers/FileHeader.cs index b5be7c1e..11d7883f 100644 --- a/src/SharpCompress/Common/Rar/Headers/FileHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/FileHeader.cs @@ -21,18 +21,18 @@ namespace SharpCompress.Common.Rar.Headers { private uint _fileCrc; - public FileHeader(RarHeader header, RarCrcBinaryReader reader, HeaderType headerType) - : base(header, reader, headerType) + public FileHeader(RarHeader header, RarCrcBinaryReader reader, HeaderType headerType) + : base(header, reader, headerType) { } - protected override void ReadFinish(MarkingBinaryReader reader) + protected override void ReadFinish(MarkingBinaryReader reader) { - if (IsRar5) + if (IsRar5) { ReadFromReaderV5(reader); - } - else + } + else { ReadFromReaderV4(reader); } @@ -49,11 +49,13 @@ namespace SharpCompress.Common.Rar.Headers FileAttributes = reader.ReadRarVIntUInt32(); - if (HasFlag(FileFlagsV5.HAS_MOD_TIME)) { + if (HasFlag(FileFlagsV5.HAS_MOD_TIME)) + { FileLastModifiedTime = Utility.UnixTimeToDateTime(reader.ReadUInt32()); } - if (HasFlag(FileFlagsV5.HAS_CRC32)) { + if (HasFlag(FileFlagsV5.HAS_CRC32)) + { FileCrc = reader.ReadUInt32(); } @@ -65,7 +67,7 @@ namespace SharpCompress.Common.Rar.Headers // but it was already used in RAR 1.5 and Unpack needs to distinguish // them. CompressionAlgorithm = (byte)((compressionInfo & 0x3f) + 50); - + // 7th bit (0x0040) defines the solid flag. If it is set, RAR continues to use the compression dictionary left after processing preceding files. // It can be set only for file headers and is never set for service headers. IsSolid = (compressionInfo & 0x40) == 0x40; @@ -74,7 +76,7 @@ namespace SharpCompress.Common.Rar.Headers CompressionMethod = (byte)((compressionInfo >> 7) & 0x7); // Bits 11 - 14 (0x3c00) define the minimum size of dictionary size required to extract data. Value 0 means 128 KB, 1 - 256 KB, ..., 14 - 2048 MB, 15 - 4096 MB. - WindowSize = IsDirectory ? 0 : ((size_t)0x20000) << ((compressionInfo>>10) & 0xf); + WindowSize = IsDirectory ? 0 : ((size_t)0x20000) << ((compressionInfo >> 10) & 0xf); HostOs = reader.ReadRarVIntByte(); @@ -101,18 +103,20 @@ namespace SharpCompress.Common.Rar.Headers FileName = ConvertPathV5(Encoding.UTF8.GetString(b, 0, b.Length)); // extra size seems to be redudant since we know the total header size - if (ExtraSize != RemainingHeaderBytes(reader)) + if (ExtraSize != RemainingHeaderBytes(reader)) { throw new InvalidFormatException("rar5 header size / extra size inconsistency"); } isEncryptedRar5 = false; - while (RemainingHeaderBytes(reader) > 0) { + while (RemainingHeaderBytes(reader) > 0) + { var size = reader.ReadRarVIntUInt16(); int n = RemainingHeaderBytes(reader); var type = reader.ReadRarVIntUInt16(); - switch (type) { + switch (type) + { //TODO case 1: // file encryption { @@ -120,7 +124,7 @@ namespace SharpCompress.Common.Rar.Headers //var version = reader.ReadRarVIntByte(); //if (version != 0) throw new InvalidFormatException("unknown encryption algorithm " + version); - } + } break; // case 2: // file hash // { @@ -131,38 +135,41 @@ namespace SharpCompress.Common.Rar.Headers { ushort flags = reader.ReadRarVIntUInt16(); var isWindowsTime = (flags & 1) == 0; - if ((flags & 0x2) == 0x2) { + if ((flags & 0x2) == 0x2) + { FileLastModifiedTime = ReadExtendedTimeV5(reader, isWindowsTime); } - if ((flags & 0x4) == 0x4) { + if ((flags & 0x4) == 0x4) + { FileCreatedTime = ReadExtendedTimeV5(reader, isWindowsTime); } - if ((flags & 0x8) == 0x8) { + if ((flags & 0x8) == 0x8) + { FileLastAccessedTime = ReadExtendedTimeV5(reader, isWindowsTime); } } break; -//TODO -// case 4: // file version -// { -// -// } -// break; -// case 5: // file system redirection -// { -// -// } -// break; -// case 6: // unix owner -// { -// -// } -// break; -// case 7: // service data -// { -// -// } -// break; + //TODO + // case 4: // file version + // { + // + // } + // break; + // case 5: // file system redirection + // { + // + // } + // break; + // case 6: // unix owner + // { + // + // } + // break; + // case 7: // service data + // { + // + // } + // break; default: // skip unknown record types to allow new record types to be added in the future @@ -171,25 +178,26 @@ namespace SharpCompress.Common.Rar.Headers // drain any trailing bytes of extra record int did = n - RemainingHeaderBytes(reader); int drain = size - did; - if (drain > 0) + if (drain > 0) { reader.ReadBytes(drain); } } - if (AdditionalDataSize != 0) { + if (AdditionalDataSize != 0) + { CompressedSize = AdditionalDataSize; } } - private static DateTime ReadExtendedTimeV5(MarkingBinaryReader reader, bool isWindowsTime) + private static DateTime ReadExtendedTimeV5(MarkingBinaryReader reader, bool isWindowsTime) { - if (isWindowsTime) + if (isWindowsTime) { return DateTime.FromFileTime(reader.ReadInt64()); - } - else + } + else { return Utility.UnixTimeToDateTime(reader.ReadUInt32()); } @@ -201,7 +209,7 @@ namespace SharpCompress.Common.Rar.Headers { // replace embedded \\ with valid filename char return path.Replace('\\', '-').Replace('/', '\\'); - } + } return path; } @@ -376,20 +384,22 @@ namespace SharpCompress.Common.Rar.Headers private ushort Flags { get; set; } - private bool HasFlag(ushort flag) + private bool HasFlag(ushort flag) { return (Flags & flag) == flag; } - internal uint FileCrc - { - get { - if (IsRar5 && !HasFlag(FileFlagsV5.HAS_CRC32)) { -//!!! rar5: + internal uint FileCrc + { + get + { + if (IsRar5 && !HasFlag(FileFlagsV5.HAS_CRC32)) + { + //!!! rar5: throw new InvalidOperationException("TODO rar5"); } - return _fileCrc; - } + return _fileCrc; + } private set => _fileCrc = value; } @@ -409,7 +419,7 @@ namespace SharpCompress.Common.Rar.Headers //case 29: // rar 3.x compression //case 50: // RAR 5.0 compression algorithm. internal byte CompressionAlgorithm { get; private set; } - + public bool IsSolid { get; private set; } // unused for UnpackV1 implementation (limitation) @@ -432,8 +442,8 @@ namespace SharpCompress.Common.Rar.Headers public bool IsDirectory => HasFlag(IsRar5 ? FileFlagsV5.DIRECTORY : FileFlagsV4.DIRECTORY); private bool isEncryptedRar5 = false; - public bool IsEncrypted => IsRar5 ? isEncryptedRar5: HasFlag(FileFlagsV4.PASSWORD); - + public bool IsEncrypted => IsRar5 ? isEncryptedRar5 : HasFlag(FileFlagsV4.PASSWORD); + internal DateTime? FileLastModifiedTime { get; private set; } internal DateTime? FileCreatedTime { get; private set; } diff --git a/src/SharpCompress/Common/Rar/Headers/Flags.cs b/src/SharpCompress/Common/Rar/Headers/Flags.cs index 0c19079b..b6457661 100644 --- a/src/SharpCompress/Common/Rar/Headers/Flags.cs +++ b/src/SharpCompress/Common/Rar/Headers/Flags.cs @@ -42,10 +42,10 @@ namespace SharpCompress.Common.Rar.Headers } internal static class EncryptionFlagsV5 - { + { // RAR 5.0 archive encryption header specific flags. public const uint CHFL_CRYPT_PSWCHECK = 0x01; // Password check data is present. - + public const uint FHEXTRA_CRYPT_PSWCHECK = 0x01; // Password check data is present. public const uint FHEXTRA_CRYPT_HASHMAC = 0x02; } diff --git a/src/SharpCompress/Common/Rar/Headers/IRarHeader.cs b/src/SharpCompress/Common/Rar/Headers/IRarHeader.cs index bbc03593..5d3433b7 100644 --- a/src/SharpCompress/Common/Rar/Headers/IRarHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/IRarHeader.cs @@ -1,6 +1,6 @@ namespace SharpCompress.Common.Rar.Headers { - internal interface IRarHeader + internal interface IRarHeader { HeaderType HeaderType { get; } } diff --git a/src/SharpCompress/Common/Rar/Headers/MarkHeader.cs b/src/SharpCompress/Common/Rar/Headers/MarkHeader.cs index 8af80c8c..82b40ad8 100644 --- a/src/SharpCompress/Common/Rar/Headers/MarkHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/MarkHeader.cs @@ -11,39 +11,39 @@ namespace SharpCompress.Common.Rar.Headers public bool IsRar5 { get; } - private MarkHeader(bool isRar5) - { + private MarkHeader(bool isRar5) + { IsRar5 = isRar5; } public HeaderType HeaderType => HeaderType.Mark; - private static byte GetByte(Stream stream) + private static byte GetByte(Stream stream) { var b = stream.ReadByte(); - if (b != -1) + if (b != -1) { return (byte)b; } throw new EndOfStreamException(); } - public static MarkHeader Read(Stream stream, bool leaveStreamOpen, bool lookForHeader) + public static MarkHeader Read(Stream stream, bool leaveStreamOpen, bool lookForHeader) { int maxScanIndex = lookForHeader ? MAX_SFX_SIZE : 0; try { int start = -1; var b = GetByte(stream); start++; - while (start <= maxScanIndex) + while (start <= maxScanIndex) { // Rar old signature: 52 45 7E 5E // Rar4 signature: 52 61 72 21 1A 07 00 // Rar5 signature: 52 61 72 21 1A 07 01 00 - if (b == 0x52) + if (b == 0x52) { b = GetByte(stream); start++; - if (b == 0x61) + if (b == 0x61) { b = GetByte(stream); start++; if (b != 0x72) @@ -70,7 +70,7 @@ namespace SharpCompress.Common.Rar.Headers } b = GetByte(stream); start++; - if (b == 1) + if (b == 1) { b = GetByte(stream); start++; if (b != 0) @@ -79,13 +79,13 @@ namespace SharpCompress.Common.Rar.Headers } return new MarkHeader(true); // Rar5 - } - else if (b == 0) + } + else if (b == 0) { return new MarkHeader(false); // Rar4 - } - } - else if (b == 0x45) + } + } + else if (b == 0x45) { b = GetByte(stream); start++; if (b != 0x7e) @@ -100,9 +100,9 @@ namespace SharpCompress.Common.Rar.Headers } throw new InvalidFormatException("Rar format version pre-4 is unsupported."); - } - } - else + } + } + else { b = GetByte(stream); start++; } diff --git a/src/SharpCompress/Common/Rar/Headers/NewSubHeaderType.cs b/src/SharpCompress/Common/Rar/Headers/NewSubHeaderType.cs index 929c4b5e..5e07c92e 100644 --- a/src/SharpCompress/Common/Rar/Headers/NewSubHeaderType.cs +++ b/src/SharpCompress/Common/Rar/Headers/NewSubHeaderType.cs @@ -4,7 +4,7 @@ namespace SharpCompress.Common.Rar.Headers { internal sealed class NewSubHeaderType : IEquatable { - internal static readonly NewSubHeaderType SUBHEAD_TYPE_CMT = new ('C', 'M', 'T'); + internal static readonly NewSubHeaderType SUBHEAD_TYPE_CMT = new('C', 'M', 'T'); //internal static final NewSubHeaderType SUBHEAD_TYPE_ACL = new (new byte[]{'A','C','L'}); @@ -14,7 +14,7 @@ namespace SharpCompress.Common.Rar.Headers //internal static final NewSubHeaderType SUBHEAD_TYPE_AV = new (new byte[]{'A','V'}); - internal static readonly NewSubHeaderType SUBHEAD_TYPE_RR = new ('R', 'R'); + internal static readonly NewSubHeaderType SUBHEAD_TYPE_RR = new('R', 'R'); //internal static final NewSubHeaderType SUBHEAD_TYPE_OS2EA = new (new byte[]{'E','A','2'}); diff --git a/src/SharpCompress/Common/Rar/Headers/ProtectHeader.cs b/src/SharpCompress/Common/Rar/Headers/ProtectHeader.cs index ac18212d..27d5297b 100644 --- a/src/SharpCompress/Common/Rar/Headers/ProtectHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/ProtectHeader.cs @@ -5,8 +5,8 @@ namespace SharpCompress.Common.Rar.Headers // ProtectHeader is part of the Recovery Record feature internal sealed class ProtectHeader : RarHeader { - public ProtectHeader(RarHeader header, RarCrcBinaryReader reader) - : base(header, reader, HeaderType.Protect) + public ProtectHeader(RarHeader header, RarCrcBinaryReader reader) + : base(header, reader, HeaderType.Protect) { if (IsRar5) { diff --git a/src/SharpCompress/Common/Rar/Headers/RarHeader.cs b/src/SharpCompress/Common/Rar/Headers/RarHeader.cs index 20737f53..cb58b51e 100644 --- a/src/SharpCompress/Common/Rar/Headers/RarHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/RarHeader.cs @@ -23,12 +23,12 @@ namespace SharpCompress.Common.Rar.Headers } } - private RarHeader(RarCrcBinaryReader reader, bool isRar5, ArchiveEncoding archiveEncoding) + private RarHeader(RarCrcBinaryReader reader, bool isRar5, ArchiveEncoding archiveEncoding) { _headerType = HeaderType.Null; _isRar5 = isRar5; ArchiveEncoding = archiveEncoding; - if (IsRar5) + if (IsRar5) { HeaderCrc = reader.ReadUInt32(); reader.ResetCrc(); @@ -45,7 +45,9 @@ namespace SharpCompress.Common.Rar.Headers { AdditionalDataSize = (long)reader.ReadRarVInt(); } - } else { + } + else + { reader.Mark(); HeaderCrc = reader.ReadUInt16(); reader.ResetCrc(); @@ -59,7 +61,8 @@ namespace SharpCompress.Common.Rar.Headers } } - protected RarHeader(RarHeader header, RarCrcBinaryReader reader, HeaderType headerType) { + protected RarHeader(RarHeader header, RarCrcBinaryReader reader, HeaderType headerType) + { _headerType = headerType; _isRar5 = header.IsRar5; HeaderCrc = header.HeaderCrc; @@ -80,7 +83,8 @@ namespace SharpCompress.Common.Rar.Headers VerifyHeaderCrc(reader.GetCrc32()); } - protected int RemainingHeaderBytes(MarkingBinaryReader reader) { + protected int RemainingHeaderBytes(MarkingBinaryReader reader) + { return checked(HeaderSize - (int)reader.CurrentReadByteCount); } @@ -108,7 +112,7 @@ namespace SharpCompress.Common.Rar.Headers protected ushort HeaderFlags { get; } - protected bool HasHeaderFlag(ushort flag) + protected bool HasHeaderFlag(ushort flag) { return (HeaderFlags & flag) == flag; } diff --git a/src/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs b/src/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs index 2b510457..6c8d5686 100644 --- a/src/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs +++ b/src/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs @@ -41,11 +41,11 @@ namespace SharpCompress.Common.Rar.Headers private RarHeader? TryReadNextHeader(Stream stream) { RarCrcBinaryReader reader; - if (!IsEncrypted) + if (!IsEncrypted) { reader = new RarCrcBinaryReader(stream); - } - else + } + else { if (Options.Password is null) { @@ -65,7 +65,7 @@ namespace SharpCompress.Common.Rar.Headers case HeaderCodeV.RAR4_ARCHIVE_HEADER: { var ah = new ArchiveHeader(header, reader); - if (ah.IsEncrypted == true) + if (ah.IsEncrypted == true) { //!!! rar5 we don't know yet IsEncrypted = true; @@ -150,11 +150,11 @@ namespace SharpCompress.Common.Rar.Headers return new EndArchiveHeader(header, reader); } case HeaderCodeV.RAR5_ARCHIVE_ENCRYPTION_HEADER: - { - var ch = new ArchiveCryptHeader(header, reader); - IsEncrypted = true; - return ch; - } + { + var ch = new ArchiveCryptHeader(header, reader); + IsEncrypted = true; + return ch; + } default: { throw new InvalidFormatException("Unknown Rar Header: " + header.HeaderCode); @@ -162,21 +162,26 @@ namespace SharpCompress.Common.Rar.Headers } } - private void SkipData(FileHeader fh, RarCrcBinaryReader reader) { - switch (StreamingMode) { - case StreamingMode.Seekable: { - fh.DataStartPosition = reader.BaseStream.Position; - reader.BaseStream.Position += fh.CompressedSize; - } + private void SkipData(FileHeader fh, RarCrcBinaryReader reader) + { + switch (StreamingMode) + { + case StreamingMode.Seekable: + { + fh.DataStartPosition = reader.BaseStream.Position; + reader.BaseStream.Position += fh.CompressedSize; + } break; - case StreamingMode.Streaming: { - //skip the data because it's useless? - reader.BaseStream.Skip(fh.CompressedSize); - } + case StreamingMode.Streaming: + { + //skip the data because it's useless? + reader.BaseStream.Skip(fh.CompressedSize); + } break; - default: { - throw new InvalidFormatException("Invalid StreamingMode"); - } + default: + { + throw new InvalidFormatException("Invalid StreamingMode"); + } } } } diff --git a/src/SharpCompress/Common/Rar/Headers/SignHeader.cs b/src/SharpCompress/Common/Rar/Headers/SignHeader.cs index 3b95f6af..b45c76b2 100644 --- a/src/SharpCompress/Common/Rar/Headers/SignHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/SignHeader.cs @@ -5,8 +5,8 @@ namespace SharpCompress.Common.Rar.Headers internal class SignHeader : RarHeader { protected SignHeader(RarHeader header, RarCrcBinaryReader reader) - : base(header, reader, HeaderType.Sign) - { + : base(header, reader, HeaderType.Sign) + { if (IsRar5) { throw new InvalidFormatException("unexpected rar5 record"); diff --git a/src/SharpCompress/Common/Rar/RarEntry.cs b/src/SharpCompress/Common/Rar/RarEntry.cs index e7e3570c..623bc9bf 100644 --- a/src/SharpCompress/Common/Rar/RarEntry.cs +++ b/src/SharpCompress/Common/Rar/RarEntry.cs @@ -11,7 +11,7 @@ namespace SharpCompress.Common.Rar /// As the V2017 port isn't complete, add this check to use the legacy Rar code. /// internal bool IsRarV3 => FileHeader.CompressionAlgorithm == 29 || FileHeader.CompressionAlgorithm == 36; - + /// /// The File's 32 bit CRC Hash /// diff --git a/src/SharpCompress/Common/Rar/RarRijndael.cs b/src/SharpCompress/Common/Rar/RarRijndael.cs index 6d09fe27..44531159 100644 --- a/src/SharpCompress/Common/Rar/RarRijndael.cs +++ b/src/SharpCompress/Common/Rar/RarRijndael.cs @@ -27,13 +27,13 @@ namespace SharpCompress.Common.Rar _rijndael = new RijndaelEngine(); _aesInitializationVector = new byte[CRYPTO_BLOCK_SIZE]; - int rawLength = 2*_password.Length; + int rawLength = 2 * _password.Length; byte[] rawPassword = new byte[rawLength + 8]; byte[] passwordBytes = Encoding.UTF8.GetBytes(_password); for (int i = 0; i < _password.Length; i++) { - rawPassword[i*2] = passwordBytes[i]; - rawPassword[i*2 + 1] = 0; + rawPassword[i * 2] = passwordBytes[i]; + rawPassword[i * 2 + 1] = 0; } for (int i = 0; i < _salt.Length; i++) { @@ -68,11 +68,11 @@ namespace SharpCompress.Common.Rar { for (int j = 0; j < 4; j++) { - aesKey[i*4 + j] = (byte) - (((digest[i*4]*0x1000000) & 0xff000000 | - (uint) ((digest[i*4 + 1]*0x10000) & 0xff0000) | - (uint) ((digest[i*4 + 2]*0x100) & 0xff00) | - (uint) (digest[i*4 + 3] & 0xff)) >> (j*8)); + aesKey[i * 4 + j] = (byte) + (((digest[i * 4] * 0x1000000) & 0xff000000 | + (uint)((digest[i * 4 + 1] * 0x10000) & 0xff0000) | + (uint)((digest[i * 4 + 2] * 0x100) & 0xff00) | + (uint)(digest[i * 4 + 3] & 0xff)) >> (j * 8)); } } diff --git a/src/SharpCompress/Common/Rar/RarVolume.cs b/src/SharpCompress/Common/Rar/RarVolume.cs index 4b47b8ee..6a4628ac 100644 --- a/src/SharpCompress/Common/Rar/RarVolume.cs +++ b/src/SharpCompress/Common/Rar/RarVolume.cs @@ -39,20 +39,20 @@ namespace SharpCompress.Common.Rar switch (header.HeaderType) { case HeaderType.Mark: - { - lastMarkHeader = (MarkHeader)header; - } + { + lastMarkHeader = (MarkHeader)header; + } break; case HeaderType.Archive: - { - ArchiveHeader = (ArchiveHeader)header; - } + { + ArchiveHeader = (ArchiveHeader)header; + } break; case HeaderType.File: - { - var fh = (FileHeader)header; - yield return CreateFilePart(lastMarkHeader!, fh); - } + { + var fh = (FileHeader)header; + yield return CreateFilePart(lastMarkHeader!, fh); + } break; } } diff --git a/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs b/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs index b5f24106..2722bf55 100644 --- a/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs +++ b/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs @@ -89,7 +89,7 @@ namespace SharpCompress.Common.SevenZip { // v3.13 incorrectly worked with empty folders // v4.07: Loop for skipping empty folders - for (;;) + for (; ; ) { if (folderIndex >= _folders.Count) { diff --git a/src/SharpCompress/Common/SevenZip/ArchiveReader.cs b/src/SharpCompress/Common/SevenZip/ArchiveReader.cs index 56a6581f..1ef60c0c 100644 --- a/src/SharpCompress/Common/SevenZip/ArchiveReader.cs +++ b/src/SharpCompress/Common/SevenZip/ArchiveReader.cs @@ -90,7 +90,7 @@ namespace SharpCompress.Common.SevenZip private void WaitAttribute(BlockType attribute) { - for (;;) + for (; ; ) { BlockType? type = ReadId(); if (type == attribute) @@ -452,7 +452,7 @@ namespace SharpCompress.Common.SevenZip #endif BlockType? type; - for (;;) + for (; ; ) { type = ReadId(); if (type == BlockType.End) @@ -508,7 +508,7 @@ namespace SharpCompress.Common.SevenZip int index = 0; for (int i = 0; i < numFolders; i++) { - var f = new CFolder {_firstPackStreamId = index}; + var f = new CFolder { _firstPackStreamId = index }; folders.Add(f); GetNextFolderItem(f); index += f._packStreams.Count; @@ -539,7 +539,7 @@ namespace SharpCompress.Common.SevenZip #endif } - for (;;) + for (; ; ) { BlockType? type = ReadId(); if (type == BlockType.End) @@ -580,7 +580,7 @@ namespace SharpCompress.Common.SevenZip numUnpackStreamsInFolders = null; BlockType? type; - for (;;) + for (; ; ) { type = ReadId(); if (type == BlockType.NumUnpackStream) @@ -672,7 +672,7 @@ namespace SharpCompress.Common.SevenZip digests = null; - for (;;) + for (; ; ) { if (type == BlockType.Crc) { @@ -755,7 +755,7 @@ namespace SharpCompress.Common.SevenZip unpackSizes = null; digests = null; - for (;;) + for (; ; ) { switch (ReadId()) { @@ -926,7 +926,7 @@ namespace SharpCompress.Common.SevenZip BitVector antiFileVector = null; int numEmptyStreams = 0; - for (;;) + for (; ; ) { type = ReadId(); if (type == BlockType.End) @@ -961,7 +961,7 @@ namespace SharpCompress.Common.SevenZip #if DEBUG Log.Write("WinAttributes:"); #endif - ReadAttributeVector(dataVector, numFiles, delegate(int i, uint? attr) + ReadAttributeVector(dataVector, numFiles, delegate (int i, uint? attr) { // Some third party implementations established an unofficial extension // of the 7z archive format by placing posix file attributes in the high @@ -1049,7 +1049,7 @@ namespace SharpCompress.Common.SevenZip #if DEBUG Log.Write("StartPos:"); #endif - ReadNumberVector(dataVector, numFiles, delegate(int i, long? startPos) + ReadNumberVector(dataVector, numFiles, delegate (int i, long? startPos) { db._files[i].StartPos = startPos; #if DEBUG @@ -1064,7 +1064,7 @@ namespace SharpCompress.Common.SevenZip #if DEBUG Log.Write("CTime:"); #endif - ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) + ReadDateTimeVector(dataVector, numFiles, delegate (int i, DateTime? time) { db._files[i].CTime = time; #if DEBUG @@ -1079,7 +1079,7 @@ namespace SharpCompress.Common.SevenZip #if DEBUG Log.Write("ATime:"); #endif - ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) + ReadDateTimeVector(dataVector, numFiles, delegate (int i, DateTime? time) { db._files[i].ATime = time; #if DEBUG @@ -1094,7 +1094,7 @@ namespace SharpCompress.Common.SevenZip #if DEBUG Log.Write("MTime:"); #endif - ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) + ReadDateTimeVector(dataVector, numFiles, delegate (int i, DateTime? time) { db._files[i].MTime = time; #if DEBUG @@ -1485,7 +1485,7 @@ namespace SharpCompress.Common.SevenZip int numItems = allFilesMode ? db._files.Count : indices.Length; - + if (numItems == 0) { return; @@ -1554,7 +1554,7 @@ namespace SharpCompress.Common.SevenZip Stream s = DecoderStreamHelper.CreateDecoderStream(_stream, folderStartPackPos, packSizes, folderInfo, db.PasswordProvider); byte[] buffer = new byte[4 << 10]; - for (;;) + for (; ; ) { int processed = s.Read(buffer, 0, buffer.Length); if (processed == 0) diff --git a/src/SharpCompress/Common/SevenZip/DataReader.cs b/src/SharpCompress/Common/SevenZip/DataReader.cs index 910814d6..48fcd099 100644 --- a/src/SharpCompress/Common/SevenZip/DataReader.cs +++ b/src/SharpCompress/Common/SevenZip/DataReader.cs @@ -161,7 +161,7 @@ namespace SharpCompress.Common.SevenZip { int ending = Offset; - for (;;) + for (; ; ) { if (ending + 2 > _ending) { diff --git a/src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs b/src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs index cd22ffc9..612a89d0 100644 --- a/src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs +++ b/src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs @@ -84,20 +84,20 @@ namespace SharpCompress.Common.SevenZip { var coder = Folder!._coders.First(); switch (coder._methodId._id) - { + { case K_LZMA: case K_LZMA2: - { - return CompressionType.LZMA; - } + { + return CompressionType.LZMA; + } case K_PPMD: - { - return CompressionType.PPMd; - } + { + return CompressionType.PPMd; + } case K_B_ZIP2: - { - return CompressionType.BZip2; - } + { + return CompressionType.BZip2; + } default: throw new NotImplementedException(); } diff --git a/src/SharpCompress/Common/Tar/Headers/TarHeader.cs b/src/SharpCompress/Common/Tar/Headers/TarHeader.cs index b04b0b2c..9d7c052f 100644 --- a/src/SharpCompress/Common/Tar/Headers/TarHeader.cs +++ b/src/SharpCompress/Common/Tar/Headers/TarHeader.cs @@ -261,9 +261,9 @@ namespace SharpCompress.Common.Tar.Headers } - private static readonly byte[] eightSpaces = { + private static readonly byte[] eightSpaces = { (byte)' ', (byte)' ', (byte)' ', (byte)' ', - (byte)' ', (byte)' ', (byte)' ', (byte)' ' + (byte)' ', (byte)' ', (byte)' ', (byte)' ' }; internal static int RecalculateChecksum(byte[] buf) diff --git a/src/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs b/src/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs index f46dc1de..54553c81 100644 --- a/src/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs +++ b/src/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs @@ -32,7 +32,7 @@ namespace SharpCompress.Common.Zip.Headers byte[] name = reader.ReadBytes(nameLength); byte[] extra = reader.ReadBytes(extraLength); byte[] comment = reader.ReadBytes(commentLength); - + // According to .ZIP File Format Specification // // For example: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT @@ -40,7 +40,7 @@ namespace SharpCompress.Common.Zip.Headers // Bit 11: Language encoding flag (EFS). If this bit is set, // the filename and comment fields for this file // MUST be encoded using UTF-8. (see APPENDIX D) - + if (Flags.HasFlag(HeaderFlags.Efs)) { Name = ArchiveEncoding.DecodeUTF8(name); diff --git a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs index 36a1a93d..1cd15649 100644 --- a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs +++ b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs @@ -24,7 +24,7 @@ namespace SharpCompress.Common.Zip.Headers ushort extraLength = reader.ReadUInt16(); byte[] name = reader.ReadBytes(nameLength); byte[] extra = reader.ReadBytes(extraLength); - + // According to .ZIP File Format Specification // // For example: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT @@ -32,7 +32,7 @@ namespace SharpCompress.Common.Zip.Headers // Bit 11: Language encoding flag (EFS). If this bit is set, // the filename and comment fields for this file // MUST be encoded using UTF-8. (see APPENDIX D) - + if (Flags.HasFlag(HeaderFlags.Efs)) { Name = ArchiveEncoding.DecodeUTF8(name); @@ -41,7 +41,7 @@ namespace SharpCompress.Common.Zip.Headers { Name = ArchiveEncoding.Decode(name); } - + LoadExtra(extra); var unicodePathExtra = Extra.FirstOrDefault(u => u.Type == ExtraDataType.UnicodePathExtraField); diff --git a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs index 4053809a..f884cc54 100644 --- a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs +++ b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs @@ -36,7 +36,7 @@ namespace SharpCompress.Common.Zip.Headers : base(type, length, dataBytes) { } - + internal byte Version => DataBytes[0]; internal byte[] NameCrc32 @@ -115,7 +115,7 @@ namespace SharpCompress.Common.Zip.Headers VolumeNumber = BinaryPrimitives.ReadUInt32LittleEndian(DataBytes.AsSpan(24)); return; default: - throw new ArchiveException("Unexpected size of of Zip64 extended information extra field"); + throw new ArchiveException("Unexpected size of of Zip64 extended information extra field"); } } diff --git a/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs b/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs index 6e891b95..4021f957 100644 --- a/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs +++ b/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs @@ -7,7 +7,7 @@ namespace SharpCompress.Common.Zip internal class PkwareTraditionalEncryptionData { private static readonly CRC32 CRC32 = new CRC32(); - private readonly UInt32[] _keys = {0x12345678, 0x23456789, 0x34567890}; + private readonly UInt32[] _keys = { 0x12345678, 0x23456789, 0x34567890 }; private readonly ArchiveEncoding _archiveEncoding; private PkwareTraditionalEncryptionData(string password, ArchiveEncoding archiveEncoding) diff --git a/src/SharpCompress/Common/Zip/StreamingZipFilePart.cs b/src/SharpCompress/Common/Zip/StreamingZipFilePart.cs index dca46fdb..f94413f9 100644 --- a/src/SharpCompress/Common/Zip/StreamingZipFilePart.cs +++ b/src/SharpCompress/Common/Zip/StreamingZipFilePart.cs @@ -42,7 +42,7 @@ namespace SharpCompress.Common.Zip if (Header.HasData && !Skipped) { _decompressionStream ??= GetCompressedStream(); - + _decompressionStream.Skip(); if (_decompressionStream is DeflateStream deflateStream) diff --git a/src/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs b/src/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs index e37da40a..59953e53 100644 --- a/src/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs +++ b/src/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs @@ -57,11 +57,11 @@ namespace SharpCompress.Common.Zip var local_header = ((LocalEntryHeader)header); // If we have CompressedSize, there is data to be read - if( local_header.CompressedSize > 0 ) + if (local_header.CompressedSize > 0) { header.HasData = true; } // Check if zip is streaming ( Length is 0 and is declared in PostDataDescriptor ) - else if( local_header.Flags.HasFlag(HeaderFlags.UsePostDataDescriptor) ) + else if (local_header.Flags.HasFlag(HeaderFlags.UsePostDataDescriptor)) { bool isRecording = rewindableStream.IsRecording; if (!isRecording) diff --git a/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs b/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs index 4c0a2c32..e893adde 100644 --- a/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs +++ b/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs @@ -33,8 +33,10 @@ namespace SharpCompress.Common.Zip private int KeySizeInBytes { - get { return KeyLengthInBytes(_keySize); -} + get + { + return KeyLengthInBytes(_keySize); + } } internal static int KeyLengthInBytes(WinzipAesKeySize keySize) diff --git a/src/SharpCompress/Common/Zip/ZipEntry.cs b/src/SharpCompress/Common/Zip/ZipEntry.cs index b8e78224..d82335b5 100644 --- a/src/SharpCompress/Common/Zip/ZipEntry.cs +++ b/src/SharpCompress/Common/Zip/ZipEntry.cs @@ -27,33 +27,33 @@ namespace SharpCompress.Common.Zip switch (_filePart.Header.CompressionMethod) { case ZipCompressionMethod.BZip2: - { - return CompressionType.BZip2; - } + { + return CompressionType.BZip2; + } case ZipCompressionMethod.Deflate: - { - return CompressionType.Deflate; - } + { + return CompressionType.Deflate; + } case ZipCompressionMethod.Deflate64: - { - return CompressionType.Deflate64; - } + { + return CompressionType.Deflate64; + } case ZipCompressionMethod.LZMA: - { - return CompressionType.LZMA; - } + { + return CompressionType.LZMA; + } case ZipCompressionMethod.PPMd: - { - return CompressionType.PPMd; - } + { + return CompressionType.PPMd; + } case ZipCompressionMethod.None: - { - return CompressionType.None; - } + { + return CompressionType.None; + } default: - { - return CompressionType.Unknown; - } + { + return CompressionType.Unknown; + } } } } diff --git a/src/SharpCompress/Common/Zip/ZipFilePart.cs b/src/SharpCompress/Common/Zip/ZipFilePart.cs index 0c5d78e6..6176bccf 100644 --- a/src/SharpCompress/Common/Zip/ZipFilePart.cs +++ b/src/SharpCompress/Common/Zip/ZipFilePart.cs @@ -60,72 +60,72 @@ namespace SharpCompress.Common.Zip switch (method) { case ZipCompressionMethod.None: - { - return stream; - } + { + return stream; + } case ZipCompressionMethod.Deflate: - { - return new DeflateStream(stream, CompressionMode.Decompress); - } + { + return new DeflateStream(stream, CompressionMode.Decompress); + } case ZipCompressionMethod.Deflate64: - { - return new Deflate64Stream(stream, CompressionMode.Decompress); - } + { + return new Deflate64Stream(stream, CompressionMode.Decompress); + } case ZipCompressionMethod.BZip2: - { - return new BZip2Stream(stream, CompressionMode.Decompress, false); - } + { + return new BZip2Stream(stream, CompressionMode.Decompress, false); + } case ZipCompressionMethod.LZMA: - { - if (FlagUtility.HasFlag(Header.Flags, HeaderFlags.Encrypted)) { - throw new NotSupportedException("LZMA with pkware encryption."); + if (FlagUtility.HasFlag(Header.Flags, HeaderFlags.Encrypted)) + { + throw new NotSupportedException("LZMA with pkware encryption."); + } + var reader = new BinaryReader(stream); + reader.ReadUInt16(); //LZMA version + var props = new byte[reader.ReadUInt16()]; + reader.Read(props, 0, props.Length); + return new LzmaStream(props, stream, + Header.CompressedSize > 0 ? Header.CompressedSize - 4 - props.Length : -1, + FlagUtility.HasFlag(Header.Flags, HeaderFlags.Bit1) + ? -1 + : (long)Header.UncompressedSize); } - var reader = new BinaryReader(stream); - reader.ReadUInt16(); //LZMA version - var props = new byte[reader.ReadUInt16()]; - reader.Read(props, 0, props.Length); - return new LzmaStream(props, stream, - Header.CompressedSize > 0 ? Header.CompressedSize - 4 - props.Length : -1, - FlagUtility.HasFlag(Header.Flags, HeaderFlags.Bit1) - ? -1 - : (long)Header.UncompressedSize); - } case ZipCompressionMethod.PPMd: - { - var props = new byte[2]; - stream.ReadFully(props); - return new PpmdStream(new PpmdProperties(props), stream, false); - } + { + var props = new byte[2]; + stream.ReadFully(props); + return new PpmdStream(new PpmdProperties(props), stream, false); + } case ZipCompressionMethod.WinzipAes: - { - ExtraData data = Header.Extra.Where(x => x.Type == ExtraDataType.WinZipAes).SingleOrDefault(); - if (data is null) { - throw new InvalidFormatException("No Winzip AES extra data found."); - } - if (data.Length != 7) - { - throw new InvalidFormatException("Winzip data length is not 7."); - } - ushort compressedMethod = BinaryPrimitives.ReadUInt16LittleEndian(data.DataBytes); + ExtraData data = Header.Extra.Where(x => x.Type == ExtraDataType.WinZipAes).SingleOrDefault(); + if (data is null) + { + throw new InvalidFormatException("No Winzip AES extra data found."); + } + if (data.Length != 7) + { + throw new InvalidFormatException("Winzip data length is not 7."); + } + ushort compressedMethod = BinaryPrimitives.ReadUInt16LittleEndian(data.DataBytes); - if (compressedMethod != 0x01 && compressedMethod != 0x02) - { - throw new InvalidFormatException("Unexpected vendor version number for WinZip AES metadata"); - } + if (compressedMethod != 0x01 && compressedMethod != 0x02) + { + throw new InvalidFormatException("Unexpected vendor version number for WinZip AES metadata"); + } - ushort vendorId = BinaryPrimitives.ReadUInt16LittleEndian(data.DataBytes.AsSpan(2)); - if (vendorId != 0x4541) - { - throw new InvalidFormatException("Unexpected vendor ID for WinZip AES metadata"); + ushort vendorId = BinaryPrimitives.ReadUInt16LittleEndian(data.DataBytes.AsSpan(2)); + if (vendorId != 0x4541) + { + throw new InvalidFormatException("Unexpected vendor ID for WinZip AES metadata"); + } + return CreateDecompressionStream(stream, (ZipCompressionMethod)BinaryPrimitives.ReadUInt16LittleEndian(data.DataBytes.AsSpan(5))); } - return CreateDecompressionStream(stream, (ZipCompressionMethod)BinaryPrimitives.ReadUInt16LittleEndian(data.DataBytes.AsSpan(5))); - } default: - { - throw new NotSupportedException("CompressionMethod: " + Header.CompressionMethod); - } + { + throw new NotSupportedException("CompressionMethod: " + Header.CompressionMethod); + } } } @@ -159,23 +159,23 @@ namespace SharpCompress.Common.Zip case ZipCompressionMethod.BZip2: case ZipCompressionMethod.LZMA: case ZipCompressionMethod.PPMd: - { - return new PkwareTraditionalCryptoStream(plainStream, Header.ComposeEncryptionData(plainStream), CryptoMode.Decrypt); - } + { + return new PkwareTraditionalCryptoStream(plainStream, Header.ComposeEncryptionData(plainStream), CryptoMode.Decrypt); + } case ZipCompressionMethod.WinzipAes: - { - if (Header.WinzipAesEncryptionData != null) { - return new WinzipAesCryptoStream(plainStream, Header.WinzipAesEncryptionData, Header.CompressedSize - 10); + if (Header.WinzipAesEncryptionData != null) + { + return new WinzipAesCryptoStream(plainStream, Header.WinzipAesEncryptionData, Header.CompressedSize - 10); + } + return plainStream; } - return plainStream; - } default: - { - throw new ArgumentOutOfRangeException(); - } + { + throw new ArgumentOutOfRangeException(); + } } } diff --git a/src/SharpCompress/Common/Zip/ZipHeaderFactory.cs b/src/SharpCompress/Common/Zip/ZipHeaderFactory.cs index 37612e0f..3e67e5af 100644 --- a/src/SharpCompress/Common/Zip/ZipHeaderFactory.cs +++ b/src/SharpCompress/Common/Zip/ZipHeaderFactory.cs @@ -35,20 +35,20 @@ namespace SharpCompress.Common.Zip switch (headerBytes) { case ENTRY_HEADER_BYTES: - { - var entryHeader = new LocalEntryHeader(_archiveEncoding); - entryHeader.Read(reader); - LoadHeader(entryHeader, reader.BaseStream); + { + var entryHeader = new LocalEntryHeader(_archiveEncoding); + entryHeader.Read(reader); + LoadHeader(entryHeader, reader.BaseStream); - _lastEntryHeader = entryHeader; - return entryHeader; - } + _lastEntryHeader = entryHeader; + return entryHeader; + } case DIRECTORY_START_HEADER_BYTES: - { - var entry = new DirectoryEntryHeader(_archiveEncoding); - entry.Read(reader); - return entry; - } + { + var entry = new DirectoryEntryHeader(_archiveEncoding); + entry.Read(reader); + return entry; + } case POST_DATA_DESCRIPTOR: { if (FlagUtility.HasFlag(_lastEntryHeader!.Flags, HeaderFlags.UsePostDataDescriptor)) diff --git a/src/SharpCompress/Compressors/Deflate/Inflate.cs b/src/SharpCompress/Compressors/Deflate/Inflate.cs index 863f999f..a0672f28 100644 --- a/src/SharpCompress/Compressors/Deflate/Inflate.cs +++ b/src/SharpCompress/Compressors/Deflate/Inflate.cs @@ -74,7 +74,7 @@ namespace SharpCompress.Compressors.Deflate private const int MANY = 1440; // Table for deflate from PKZIP's appnote.txt. - internal static readonly int[] border = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + internal static readonly int[] border = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; internal ZlibCodec _codec; // pointer back to this zlib stream internal int[] bb = new int[1]; // bit length tree depth @@ -561,35 +561,35 @@ namespace SharpCompress.Compressors.Deflate } tb[0] = -1; - { - var bl = new[] {9}; // must be <= 9 for lookahead assumptions - var bd = new[] {6}; // must be <= 9 for lookahead assumptions - var tl = new int[1]; - var td = new int[1]; - - t = table; - t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, - td, hufts, _codec); - - if (t != ZlibConstants.Z_OK) { - if (t == ZlibConstants.Z_DATA_ERROR) - { - blens = null; - mode = InflateBlockMode.BAD; - } - r = t; + var bl = new[] { 9 }; // must be <= 9 for lookahead assumptions + var bd = new[] { 6 }; // must be <= 9 for lookahead assumptions + var tl = new int[1]; + var td = new int[1]; - bitb = b; - bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - writeAt = q; - return Flush(r); + t = table; + t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, + td, hufts, _codec); + + if (t != ZlibConstants.Z_OK) + { + if (t == ZlibConstants.Z_DATA_ERROR) + { + blens = null; + mode = InflateBlockMode.BAD; + } + r = t; + + bitb = b; + bitk = k; + _codec.AvailableBytesIn = n; + _codec.TotalBytesIn += p - _codec.NextIn; + _codec.NextIn = p; + writeAt = q; + return Flush(r); + } + codes.Init(bl[0], bd[0], hufts, tl[0], hufts, td[0]); } - codes.Init(bl[0], bd[0], hufts, tl[0], hufts, td[0]); - } mode = InflateBlockMode.CODES; goto case InflateBlockMode.CODES; @@ -1567,7 +1567,7 @@ namespace SharpCompress.Compressors.Deflate private const int PRESET_DICT = 0x20; private const int Z_DEFLATED = 8; - private static readonly byte[] mark = {0, 0, 0xff, 0xff}; + private static readonly byte[] mark = { 0, 0, 0xff, 0xff }; internal ZlibCodec _codec; // pointer back to this zlib stream internal InflateBlocks blocks; // current inflate_blocks state diff --git a/src/SharpCompress/Compressors/Deflate/Zlib.cs b/src/SharpCompress/Compressors/Deflate/Zlib.cs index 6133feb4..434845ae 100644 --- a/src/SharpCompress/Compressors/Deflate/Zlib.cs +++ b/src/SharpCompress/Compressors/Deflate/Zlib.cs @@ -374,7 +374,7 @@ namespace SharpCompress.Compressors.Deflate }; // extra bits for each bit length code - internal static readonly int[] extra_blbits = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; + internal static readonly int[] extra_blbits = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 }; internal static readonly StaticTree Literals; internal static readonly StaticTree Distances; diff --git a/src/SharpCompress/Compressors/Deflate/ZlibConstants.cs b/src/SharpCompress/Compressors/Deflate/ZlibConstants.cs index 46dc62ee..a6780614 100644 --- a/src/SharpCompress/Compressors/Deflate/ZlibConstants.cs +++ b/src/SharpCompress/Compressors/Deflate/ZlibConstants.cs @@ -111,7 +111,7 @@ namespace SharpCompress.Compressors.Deflate /// /// The size of the working buffer used in the ZlibCodec class. Defaults to 8192 bytes. /// -#if NETCF +#if NETCF public const int WorkingBufferSizeDefault = 8192; #else public const int WorkingBufferSizeDefault = 16384; diff --git a/src/SharpCompress/Compressors/Deflate64/InflaterManaged.cs b/src/SharpCompress/Compressors/Deflate64/InflaterManaged.cs index 56ce8dd3..de9b78d5 100644 --- a/src/SharpCompress/Compressors/Deflate64/InflaterManaged.cs +++ b/src/SharpCompress/Compressors/Deflate64/InflaterManaged.cs @@ -114,7 +114,7 @@ namespace SharpCompress.Compressors.Deflate64 private void Reset() { _state = //_hasFormatReader ? - //InflaterState.ReadingHeader : // start by reading Header info + //InflaterState.ReadingHeader : // start by reading Header info InflaterState.ReadingBFinal; // start by reading BFinal bit } @@ -294,7 +294,7 @@ namespace SharpCompress.Compressors.Deflate64 //if (_hasFormatReader) // _state = InflaterState.StartReadingFooter; //else - _state = InflaterState.Done; + _state = InflaterState.Done; } return result; } diff --git a/src/SharpCompress/Compressors/Deflate64/OutputWindow.cs b/src/SharpCompress/Compressors/Deflate64/OutputWindow.cs index 2dbc4442..13bf90c2 100644 --- a/src/SharpCompress/Compressors/Deflate64/OutputWindow.cs +++ b/src/SharpCompress/Compressors/Deflate64/OutputWindow.cs @@ -38,14 +38,14 @@ namespace SharpCompress.Compressors.Deflate64 public void WriteLengthDistance(int length, int distance) { Debug.Assert((_bytesUsed + length) <= WINDOW_SIZE, "No Enough space"); - + // move backwards distance bytes in the output stream, // and copy length bytes from this position to the output stream. _bytesUsed += length; int copyStart = (_end - distance) & WINDOW_MASK; // start position for coping. int border = WINDOW_SIZE - length; - if (copyStart <= border && _end < border) + if (copyStart <= border && _end < border) { if (length <= distance) { diff --git a/src/SharpCompress/Compressors/Filters/BCJFilter.cs b/src/SharpCompress/Compressors/Filters/BCJFilter.cs index 3caa492b..4bc6bb2e 100644 --- a/src/SharpCompress/Compressors/Filters/BCJFilter.cs +++ b/src/SharpCompress/Compressors/Filters/BCJFilter.cs @@ -4,9 +4,9 @@ namespace SharpCompress.Compressors.Filters { internal class BCJFilter : Filter { - private static readonly bool[] MASK_TO_ALLOWED_STATUS = {true, true, true, false, true, false, false, false}; + private static readonly bool[] MASK_TO_ALLOWED_STATUS = { true, true, true, false, true, false, false, false }; - private static readonly int[] MASK_TO_BIT_NUMBER = {0, 1, 2, 2, 3, 3, 3, 3}; + private static readonly int[] MASK_TO_BIT_NUMBER = { 0, 1, 2, 2, 3, 3, 3, 3 }; private int _pos; private int _prevMask; diff --git a/src/SharpCompress/Compressors/LZMA/AesDecoderStream.cs b/src/SharpCompress/Compressors/LZMA/AesDecoderStream.cs index 0a4be38b..7c2a8163 100644 --- a/src/SharpCompress/Compressors/LZMA/AesDecoderStream.cs +++ b/src/SharpCompress/Compressors/LZMA/AesDecoderStream.cs @@ -23,12 +23,12 @@ namespace SharpCompress.Compressors.LZMA mStream = input; mLimit = limit; - if (((uint) input.Length & 15) != 0) + if (((uint)input.Length & 15) != 0) { throw new NotSupportedException("AES decoder does not support padding."); } - Init(info, out int numCyclesPower, out byte[] salt, out byte[] seed); + Init(info, out int numCyclesPower, out byte[] salt, out byte[] seed); byte[] password = Encoding.Unicode.GetBytes(pass.CryptoGetTextPassword()); byte[] key = InitKey(numCyclesPower, salt, password); @@ -67,7 +67,7 @@ namespace SharpCompress.Compressors.LZMA public override long Position => mWritten; public override long Length => mLimit; - + public override int Read(byte[] buffer, int offset, int count) { if (count == 0 @@ -107,7 +107,7 @@ namespace SharpCompress.Compressors.LZMA // the stream length is not a multiple of the block size. if (count > mLimit - mWritten) { - count = (int) (mLimit - mWritten); + count = (int)(mLimit - mWritten); } // We cannot transform less than 16 bytes into the target buffer, diff --git a/src/SharpCompress/Compressors/LZMA/Bcj2DecoderStream.cs b/src/SharpCompress/Compressors/LZMA/Bcj2DecoderStream.cs index 4bdac69b..62a7ad65 100644 --- a/src/SharpCompress/Compressors/LZMA/Bcj2DecoderStream.cs +++ b/src/SharpCompress/Compressors/LZMA/Bcj2DecoderStream.cs @@ -215,7 +215,7 @@ namespace SharpCompress.Compressors.LZMA byte prevByte = 0; uint processedBytes = 0; - for (;;) + for (; ; ) { byte b = 0; uint i; diff --git a/src/SharpCompress/Compressors/LZMA/LzmaEncoder.cs b/src/SharpCompress/Compressors/LZMA/LzmaEncoder.cs index 17d90de3..e4420f21 100644 --- a/src/SharpCompress/Compressors/LZMA/LzmaEncoder.cs +++ b/src/SharpCompress/Compressors/LZMA/LzmaEncoder.cs @@ -766,7 +766,7 @@ namespace SharpCompress.Compressors.LZMA { offs += 2; } - for (;; len++) + for (; ; len++) { UInt32 distance = _matchDistances[offs + 1]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); @@ -1107,7 +1107,7 @@ namespace SharpCompress.Compressors.LZMA offs += 2; } - for (UInt32 lenTest = startLen;; lenTest++) + for (UInt32 lenTest = startLen; ; lenTest++) { UInt32 curBack = _matchDistances[offs + 1]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); @@ -1665,129 +1665,129 @@ namespace SharpCompress.Compressors.LZMA switch (propIDs[i]) { case CoderPropId.NumFastBytes: - { - if (!(prop is Int32)) { - throw new InvalidParamException(); - } - Int32 numFastBytes = (Int32)prop; - if (numFastBytes < 5 || numFastBytes > Base.K_MATCH_MAX_LEN) - { - throw new InvalidParamException(); - } - _numFastBytes = (UInt32)numFastBytes; - break; - } - case CoderPropId.Algorithm: - { - /* - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 maximize = (Int32)prop; - _fastMode = (maximize == 0); - _maxMode = (maximize >= 2); - */ - break; - } - case CoderPropId.MatchFinder: - { - if (!(prop is String)) - { - throw new InvalidParamException(); - } - EMatchFinderType matchFinderIndexPrev = _matchFinderType; - int m = FindMatchFinder(((string)prop).ToUpper()); - if (m < 0) - { - throw new InvalidParamException(); - } - _matchFinderType = (EMatchFinderType)m; - if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) - { - _dictionarySizePrev = 0xFFFFFFFF; - _matchFinder = null; - } - break; - } - case CoderPropId.DictionarySize: - { - const int kDicLogSizeMaxCompress = 30; - if (!(prop is Int32)) - { - throw new InvalidParamException(); - } - ; - Int32 dictionarySize = (Int32)prop; - if (dictionarySize < (UInt32)(1 << Base.K_DIC_LOG_SIZE_MIN) || - dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress)) - { - throw new InvalidParamException(); - } - _dictionarySize = (UInt32)dictionarySize; - int dicLogSize; - for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) - { - if (dictionarySize <= ((UInt32)(1) << dicLogSize)) + if (!(prop is Int32)) { - break; + throw new InvalidParamException(); } + Int32 numFastBytes = (Int32)prop; + if (numFastBytes < 5 || numFastBytes > Base.K_MATCH_MAX_LEN) + { + throw new InvalidParamException(); + } + _numFastBytes = (UInt32)numFastBytes; + break; } - _distTableSize = (UInt32)dicLogSize * 2; - break; - } - case CoderPropId.PosStateBits: - { - if (!(prop is Int32)) + case CoderPropId.Algorithm: { - throw new InvalidParamException(); + /* + if (!(prop is Int32)) + throw new InvalidParamException(); + Int32 maximize = (Int32)prop; + _fastMode = (maximize == 0); + _maxMode = (maximize >= 2); + */ + break; } - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.K_NUM_POS_STATES_BITS_ENCODING_MAX) + case CoderPropId.MatchFinder: { - throw new InvalidParamException(); + if (!(prop is String)) + { + throw new InvalidParamException(); + } + EMatchFinderType matchFinderIndexPrev = _matchFinderType; + int m = FindMatchFinder(((string)prop).ToUpper()); + if (m < 0) + { + throw new InvalidParamException(); + } + _matchFinderType = (EMatchFinderType)m; + if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) + { + _dictionarySizePrev = 0xFFFFFFFF; + _matchFinder = null; + } + break; } - _posStateBits = v; - _posStateMask = (((UInt32)1) << _posStateBits) - 1; - break; - } - case CoderPropId.LitPosBits: - { - if (!(prop is Int32)) + case CoderPropId.DictionarySize: { - throw new InvalidParamException(); - } - Int32 v = (Int32)prop; - if (v < 0 || v > Base.K_NUM_LIT_POS_STATES_BITS_ENCODING_MAX) - { - throw new InvalidParamException(); - } - _numLiteralPosStateBits = v; - break; - } - case CoderPropId.LitContextBits: - { - if (!(prop is Int32)) - { - throw new InvalidParamException(); - } - Int32 v = (Int32)prop; - if (v < 0 || v > Base.K_NUM_LIT_CONTEXT_BITS_MAX) - { - throw new InvalidParamException(); - } + const int kDicLogSizeMaxCompress = 30; + if (!(prop is Int32)) + { + throw new InvalidParamException(); + } ; - _numLiteralContextBits = v; - break; - } - case CoderPropId.EndMarker: - { - if (!(prop is Boolean)) - { - throw new InvalidParamException(); + Int32 dictionarySize = (Int32)prop; + if (dictionarySize < (UInt32)(1 << Base.K_DIC_LOG_SIZE_MIN) || + dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress)) + { + throw new InvalidParamException(); + } + _dictionarySize = (UInt32)dictionarySize; + int dicLogSize; + for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) + { + if (dictionarySize <= ((UInt32)(1) << dicLogSize)) + { + break; + } + } + _distTableSize = (UInt32)dicLogSize * 2; + break; + } + case CoderPropId.PosStateBits: + { + if (!(prop is Int32)) + { + throw new InvalidParamException(); + } + Int32 v = (Int32)prop; + if (v < 0 || v > (UInt32)Base.K_NUM_POS_STATES_BITS_ENCODING_MAX) + { + throw new InvalidParamException(); + } + _posStateBits = v; + _posStateMask = (((UInt32)1) << _posStateBits) - 1; + break; + } + case CoderPropId.LitPosBits: + { + if (!(prop is Int32)) + { + throw new InvalidParamException(); + } + Int32 v = (Int32)prop; + if (v < 0 || v > Base.K_NUM_LIT_POS_STATES_BITS_ENCODING_MAX) + { + throw new InvalidParamException(); + } + _numLiteralPosStateBits = v; + break; + } + case CoderPropId.LitContextBits: + { + if (!(prop is Int32)) + { + throw new InvalidParamException(); + } + Int32 v = (Int32)prop; + if (v < 0 || v > Base.K_NUM_LIT_CONTEXT_BITS_MAX) + { + throw new InvalidParamException(); + } + ; + _numLiteralContextBits = v; + break; + } + case CoderPropId.EndMarker: + { + if (!(prop is Boolean)) + { + throw new InvalidParamException(); + } + SetWriteEndMarkerMode((Boolean)prop); + break; } - SetWriteEndMarkerMode((Boolean)prop); - break; - } default: throw new InvalidParamException(); } diff --git a/src/SharpCompress/Compressors/PPMd/H/ModelPPM.cs b/src/SharpCompress/Compressors/PPMd/H/ModelPPM.cs index 13208e74..8f0e6867 100644 --- a/src/SharpCompress/Compressors/PPMd/H/ModelPPM.cs +++ b/src/SharpCompress/Compressors/PPMd/H/ModelPPM.cs @@ -92,7 +92,7 @@ namespace SharpCompress.Compressors.PPMd.H private readonly int[][] _binSumm = new int[128][]; // binary SEE-contexts - private static readonly int[] INIT_BIN_ESC = {0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; + private static readonly int[] INIT_BIN_ESC = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051 }; // Temp fields //UPGRADE_NOTE: Final was removed from the declaration of 'tempState1 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" @@ -846,7 +846,7 @@ namespace SharpCompress.Compressors.PPMd.H _charMask[rs.Symbol] = 0; _prevSuccess = 0; } - for (;;) + for (; ; ) { State s = _tempState1.Initialize(Heap); int i; diff --git a/src/SharpCompress/Compressors/PPMd/H/PPMContext.cs b/src/SharpCompress/Compressors/PPMd/H/PPMContext.cs index 0bcde66f..83340887 100644 --- a/src/SharpCompress/Compressors/PPMd/H/PPMContext.cs +++ b/src/SharpCompress/Compressors/PPMd/H/PPMContext.cs @@ -61,7 +61,7 @@ namespace SharpCompress.Compressors.PPMd.H private int _suffix; // pointer ppmcontext //UPGRADE_NOTE: Final was removed from the declaration of 'ExpEscape'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int[] EXP_ESCAPE = {25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2}; + public static readonly int[] EXP_ESCAPE = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; // Temp fields //UPGRADE_NOTE: Final was removed from the declaration of 'tempState1 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" diff --git a/src/SharpCompress/Compressors/PPMd/I1/Model.cs b/src/SharpCompress/Compressors/PPMd/I1/Model.cs index f66c6eab..347057eb 100644 --- a/src/SharpCompress/Compressors/PPMd/I1/Model.cs +++ b/src/SharpCompress/Compressors/PPMd/I1/Model.cs @@ -56,7 +56,7 @@ namespace SharpCompress.Compressors.PPMd.I1 0x6051 }; - private static ReadOnlySpan EXPONENTIAL_ESCAPES => new byte[] {25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2}; + private static ReadOnlySpan EXPONENTIAL_ESCAPES => new byte[] { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; #region Public Methods @@ -222,7 +222,7 @@ namespace SharpCompress.Compressors.PPMd.I1 _coder.RangeEncoderNormalize(target); } - StopEncoding: + StopEncoding: _coder.RangeEncoderFlush(target); } @@ -321,7 +321,7 @@ namespace SharpCompress.Compressors.PPMd.I1 _coder.RangeDecoderNormalize(source); } - StopDecoding: + StopDecoding: return total; } @@ -573,7 +573,7 @@ namespace SharpCompress.Compressors.PPMd.I1 _maximumContext = foundStateSuccessor; return; - RestartModel: + RestartModel: RestoreModel(currentContext, minimumContext, foundStateSuccessor); } @@ -633,7 +633,7 @@ namespace SharpCompress.Compressors.PPMd.I1 (byte)(((context.Suffix.NumberStatistics == 0) ? 1 : 0) & ((state.Frequency < 24) ? 1 : 0)); } - LoopEntry: + LoopEntry: if (state.Successor != upBranch) { context = state.Successor; @@ -643,7 +643,7 @@ namespace SharpCompress.Compressors.PPMd.I1 } while (context.Suffix != PpmContext.ZERO); - NoLoop: + NoLoop: if (stateIndex == 0) { return context; @@ -767,7 +767,7 @@ namespace SharpCompress.Compressors.PPMd.I1 state.Frequency += (byte)((state.Frequency < 32) ? 1 : 0); } - LoopEntry: + LoopEntry: if (state.Successor != PpmContext.ZERO) { break; diff --git a/src/SharpCompress/Compressors/PPMd/I1/PpmContext.cs b/src/SharpCompress/Compressors/PPMd/I1/PpmContext.cs index 1fb29cde..f75cbd3a 100644 --- a/src/SharpCompress/Compressors/PPMd/I1/PpmContext.cs +++ b/src/SharpCompress/Compressors/PPMd/I1/PpmContext.cs @@ -363,7 +363,7 @@ namespace SharpCompress.Compressors.PPMd.I1 _numberMasked = context.NumberStatistics; return; - SymbolFound: + SymbolFound: _coder._lowCount = lowCount; lowCount += state.Frequency; _coder._highCount = lowCount; diff --git a/src/SharpCompress/Compressors/PPMd/PpmdProperties.cs b/src/SharpCompress/Compressors/PPMd/PpmdProperties.cs index 8cd93bae..8b62388b 100644 --- a/src/SharpCompress/Compressors/PPMd/PpmdProperties.cs +++ b/src/SharpCompress/Compressors/PPMd/PpmdProperties.cs @@ -57,7 +57,7 @@ namespace SharpCompress.Compressors.PPMd if (Version == PpmdVersion.I1) { _allocator ??= new Allocator(); - + _allocator.Start(_allocatorSize); } } diff --git a/src/SharpCompress/Compressors/Rar/RarCRC.cs b/src/SharpCompress/Compressors/Rar/RarCRC.cs index 077b2f46..c9e8159c 100644 --- a/src/SharpCompress/Compressors/Rar/RarCRC.cs +++ b/src/SharpCompress/Compressors/Rar/RarCRC.cs @@ -6,8 +6,9 @@ namespace SharpCompress.Compressors.Rar { private static readonly uint[] crcTab; - public static uint CheckCrc(uint startCrc, byte b) { - return (crcTab[((int) ((int) startCrc ^ (int) b)) & 0xff] ^ (startCrc >> 8)); + public static uint CheckCrc(uint startCrc, byte b) + { + return (crcTab[((int)((int)startCrc ^ (int)b)) & 0xff] ^ (startCrc >> 8)); } public static uint CheckCrc(uint startCrc, byte[] data, int offset, int count) diff --git a/src/SharpCompress/Compressors/Rar/RarStream.cs b/src/SharpCompress/Compressors/Rar/RarStream.cs index dea52fc6..5e1cc12a 100644 --- a/src/SharpCompress/Compressors/Rar/RarStream.cs +++ b/src/SharpCompress/Compressors/Rar/RarStream.cs @@ -36,7 +36,8 @@ namespace SharpCompress.Compressors.Rar protected override void Dispose(bool disposing) { - if (!isDisposed) { + if (!isDisposed) + { isDisposed = true; base.Dispose(disposing); readStream.Dispose(); diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/Decode/FilterType.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/Decode/FilterType.cs index 6d915e44..32166837 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/Decode/FilterType.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/Decode/FilterType.cs @@ -2,9 +2,9 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode { internal enum FilterType : byte { - // These values must not be changed, because we use them directly - // in RAR5 compression and decompression code. - FILTER_DELTA=0, FILTER_E8, FILTER_E8E9, FILTER_ARM, - FILTER_AUDIO, FILTER_RGB, FILTER_ITANIUM, FILTER_PPM, FILTER_NONE + // These values must not be changed, because we use them directly + // in RAR5 compression and decompression code. + FILTER_DELTA = 0, FILTER_E8, FILTER_E8E9, FILTER_ARM, + FILTER_AUDIO, FILTER_RGB, FILTER_ITANIUM, FILTER_PPM, FILTER_NONE } } \ No newline at end of file diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/Decode/PackDef.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/Decode/PackDef.cs index 87f1977e..163ba5f3 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/Decode/PackDef.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/Decode/PackDef.cs @@ -15,27 +15,27 @@ namespace SharpCompress.Compressors.Rar.UnpackV1.Decode public const int DC = 60; public const int LDC = 17; public const int RC = 28; -// 20171217: NOTE: these constants seem to have been updated in the unrar src code -// at some unknown point. updating causes decompression failure, not sure why. -// public const int NC = 306; /* alphabet = {0, 1, 2, ..., NC - 1} */ -// public const int DC = 64; -// public const int LDC = 16; -// public const int RC = 44; + // 20171217: NOTE: these constants seem to have been updated in the unrar src code + // at some unknown point. updating causes decompression failure, not sure why. + // public const int NC = 306; /* alphabet = {0, 1, 2, ..., NC - 1} */ + // public const int DC = 64; + // public const int LDC = 16; + // public const int RC = 44; public const int HUFF_TABLE_SIZE = NC + DC + RC + LDC; - public const int BC = 20; + public const int BC = 20; - public const uint NC30 = 299; /* alphabet = {0, 1, 2, ..., NC - 1} */ - public const uint DC30 = 60; + public const uint NC30 = 299; /* alphabet = {0, 1, 2, ..., NC - 1} */ + public const uint DC30 = 60; public const uint LDC30 = 17; - public const uint RC30 = 28; - public const uint BC30 = 20; + public const uint RC30 = 28; + public const uint BC30 = 20; public const uint HUFF_TABLE_SIZE30 = NC30 + DC30 + RC30 + LDC30; - public const int NC20 = 298; /* alphabet = {0, 1, 2, ..., NC - 1} */ - public const int DC20 = 48; - public const int RC20 = 28; - public const int BC20 = 19; - public const int MC20 = 257; + public const int NC20 = 298; /* alphabet = {0, 1, 2, ..., NC - 1} */ + public const int DC20 = 48; + public const int RC20 = 28; + public const int BC20 = 19; + public const int MC20 = 257; // Largest alphabet size among all values listed above. public const uint LARGEST_TABLE_SIZE = 306; diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack.cs index ba1c8f50..cc33b25f 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack.cs @@ -16,7 +16,8 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 { private readonly BitInput Inp; - public Unpack() { + public Unpack() + { // to ease in porting Unpack50.cs Inp = this; } @@ -86,7 +87,7 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 private int lowDistRepCount; - private static readonly int[] DBitLengthCounts = {4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 14, 0, 12}; + private static readonly int[] DBitLengthCounts = { 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 14, 0, 12 }; private FileHeader fileHeader; @@ -677,7 +678,8 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 destUnpSize -= size; } - private void InsertOldDist(uint distance) { + private void InsertOldDist(uint distance) + { // TODO uint InsertOldDist((int)distance); } @@ -696,9 +698,10 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 lastLength = length; } - private void CopyString(uint length, uint distance) { + private void CopyString(uint length, uint distance) + { // TODO uint - CopyString((int)length, (int)distance) ; + CopyString((int)length, (int)distance); } private void CopyString(int length, int distance) @@ -743,7 +746,7 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 unpPtr = 0; wrPtr = 0; PpmEscChar = 2; -WriteBorder=Math.Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; + WriteBorder = Math.Min(MaxWinSize, UNPACK_MAX_WRITE) & MaxWinMask; InitFilters(); } @@ -755,35 +758,35 @@ WriteBorder=Math.Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; unpInitData20(solid); } -//void Unpack::UnpInitData(bool Solid) -//{ -// if (!Solid) -// { -// memset(OldDist,0,sizeof(OldDist)); -// OldDistPtr=0; -// LastDist=LastLength=0; -//// memset(Window,0,MaxWinSize); -// memset(&BlockTables,0,sizeof(BlockTables)); -// UnpPtr=WrPtr=0; -// WriteBorder=Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; -// } -// // Filters never share several solid files, so we can safely reset them -// // even in solid archive. -// InitFilters(); -// -// Inp.InitBitInput(); -// WrittenFileSize=0; -// ReadTop=0; -// ReadBorder=0; -// -// memset(&BlockHeader,0,sizeof(BlockHeader)); -// BlockHeader.BlockSize=-1; // '-1' means not defined yet. -//#ifndef SFX_MODULE -// UnpInitData20(Solid); -//#endif -// UnpInitData30(Solid); -// UnpInitData50(Solid); -//} + //void Unpack::UnpInitData(bool Solid) + //{ + // if (!Solid) + // { + // memset(OldDist,0,sizeof(OldDist)); + // OldDistPtr=0; + // LastDist=LastLength=0; + //// memset(Window,0,MaxWinSize); + // memset(&BlockTables,0,sizeof(BlockTables)); + // UnpPtr=WrPtr=0; + // WriteBorder=Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; + // } + // // Filters never share several solid files, so we can safely reset them + // // even in solid archive. + // InitFilters(); + // + // Inp.InitBitInput(); + // WrittenFileSize=0; + // ReadTop=0; + // ReadBorder=0; + // + // memset(&BlockHeader,0,sizeof(BlockHeader)); + // BlockHeader.BlockSize=-1; // '-1' means not defined yet. + //#ifndef SFX_MODULE + // UnpInitData20(Solid); + //#endif + // UnpInitData30(Solid); + // UnpInitData50(Solid); + //} private void InitFilters() { @@ -1063,7 +1066,7 @@ WriteBorder=Math.Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; UnpackFilter Filter; if (NewFilter) - // new filter code, never used before since VM reset + // new filter code, never used before since VM reset { // too many different filters, corrupt archive if (FiltPos > 1024) @@ -1121,8 +1124,8 @@ WriteBorder=Math.Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; if ((firstByte & 0x10) != 0) - // set registers to optional parameters - // if any + // set registers to optional parameters + // if any { int InitMask = Utility.URShift(Inp.GetBits(), 9); Inp.AddBits(7); @@ -1208,7 +1211,7 @@ WriteBorder=Math.Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; } if ((firstByte & 8) != 0) - // put data block passed as parameter if any + // put data block passed as parameter if any { if (Inp.Overflow(3)) { diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack15.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack15.cs index 435a6fca..7a0ae2bd 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack15.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack15.cs @@ -67,7 +67,7 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 , 0xffff }; - private static readonly int[] PosL1 = {0, 0, 0, 2, 3, 5, 7, 11, 16, 20, 24, 32, 32}; + private static readonly int[] PosL1 = { 0, 0, 0, 2, 3, 5, 7, 11, 16, 20, 24, 32, 32 }; private const int STARTL2 = 3; @@ -76,39 +76,39 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 0xa000, 0xc000, 0xd000, 0xe000, 0xea00, 0xee00, 0xf000, 0xf200, 0xf240, 0xffff }; - private static readonly int[] PosL2 = {0, 0, 0, 0, 5, 7, 9, 13, 18, 22, 26, 34, 36}; + private static readonly int[] PosL2 = { 0, 0, 0, 0, 5, 7, 9, 13, 18, 22, 26, 34, 36 }; private const int STARTHF0 = 4; - private static readonly int[] DecHf0 = {0x8000, 0xc000, 0xe000, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xffff}; + private static readonly int[] DecHf0 = { 0x8000, 0xc000, 0xe000, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xffff }; - private static readonly int[] PosHf0 = {0, 0, 0, 0, 0, 8, 16, 24, 33, 33, 33, 33, 33}; + private static readonly int[] PosHf0 = { 0, 0, 0, 0, 0, 8, 16, 24, 33, 33, 33, 33, 33 }; private const int STARTHF1 = 5; - private static readonly int[] DecHf1 = {0x2000, 0xc000, 0xe000, 0xf000, 0xf200, 0xf200, 0xf7e0, 0xffff}; + private static readonly int[] DecHf1 = { 0x2000, 0xc000, 0xe000, 0xf000, 0xf200, 0xf200, 0xf7e0, 0xffff }; - private static readonly int[] PosHf1 = {0, 0, 0, 0, 0, 0, 4, 44, 60, 76, 80, 80, 127}; + private static readonly int[] PosHf1 = { 0, 0, 0, 0, 0, 0, 4, 44, 60, 76, 80, 80, 127 }; private const int STARTHF2 = 5; - private static readonly int[] DecHf2 = {0x1000, 0x2400, 0x8000, 0xc000, 0xfa00, 0xffff, 0xffff, 0xffff}; + private static readonly int[] DecHf2 = { 0x1000, 0x2400, 0x8000, 0xc000, 0xfa00, 0xffff, 0xffff, 0xffff }; - private static readonly int[] PosHf2 = {0, 0, 0, 0, 0, 0, 2, 7, 53, 117, 233, 0, 0}; + private static readonly int[] PosHf2 = { 0, 0, 0, 0, 0, 0, 2, 7, 53, 117, 233, 0, 0 }; private const int STARTHF3 = 6; - private static readonly int[] DecHf3 = {0x800, 0x2400, 0xee00, 0xfe80, 0xffff, 0xffff, 0xffff}; + private static readonly int[] DecHf3 = { 0x800, 0x2400, 0xee00, 0xfe80, 0xffff, 0xffff, 0xffff }; - private static readonly int[] PosHf3 = {0, 0, 0, 0, 0, 0, 0, 2, 16, 218, 251, 0, 0}; + private static readonly int[] PosHf3 = { 0, 0, 0, 0, 0, 0, 0, 2, 16, 218, 251, 0, 0 }; private const int STARTHF4 = 8; - private static readonly int[] DecHf4 = {0xff00, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; + private static readonly int[] DecHf4 = { 0xff00, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff }; - private static readonly int[] PosHf4 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0}; + private static readonly int[] PosHf4 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0 }; - private static readonly int[] ShortLen1 = {1, 3, 4, 4, 5, 6, 7, 8, 8, 4, 4, 5, 6, 6, 4, 0}; + private static readonly int[] ShortLen1 = { 1, 3, 4, 4, 5, 6, 7, 8, 8, 4, 4, 5, 6, 6, 4, 0 }; private static readonly int[] ShortXor1 = { @@ -116,7 +116,7 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 , 0x9c, 0xb0 }; - private static readonly int[] ShortLen2 = {2, 3, 3, 3, 4, 4, 5, 6, 6, 4, 4, 5, 6, 6, 4, 0}; + private static readonly int[] ShortLen2 = { 2, 3, 3, 3, 4, 4, 5, 6, 6, 4, 4, 5, 6, 6, 4, 0 }; private static readonly int[] ShortXor2 = { @@ -290,7 +290,7 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 BitField = Utility.URShift(BitField, 8); if (AvrLn1 < 37) { - for (Length = 0;; Length++) + for (Length = 0; ; Length++) { if (((BitField ^ ShortXor1[Length]) & (~(Utility.URShift(0xff, getShortLen1(Length))))) == 0) { @@ -301,7 +301,7 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 } else { - for (Length = 0;; Length++) + for (Length = 0; ; Length++) { if (((BitField ^ ShortXor2[Length]) & (~(0xff >> getShortLen2(Length)))) == 0) { diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs index ad022c6b..eb0ce540 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs @@ -60,9 +60,9 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 , 16, 16, 16, 16, 16, 16, 16 }; - private static readonly int[] SDDecode = {0, 4, 8, 16, 32, 64, 128, 192}; + private static readonly int[] SDDecode = { 0, 4, 8, 16, 32, 64, 128, 192 }; - private static readonly int[] SDBits = {2, 2, 3, 4, 5, 6, 6, 6}; + private static readonly int[] SDBits = { 2, 2, 3, 4, 5, 6, 6, 6 }; private void unpack20(bool solid) { diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack50.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack50.cs index 81fe8208..d9e68205 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack50.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack50.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using SharpCompress.Compressors.Rar.UnpackV1.Decode; -using size_t=System.UInt32; +using size_t = System.UInt32; using UnpackBlockHeader = SharpCompress.Compressors.Rar.UnpackV1; namespace SharpCompress.Compressors.Rar.UnpackV1 @@ -11,22 +11,22 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 { // Maximum allowed number of compressed bits processed in quick mode. - private const int MAX_QUICK_DECODE_BITS = 10; + private const int MAX_QUICK_DECODE_BITS = 10; // Maximum number of filters per entire data block. Must be at least // twice more than MAX_PACK_FILTERS to store filters from two data blocks. - private const int MAX_UNPACK_FILTERS = 8192; + private const int MAX_UNPACK_FILTERS = 8192; // Maximum number of filters per entire data block for RAR3 unpack. // Must be at least twice more than v3_MAX_PACK_FILTERS to store filters // from two data blocks. - private const int MAX3_UNPACK_FILTERS = 8192; + private const int MAX3_UNPACK_FILTERS = 8192; // Limit maximum number of channels in RAR3 delta filter to some reasonable // value to prevent too slow processing of corrupt archives with invalid // channels number. Must be equal or larger than v3_MAX_FILTER_CHANNELS. // No need to provide it for RAR5, which uses only 5 bits to store channels. - private const int MAX3_UNPACK_CHANNELS = 1024; + private const int MAX3_UNPACK_CHANNELS = 1024; // Maximum size of single filter block. We restrict it to limit memory // allocation. Must be equal or larger than MAX_ANALYZE_SIZE. @@ -34,71 +34,71 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 // Write data in 4 MB or smaller blocks. Must not exceed PACK_MAX_WRITE, // so we keep number of buffered filter in unpacker reasonable. - private const int UNPACK_MAX_WRITE = 0x400000; + private const int UNPACK_MAX_WRITE = 0x400000; // Decode compressed bit fields to alphabet numbers. -// struct DecodeTable -// { -// // Real size of DecodeNum table. -// public uint MaxNum; -// -// // Left aligned start and upper limit codes defining code space -// // ranges for bit lengths. DecodeLen[BitLength-1] defines the start of -// // range for bit length and DecodeLen[BitLength] defines next code -// // after the end of range or in other words the upper limit code -// // for specified bit length. -// //uint DecodeLen[16]; -// public uint [] DecodeLen = new uint[16]; -// -// // Every item of this array contains the sum of all preceding items. -// // So it contains the start position in code list for every bit length. -// public uint DecodePos[16]; -// -// // Number of compressed bits processed in quick mode. -// // Must not exceed MAX_QUICK_DECODE_BITS. -// public uint QuickBits; -// -// // Translates compressed bits (up to QuickBits length) -// // to bit length in quick mode. -// public byte QuickLen[1< Filters { get { return filters; } } -// TODO: make sure these aren't already somewhere else -public int BlockSize; -public int BlockBitSize; -public int BlockStart; -public int HeaderSize; -public bool LastBlockInFile; -public bool TablePresent; + // TODO: make sure these aren't already somewhere else + public int BlockSize; + public int BlockBitSize; + public int BlockStart; + public int HeaderSize; + public bool LastBlockInFile; + public bool TablePresent; - public void Unpack5(bool Solid) { - FileExtracted=true; + public void Unpack5(bool Solid) + { + FileExtracted = true; if (!Suspended) { UnpInitData(Solid); if (!UnpReadBuf()) { - return; + return; } // Check TablesRead5 to be sure that we read tables at least once // regardless of current block header TablePresent flag. // So we can safefly use these tables below. - if (!ReadBlockHeader() || + if (!ReadBlockHeader() || !ReadTables() || !TablesRead5) { - return; + return; } } @@ -155,740 +156,740 @@ public bool TablePresent; { UnpPtr &= MaxWinMask; - if (Inp.InAddr>=ReadBorder) - { - bool FileDone=false; - - // We use 'while', because for empty block containing only Huffman table, - // we'll be on the block border once again just after reading the table. - while (Inp.InAddr>BlockHeader.BlockStart+BlockHeader.BlockSize-1 || - Inp.InAddr==BlockHeader.BlockStart+BlockHeader.BlockSize-1 && - Inp.InBit>=BlockHeader.BlockBitSize) - { - if (BlockHeader.LastBlockInFile) + if (Inp.InAddr >= ReadBorder) { - FileDone=true; - break; + bool FileDone = false; + + // We use 'while', because for empty block containing only Huffman table, + // we'll be on the block border once again just after reading the table. + while (Inp.InAddr > BlockHeader.BlockStart + BlockHeader.BlockSize - 1 || + Inp.InAddr == BlockHeader.BlockStart + BlockHeader.BlockSize - 1 && + Inp.InBit >= BlockHeader.BlockBitSize) + { + if (BlockHeader.LastBlockInFile) + { + FileDone = true; + break; + } + if (!ReadBlockHeader() || !ReadTables()) + { + return; + } + } + if (FileDone || !UnpReadBuf()) + { + break; + } } - if (!ReadBlockHeader() || !ReadTables()) + + if (((WriteBorder - UnpPtr) & MaxWinMask) < PackDef.MAX_LZ_MATCH + 3 && WriteBorder != UnpPtr) { - return; + UnpWriteBuf(); + if (WrittenFileSize > DestUnpSize) + { + return; + } + + if (Suspended) + { + FileExtracted = false; + return; + } } - } - if (FileDone || !UnpReadBuf()) - { - break; - } - } - if (((WriteBorder-UnpPtr) & MaxWinMask)DestUnpSize) - { - return; - } - - if (Suspended) - { - FileExtracted=false; - return; - } - } - - //uint MainSlot=DecodeNumber(Inp,LD); - uint MainSlot= this.DecodeNumber(LD); - if (MainSlot<256) - { -// if (Fragmented) -// FragWindow[UnpPtr++]=(byte)MainSlot; -// else - Window[UnpPtr++]=(byte)MainSlot; - continue; - } - if (MainSlot>=262) - { - uint Length=SlotToLength(MainSlot-262); - - //uint DBits,Distance=1,DistSlot=DecodeNumber(Inp,&BlockTables.DD); - int DBits; - uint Distance=1,DistSlot=this.DecodeNumber(DD); - if (DistSlot<4) - { - DBits=0; - Distance+=DistSlot; - } - else - { - //DBits=DistSlot/2 - 1; - DBits=(int)(DistSlot/2 - 1); - Distance+=(2 | (DistSlot & 1)) << DBits; - } - - if (DBits>0) - { - if (DBits>=4) + //uint MainSlot=DecodeNumber(Inp,LD); + uint MainSlot = this.DecodeNumber(LD); + if (MainSlot < 256) { - if (DBits>4) - { - Distance+=((Inp.getbits()>>(36-DBits))<<4); - Inp.AddBits(DBits-4); - } - //uint LowDist=DecodeNumber(Inp,&BlockTables.LDD); - uint LowDist=this.DecodeNumber(LDD); - Distance+=LowDist; + // if (Fragmented) + // FragWindow[UnpPtr++]=(byte)MainSlot; + // else + Window[UnpPtr++] = (byte)MainSlot; + continue; } - else + if (MainSlot >= 262) { - Distance+=Inp.getbits()>>(32-DBits); - Inp.AddBits(DBits); - } - } + uint Length = SlotToLength(MainSlot - 262); - if (Distance>0x100) - { - Length++; - if (Distance>0x2000) + //uint DBits,Distance=1,DistSlot=DecodeNumber(Inp,&BlockTables.DD); + int DBits; + uint Distance = 1, DistSlot = this.DecodeNumber(DD); + if (DistSlot < 4) + { + DBits = 0; + Distance += DistSlot; + } + else + { + //DBits=DistSlot/2 - 1; + DBits = (int)(DistSlot / 2 - 1); + Distance += (2 | (DistSlot & 1)) << DBits; + } + + if (DBits > 0) + { + if (DBits >= 4) + { + if (DBits > 4) + { + Distance += ((Inp.getbits() >> (36 - DBits)) << 4); + Inp.AddBits(DBits - 4); + } + //uint LowDist=DecodeNumber(Inp,&BlockTables.LDD); + uint LowDist = this.DecodeNumber(LDD); + Distance += LowDist; + } + else + { + Distance += Inp.getbits() >> (32 - DBits); + Inp.AddBits(DBits); + } + } + + if (Distance > 0x100) + { + Length++; + if (Distance > 0x2000) + { + Length++; + if (Distance > 0x40000) + { + Length++; + } + } + } + + InsertOldDist(Distance); + LastLength = Length; + // if (Fragmented) + // FragWindow.CopyString(Length,Distance,UnpPtr,MaxWinMask); + // else + CopyString(Length, Distance); + continue; + } + if (MainSlot == 256) { - Length++; - if (Distance>0x40000) - { - Length++; - } + UnpackFilter Filter = new UnpackFilter(); + if (!ReadFilter(Filter) || !AddFilter(Filter)) + { + break; + } + + continue; } - } + if (MainSlot == 257) + { + if (LastLength != 0) + // if (Fragmented) + // FragWindow.CopyString(LastLength,OldDist[0],UnpPtr,MaxWinMask); + // else + //CopyString(LastLength,OldDist[0]); + { + CopyString(LastLength, OldDistN(0)); + } - InsertOldDist(Distance); - LastLength=Length; -// if (Fragmented) -// FragWindow.CopyString(Length,Distance,UnpPtr,MaxWinMask); -// else - CopyString(Length,Distance); - continue; + continue; + } + if (MainSlot < 262) + { + //uint DistNum=MainSlot-258; + int DistNum = (int)(MainSlot - 258); + //uint Distance=OldDist[DistNum]; + uint Distance = OldDistN(DistNum); + //for (uint I=DistNum;I>0;I--) + for (int I = DistNum; I > 0; I--) + //OldDistN[I]=OldDistN(I-1); + { + SetOldDistN(I, OldDistN(I - 1)); + } + + //OldDistN[0]=Distance; + SetOldDistN(0, Distance); + + uint LengthSlot = this.DecodeNumber(RD); + uint Length = SlotToLength(LengthSlot); + LastLength = Length; + // if (Fragmented) + // FragWindow.CopyString(Length,Distance,UnpPtr,MaxWinMask); + // else + CopyString(Length, Distance); + continue; + } } - if (MainSlot==256) - { - UnpackFilter Filter = new UnpackFilter(); - if (!ReadFilter(Filter) || !AddFilter(Filter)) - { - break; - } - - continue; - } - if (MainSlot==257) - { - if (LastLength!=0) -// if (Fragmented) -// FragWindow.CopyString(LastLength,OldDist[0],UnpPtr,MaxWinMask); -// else - //CopyString(LastLength,OldDist[0]); - { - CopyString(LastLength,OldDistN(0)); - } - - continue; - } - if (MainSlot<262) - { - //uint DistNum=MainSlot-258; - int DistNum=(int)(MainSlot-258); - //uint Distance=OldDist[DistNum]; - uint Distance=OldDistN(DistNum); - //for (uint I=DistNum;I>0;I--) - for (int I=DistNum;I>0;I--) - //OldDistN[I]=OldDistN(I-1); - { - SetOldDistN(I, OldDistN(I-1)); - } - - //OldDistN[0]=Distance; - SetOldDistN(0, Distance); - - uint LengthSlot=this.DecodeNumber(RD); - uint Length=SlotToLength(LengthSlot); - LastLength=Length; -// if (Fragmented) -// FragWindow.CopyString(Length,Distance,UnpPtr,MaxWinMask); -// else - CopyString(Length,Distance); - continue; - } - } - UnpWriteBuf(); + UnpWriteBuf(); } - private uint ReadFilterData() + private uint ReadFilterData() { - uint ByteCount=(Inp.fgetbits()>>14)+1; - Inp.AddBits(2); + uint ByteCount = (Inp.fgetbits() >> 14) + 1; + Inp.AddBits(2); - uint Data=0; - //for (uint I=0;I>8)<<(I*8); - Inp.AddBits(8); - } - return Data; + uint Data = 0; + //for (uint I=0;I> 8) << (I * 8); + Inp.AddBits(8); + } + return Data; } - private bool ReadFilter(UnpackFilter Filter) + private bool ReadFilter(UnpackFilter Filter) { - if (!Inp.ExternalBuffer && Inp.InAddr>ReadTop-16) - { - if (!UnpReadBuf()) + if (!Inp.ExternalBuffer && Inp.InAddr > ReadTop - 16) { - return false; + if (!UnpReadBuf()) + { + return false; + } } - } - Filter.uBlockStart=ReadFilterData(); - Filter.uBlockLength=ReadFilterData(); - if (Filter.BlockLength>MAX_FILTER_BLOCK_SIZE) - { - Filter.BlockLength=0; - } + Filter.uBlockStart = ReadFilterData(); + Filter.uBlockLength = ReadFilterData(); + if (Filter.BlockLength > MAX_FILTER_BLOCK_SIZE) + { + Filter.BlockLength = 0; + } - //Filter.Type=Inp.fgetbits()>>13; - Filter.Type=(byte)(Inp.fgetbits()>>13); - Inp.faddbits(3); + //Filter.Type=Inp.fgetbits()>>13; + Filter.Type = (byte)(Inp.fgetbits() >> 13); + Inp.faddbits(3); - if (Filter.Type==(byte)FilterType.FILTER_DELTA) - { - //Filter.Channels=(Inp.fgetbits()>>11)+1; - Filter.Channels=(byte)((Inp.fgetbits()>>11)+1); - Inp.faddbits(5); - } + if (Filter.Type == (byte)FilterType.FILTER_DELTA) + { + //Filter.Channels=(Inp.fgetbits()>>11)+1; + Filter.Channels = (byte)((Inp.fgetbits() >> 11) + 1); + Inp.faddbits(5); + } - return true; + return true; } - private bool AddFilter(UnpackFilter Filter) + private bool AddFilter(UnpackFilter Filter) { - if (Filters.Count>=MAX_UNPACK_FILTERS) - { - UnpWriteBuf(); // Write data, apply and flush filters. - if (Filters.Count>=MAX_UNPACK_FILTERS) + if (Filters.Count >= MAX_UNPACK_FILTERS) { - InitFilters(); // Still too many filters, prevent excessive memory use. + UnpWriteBuf(); // Write data, apply and flush filters. + if (Filters.Count >= MAX_UNPACK_FILTERS) + { + InitFilters(); // Still too many filters, prevent excessive memory use. + } } - } - // If distance to filter start is that large that due to circular dictionary - // mode now it points to old not written yet data, then we set 'NextWindow' - // flag and process this filter only after processing that older data. - Filter.NextWindow=WrPtr!=UnpPtr && ((WrPtr-UnpPtr)&MaxWinMask)<=Filter.BlockStart; + // If distance to filter start is that large that due to circular dictionary + // mode now it points to old not written yet data, then we set 'NextWindow' + // flag and process this filter only after processing that older data. + Filter.NextWindow = WrPtr != UnpPtr && ((WrPtr - UnpPtr) & MaxWinMask) <= Filter.BlockStart; - Filter.uBlockStart=(uint)((Filter.BlockStart+UnpPtr)&MaxWinMask); - Filters.Add(Filter); - return true; + Filter.uBlockStart = (uint)((Filter.BlockStart + UnpPtr) & MaxWinMask); + Filters.Add(Filter); + return true; } - private bool UnpReadBuf() + private bool UnpReadBuf() { - int DataSize=ReadTop-Inp.InAddr; // Data left to process. - if (DataSize<0) - { - return false; - } - - BlockHeader.BlockSize-=Inp.InAddr-BlockHeader.BlockStart; - if (Inp.InAddr>MAX_SIZE/2) - { - // If we already processed more than half of buffer, let's move - // remaining data into beginning to free more space for new data - // and ensure that calling function does not cross the buffer border - // even if we did not read anything here. Also it ensures that read size - // is not less than CRYPT_BLOCK_SIZE, so we can align it without risk - // to make it zero. - if (DataSize>0) - //memmove(Inp.InBuf,Inp.InBuf+Inp.InAddr,DataSize); + int DataSize = ReadTop - Inp.InAddr; // Data left to process. + if (DataSize < 0) { - Array.Copy(InBuf, inAddr, InBuf, 0, DataSize); + return false; } - // TODO: perf - //Buffer.BlockCopy(InBuf, inAddr, InBuf, 0, DataSize); + BlockHeader.BlockSize -= Inp.InAddr - BlockHeader.BlockStart; + if (Inp.InAddr > MAX_SIZE / 2) + { + // If we already processed more than half of buffer, let's move + // remaining data into beginning to free more space for new data + // and ensure that calling function does not cross the buffer border + // even if we did not read anything here. Also it ensures that read size + // is not less than CRYPT_BLOCK_SIZE, so we can align it without risk + // to make it zero. + if (DataSize > 0) + //memmove(Inp.InBuf,Inp.InBuf+Inp.InAddr,DataSize); + { + Array.Copy(InBuf, inAddr, InBuf, 0, DataSize); + } - Inp.InAddr=0; - ReadTop=DataSize; - } - else - { - DataSize=ReadTop; - } + // TODO: perf + //Buffer.BlockCopy(InBuf, inAddr, InBuf, 0, DataSize); - int ReadCode=0; - if (MAX_SIZE!=DataSize) + Inp.InAddr = 0; + ReadTop = DataSize; + } + else + { + DataSize = ReadTop; + } + + int ReadCode = 0; + if (MAX_SIZE != DataSize) //ReadCode=UnpIO->UnpRead(Inp.InBuf+DataSize,BitInput.MAX_SIZE-DataSize); - { - ReadCode = readStream.Read(InBuf, DataSize, MAX_SIZE-DataSize); - } - - if (ReadCode>0) // Can be also -1. - { - ReadTop+=ReadCode; - } - - ReadBorder=ReadTop-30; - BlockHeader.BlockStart=Inp.InAddr; - if (BlockHeader.BlockSize!=-1) // '-1' means not defined yet. - { - // We may need to quit from main extraction loop and read new block header - // and trees earlier than data in input buffer ends. - ReadBorder=Math.Min(ReadBorder,BlockHeader.BlockStart+BlockHeader.BlockSize-1); - } - return ReadCode!=-1; - } - -//? -// void UnpWriteBuf() -// { -// size_t WrittenBorder=WrPtr; -// size_t FullWriteSize=(UnpPtr-WrittenBorder)&MaxWinMask; -// size_t WriteSizeLeft=FullWriteSize; -// bool NotAllFiltersProcessed=false; -// for (size_t I=0;IType==FilterType.FILTER_NONE) -// continue; -// if (flt->NextWindow) -// { -// // Here we skip filters which have block start in current data range -// // due to address wrap around in circular dictionary, but actually -// // belong to next dictionary block. If such filter start position -// // is included to current write range, then we reset 'NextWindow' flag. -// // In fact we can reset it even without such check, because current -// // implementation seems to guarantee 'NextWindow' flag reset after -// // buffer writing for all existing filters. But let's keep this check -// // just in case. Compressor guarantees that distance between -// // filter block start and filter storing position cannot exceed -// // the dictionary size. So if we covered the filter block start with -// // our write here, we can safely assume that filter is applicable -// // to next block on no further wrap arounds is possible. -// if (((flt->BlockStart-WrPtr)&MaxWinMask)<=FullWriteSize) -// flt->NextWindow=false; -// continue; -// } -// uint BlockStart=flt->BlockStart; -// uint BlockLength=flt->BlockLength; -// if (((BlockStart-WrittenBorder)&MaxWinMask)0) // We set it to 0 also for invalid filters. -// { -// uint BlockEnd=(BlockStart+BlockLength)&MaxWinMask; -// -// FilterSrcMemory.Alloc(BlockLength); -// byte *Mem=&FilterSrcMemory[0]; -// if (BlockStartUnpWrite(OutMem,BlockLength); -// -// UnpSomeRead=true; -// WrittenFileSize+=BlockLength; -// WrittenBorder=BlockEnd; -// WriteSizeLeft=(UnpPtr-WrittenBorder)&MaxWinMask; -// } -// } -// else -// { -// // Current filter intersects the window write border, so we adjust -// // the window border to process this filter next time, not now. -// WrPtr=WrittenBorder; -// -// // Since Filter start position can only increase, we quit processing -// // all following filters for this data block and reset 'NextWindow' -// // flag for them. -// for (size_t J=I;JType!=FilterType.FILTER_NONE) -// flt->NextWindow=false; -// } -// -// // Do not write data left after current filter now. -// NotAllFiltersProcessed=true; -// break; -// } -// } -// } -// -// // Remove processed filters from queue. -// size_t EmptyCount=0; -// for (size_t I=0;I0) -// Filters[I-EmptyCount]=Filters[I]; -// if (Filters[I].Type==FilterType.FILTER_NONE) -// EmptyCount++; -// } -// if (EmptyCount>0) -// Filters.Alloc(Filters.Size()-EmptyCount); -// -// if (!NotAllFiltersProcessed) // Only if all filters are processed. -// { -// // Write data left after last filter. -// UnpWriteArea(WrittenBorder,UnpPtr); -// WrPtr=UnpPtr; -// } -// -// // We prefer to write data in blocks not exceeding UNPACK_MAX_WRITE -// // instead of potentially huge MaxWinSize blocks. It also allows us -// // to keep the size of Filters array reasonable. -// WriteBorder=(UnpPtr+Min(MaxWinSize,UNPACK_MAX_WRITE))&MaxWinMask; -// -// // Choose the nearest among WriteBorder and WrPtr actual written border. -// // If border is equal to UnpPtr, it means that we have MaxWinSize data ahead. -// if (WriteBorder==UnpPtr || -// WrPtr!=UnpPtr && ((WrPtr-UnpPtr)&MaxWinMask)<((WriteBorder-UnpPtr)&MaxWinMask)) -// WriteBorder=WrPtr; -// } - - -// unused - //x byte* ApplyFilter(byte *Data,uint DataSize,UnpackFilter *Flt) -// byte[] ApplyFilter(byte []Data, uint DataSize, UnpackFilter Flt) -// { -// //x byte *SrcData=Data; -// byte []SrcData=Data; -// switch(Flt.Type) -// { -// case (byte)FilterType.FILTER_E8: -// case (byte)FilterType.FILTER_E8E9: -// { -// uint FileOffset=(uint)WrittenFileSize; -// -// const uint FileSize=0x1000000; -// byte CmpByte2=Flt.Type==(byte)FilterType.FILTER_E8E9 ? (byte)0xe9 : (byte)0xe8; -// // DataSize is unsigned, so we use "CurPos+4" and not "DataSize-4" -// // to avoid overflow for DataSize<4. -// for (uint CurPos=0;CurPos+4=0 -// RawPut4(Addr+FileSize,Data); -// } -// else -// if (((Addr-FileSize) & 0x80000000)!=0) // Addr>8); -// D[2]=(byte)(Offset>>16); -// } -// } -// } -// return SrcData; -// case (byte)FilterType.FILTER_DELTA: -// { -// // Unlike RAR3, we do not need to reject excessive channel -// // values here, since RAR5 uses only 5 bits to store channel. -// uint Channels=Flt->Channels,SrcPos=0; -// -// FilterDstMemory.Alloc(DataSize); -// byte *DstData=&FilterDstMemory[0]; -// -// // Bytes from same channels are grouped to continual data blocks, -// // so we need to place them back to their interleaving positions. -// for (uint CurChannel=0;CurChannel0) -//// { -//// size_t BlockSize=FragWindow.GetBlockSize(StartPtr,SizeToWrite); -//// UnpWriteData(&FragWindow[StartPtr],BlockSize); -//// SizeToWrite-=BlockSize; -//// StartPtr=(StartPtr+BlockSize) & MaxWinMask; -//// } -//// } -//// else -// if (EndPtr=DestUnpSize) -// return; -// size_t WriteSize=Size; -// long LeftToWrite=DestUnpSize-WrittenFileSize; -// if ((long)WriteSize>LeftToWrite) -// WriteSize=(size_t)LeftToWrite; -// UnpIO->UnpWrite(Data,WriteSize); -// WrittenFileSize+=Size; -// } - - private void UnpInitData50(bool Solid) - { - if (!Solid) - { - TablesRead5=false; - } - } - - private bool ReadBlockHeader() - { - Header.HeaderSize=0; - - if (!Inp.ExternalBuffer && Inp.InAddr>ReadTop-7) - { - if (!UnpReadBuf()) { - return false; + ReadCode = readStream.Read(InBuf, DataSize, MAX_SIZE - DataSize); } - } - //Inp.faddbits((8-Inp.InBit)&7); - Inp.faddbits((uint)((8-Inp.InBit)&7)); - - byte BlockFlags=(byte)(Inp.fgetbits()>>8); - Inp.faddbits(8); - //uint ByteCount=((BlockFlags>>3)&3)+1; // Block size byte count. - uint ByteCount=(uint)(((BlockFlags>>3)&3)+1); // Block size byte count. - - if (ByteCount==4) - { - return false; - } + if (ReadCode > 0) // Can be also -1. + { + ReadTop += ReadCode; + } - //Header.HeaderSize=2+ByteCount; - Header.HeaderSize=(int)(2+ByteCount); - - Header.BlockBitSize=(BlockFlags&7)+1; - - byte SavedCheckSum=(byte)(Inp.fgetbits()>>8); - Inp.faddbits(8); - - int BlockSize=0; - //for (uint I=0;I>8)<<(I*8); - BlockSize+=(int)(Inp.fgetbits()>>8)<<(I*8); - Inp.AddBits(8); - } - - Header.BlockSize=BlockSize; - byte CheckSum=(byte)(0x5a^BlockFlags^BlockSize^(BlockSize>>8)^(BlockSize>>16)); - if (CheckSum!=SavedCheckSum) - { - return false; - } - - Header.BlockStart=Inp.InAddr; - ReadBorder=Math.Min(ReadBorder,Header.BlockStart+Header.BlockSize-1); - - Header.LastBlockInFile=(BlockFlags & 0x40)!=0; - Header.TablePresent=(BlockFlags & 0x80)!=0; - return true; + ReadBorder = ReadTop - 30; + BlockHeader.BlockStart = Inp.InAddr; + if (BlockHeader.BlockSize != -1) // '-1' means not defined yet. + { + // We may need to quit from main extraction loop and read new block header + // and trees earlier than data in input buffer ends. + ReadBorder = Math.Min(ReadBorder, BlockHeader.BlockStart + BlockHeader.BlockSize - 1); + } + return ReadCode != -1; } -//? -// bool ReadTables(BitInput Inp, ref UnpackBlockHeader Header, ref UnpackBlockTables Tables) -// { -// if (!Header.TablePresent) -// return true; -// -// if (!Inp.ExternalBuffer && Inp.InAddr>ReadTop-25) -// if (!UnpReadBuf()) -// return false; -// -// byte BitLength[BC]; -// for (uint I=0;I> 12); -// Inp.faddbits(4); -// if (Length==15) -// { -// uint ZeroCount=(byte)(Inp.fgetbits() >> 12); -// Inp.faddbits(4); -// if (ZeroCount==0) -// BitLength[I]=15; -// else -// { -// ZeroCount+=2; -// while (ZeroCount-- > 0 && IReadTop-5) -// if (!UnpReadBuf()) -// return false; -// uint Number=DecodeNumber(Inp,&Tables.BD); -// if (Number<16) -// { -// Table[I]=Number; -// I++; -// } -// else -// if (Number<18) -// { -// uint N; -// if (Number==16) -// { -// N=(Inp.fgetbits() >> 13)+3; -// Inp.faddbits(3); -// } -// else -// { -// N=(Inp.fgetbits() >> 9)+11; -// Inp.faddbits(7); -// } -// if (I==0) -// { -// // We cannot have "repeat previous" code at the first position. -// // Multiple such codes would shift Inp position without changing I, -// // which can lead to reading beyond of Inp boundary in mutithreading -// // mode, where Inp.ExternalBuffer disables bounds check and we just -// // reserve a lot of buffer space to not need such check normally. -// return false; -// } -// else -// while (N-- > 0 && I> 13)+3; -// Inp.faddbits(3); -// } -// else -// { -// N=(Inp.fgetbits() >> 9)+11; -// Inp.faddbits(7); -// } -// while (N-- > 0 && IReadTop) -// return false; -// MakeDecodeTables(&Table[0],&Tables.LD,NC); -// MakeDecodeTables(&Table[NC],&Tables.DD,DC); -// MakeDecodeTables(&Table[NC+DC],&Tables.LDD,LDC); -// MakeDecodeTables(&Table[NC+DC+LDC],&Tables.RD,RC); -// return true; -// } + //? + // void UnpWriteBuf() + // { + // size_t WrittenBorder=WrPtr; + // size_t FullWriteSize=(UnpPtr-WrittenBorder)&MaxWinMask; + // size_t WriteSizeLeft=FullWriteSize; + // bool NotAllFiltersProcessed=false; + // for (size_t I=0;IType==FilterType.FILTER_NONE) + // continue; + // if (flt->NextWindow) + // { + // // Here we skip filters which have block start in current data range + // // due to address wrap around in circular dictionary, but actually + // // belong to next dictionary block. If such filter start position + // // is included to current write range, then we reset 'NextWindow' flag. + // // In fact we can reset it even without such check, because current + // // implementation seems to guarantee 'NextWindow' flag reset after + // // buffer writing for all existing filters. But let's keep this check + // // just in case. Compressor guarantees that distance between + // // filter block start and filter storing position cannot exceed + // // the dictionary size. So if we covered the filter block start with + // // our write here, we can safely assume that filter is applicable + // // to next block on no further wrap arounds is possible. + // if (((flt->BlockStart-WrPtr)&MaxWinMask)<=FullWriteSize) + // flt->NextWindow=false; + // continue; + // } + // uint BlockStart=flt->BlockStart; + // uint BlockLength=flt->BlockLength; + // if (((BlockStart-WrittenBorder)&MaxWinMask)0) // We set it to 0 also for invalid filters. + // { + // uint BlockEnd=(BlockStart+BlockLength)&MaxWinMask; + // + // FilterSrcMemory.Alloc(BlockLength); + // byte *Mem=&FilterSrcMemory[0]; + // if (BlockStartUnpWrite(OutMem,BlockLength); + // + // UnpSomeRead=true; + // WrittenFileSize+=BlockLength; + // WrittenBorder=BlockEnd; + // WriteSizeLeft=(UnpPtr-WrittenBorder)&MaxWinMask; + // } + // } + // else + // { + // // Current filter intersects the window write border, so we adjust + // // the window border to process this filter next time, not now. + // WrPtr=WrittenBorder; + // + // // Since Filter start position can only increase, we quit processing + // // all following filters for this data block and reset 'NextWindow' + // // flag for them. + // for (size_t J=I;JType!=FilterType.FILTER_NONE) + // flt->NextWindow=false; + // } + // + // // Do not write data left after current filter now. + // NotAllFiltersProcessed=true; + // break; + // } + // } + // } + // + // // Remove processed filters from queue. + // size_t EmptyCount=0; + // for (size_t I=0;I0) + // Filters[I-EmptyCount]=Filters[I]; + // if (Filters[I].Type==FilterType.FILTER_NONE) + // EmptyCount++; + // } + // if (EmptyCount>0) + // Filters.Alloc(Filters.Size()-EmptyCount); + // + // if (!NotAllFiltersProcessed) // Only if all filters are processed. + // { + // // Write data left after last filter. + // UnpWriteArea(WrittenBorder,UnpPtr); + // WrPtr=UnpPtr; + // } + // + // // We prefer to write data in blocks not exceeding UNPACK_MAX_WRITE + // // instead of potentially huge MaxWinSize blocks. It also allows us + // // to keep the size of Filters array reasonable. + // WriteBorder=(UnpPtr+Min(MaxWinSize,UNPACK_MAX_WRITE))&MaxWinMask; + // + // // Choose the nearest among WriteBorder and WrPtr actual written border. + // // If border is equal to UnpPtr, it means that we have MaxWinSize data ahead. + // if (WriteBorder==UnpPtr || + // WrPtr!=UnpPtr && ((WrPtr-UnpPtr)&MaxWinMask)<((WriteBorder-UnpPtr)&MaxWinMask)) + // WriteBorder=WrPtr; + // } -//? -// void InitFilters() -// { -// Filters.SoftReset(); -// } + + // unused + //x byte* ApplyFilter(byte *Data,uint DataSize,UnpackFilter *Flt) + // byte[] ApplyFilter(byte []Data, uint DataSize, UnpackFilter Flt) + // { + // //x byte *SrcData=Data; + // byte []SrcData=Data; + // switch(Flt.Type) + // { + // case (byte)FilterType.FILTER_E8: + // case (byte)FilterType.FILTER_E8E9: + // { + // uint FileOffset=(uint)WrittenFileSize; + // + // const uint FileSize=0x1000000; + // byte CmpByte2=Flt.Type==(byte)FilterType.FILTER_E8E9 ? (byte)0xe9 : (byte)0xe8; + // // DataSize is unsigned, so we use "CurPos+4" and not "DataSize-4" + // // to avoid overflow for DataSize<4. + // for (uint CurPos=0;CurPos+4=0 + // RawPut4(Addr+FileSize,Data); + // } + // else + // if (((Addr-FileSize) & 0x80000000)!=0) // Addr>8); + // D[2]=(byte)(Offset>>16); + // } + // } + // } + // return SrcData; + // case (byte)FilterType.FILTER_DELTA: + // { + // // Unlike RAR3, we do not need to reject excessive channel + // // values here, since RAR5 uses only 5 bits to store channel. + // uint Channels=Flt->Channels,SrcPos=0; + // + // FilterDstMemory.Alloc(DataSize); + // byte *DstData=&FilterDstMemory[0]; + // + // // Bytes from same channels are grouped to continual data blocks, + // // so we need to place them back to their interleaving positions. + // for (uint CurChannel=0;CurChannel0) + //// { + //// size_t BlockSize=FragWindow.GetBlockSize(StartPtr,SizeToWrite); + //// UnpWriteData(&FragWindow[StartPtr],BlockSize); + //// SizeToWrite-=BlockSize; + //// StartPtr=(StartPtr+BlockSize) & MaxWinMask; + //// } + //// } + //// else + // if (EndPtr=DestUnpSize) + // return; + // size_t WriteSize=Size; + // long LeftToWrite=DestUnpSize-WrittenFileSize; + // if ((long)WriteSize>LeftToWrite) + // WriteSize=(size_t)LeftToWrite; + // UnpIO->UnpWrite(Data,WriteSize); + // WrittenFileSize+=Size; + // } + + private void UnpInitData50(bool Solid) + { + if (!Solid) + { + TablesRead5 = false; + } + } + + private bool ReadBlockHeader() + { + Header.HeaderSize = 0; + + if (!Inp.ExternalBuffer && Inp.InAddr > ReadTop - 7) + { + if (!UnpReadBuf()) + { + return false; + } + } + + //Inp.faddbits((8-Inp.InBit)&7); + Inp.faddbits((uint)((8 - Inp.InBit) & 7)); + + byte BlockFlags = (byte)(Inp.fgetbits() >> 8); + Inp.faddbits(8); + //uint ByteCount=((BlockFlags>>3)&3)+1; // Block size byte count. + uint ByteCount = (uint)(((BlockFlags >> 3) & 3) + 1); // Block size byte count. + + if (ByteCount == 4) + { + return false; + } + + //Header.HeaderSize=2+ByteCount; + Header.HeaderSize = (int)(2 + ByteCount); + + Header.BlockBitSize = (BlockFlags & 7) + 1; + + byte SavedCheckSum = (byte)(Inp.fgetbits() >> 8); + Inp.faddbits(8); + + int BlockSize = 0; + //for (uint I=0;I>8)<<(I*8); + BlockSize += (int)(Inp.fgetbits() >> 8) << (I * 8); + Inp.AddBits(8); + } + + Header.BlockSize = BlockSize; + byte CheckSum = (byte)(0x5a ^ BlockFlags ^ BlockSize ^ (BlockSize >> 8) ^ (BlockSize >> 16)); + if (CheckSum != SavedCheckSum) + { + return false; + } + + Header.BlockStart = Inp.InAddr; + ReadBorder = Math.Min(ReadBorder, Header.BlockStart + Header.BlockSize - 1); + + Header.LastBlockInFile = (BlockFlags & 0x40) != 0; + Header.TablePresent = (BlockFlags & 0x80) != 0; + return true; + } + + //? + // bool ReadTables(BitInput Inp, ref UnpackBlockHeader Header, ref UnpackBlockTables Tables) + // { + // if (!Header.TablePresent) + // return true; + // + // if (!Inp.ExternalBuffer && Inp.InAddr>ReadTop-25) + // if (!UnpReadBuf()) + // return false; + // + // byte BitLength[BC]; + // for (uint I=0;I> 12); + // Inp.faddbits(4); + // if (Length==15) + // { + // uint ZeroCount=(byte)(Inp.fgetbits() >> 12); + // Inp.faddbits(4); + // if (ZeroCount==0) + // BitLength[I]=15; + // else + // { + // ZeroCount+=2; + // while (ZeroCount-- > 0 && IReadTop-5) + // if (!UnpReadBuf()) + // return false; + // uint Number=DecodeNumber(Inp,&Tables.BD); + // if (Number<16) + // { + // Table[I]=Number; + // I++; + // } + // else + // if (Number<18) + // { + // uint N; + // if (Number==16) + // { + // N=(Inp.fgetbits() >> 13)+3; + // Inp.faddbits(3); + // } + // else + // { + // N=(Inp.fgetbits() >> 9)+11; + // Inp.faddbits(7); + // } + // if (I==0) + // { + // // We cannot have "repeat previous" code at the first position. + // // Multiple such codes would shift Inp position without changing I, + // // which can lead to reading beyond of Inp boundary in mutithreading + // // mode, where Inp.ExternalBuffer disables bounds check and we just + // // reserve a lot of buffer space to not need such check normally. + // return false; + // } + // else + // while (N-- > 0 && I> 13)+3; + // Inp.faddbits(3); + // } + // else + // { + // N=(Inp.fgetbits() >> 9)+11; + // Inp.faddbits(7); + // } + // while (N-- > 0 && IReadTop) + // return false; + // MakeDecodeTables(&Table[0],&Tables.LD,NC); + // MakeDecodeTables(&Table[NC],&Tables.DD,DC); + // MakeDecodeTables(&Table[NC+DC],&Tables.LDD,LDC); + // MakeDecodeTables(&Table[NC+DC+LDC],&Tables.RD,RC); + // return true; + // } + + //? + // void InitFilters() + // { + // Filters.SoftReset(); + // } } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/UnpackInline.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/UnpackInline.cs index 1bb2893d..e509afa2 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/UnpackInline.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/UnpackInline.cs @@ -3,29 +3,29 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 { internal partial class Unpack { - private uint SlotToLength(uint Slot) + private uint SlotToLength(uint Slot) { - //uint LBits,Length=2; - int LBits; - uint Length=2; - if (Slot<8) - { - LBits=0; - Length+=Slot; - } - else - { - //LBits=Slot/4-1; - LBits=(int)(Slot/4-1); - Length+=(4 | (Slot & 3)) << LBits; - } + //uint LBits,Length=2; + int LBits; + uint Length = 2; + if (Slot < 8) + { + LBits = 0; + Length += Slot; + } + else + { + //LBits=Slot/4-1; + LBits = (int)(Slot / 4 - 1); + Length += (4 | (Slot & 3)) << LBits; + } - if (LBits>0) - { - Length+=getbits()>>(16-LBits); - AddBits(LBits); - } - return Length; + if (LBits > 0) + { + Length += getbits() >> (16 - LBits); + AddBits(LBits); + } + return Length; } } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/UnpackUtility.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/UnpackUtility.cs index 89b5d904..ec04db1c 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/UnpackUtility.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/UnpackUtility.cs @@ -6,8 +6,9 @@ namespace SharpCompress.Compressors.Rar.UnpackV1 { internal static class UnpackUtility { -//!!! TODO rename methods - internal static uint DecodeNumber(this BitInput input, Decode.Decode dec) { + //!!! TODO rename methods + internal static uint DecodeNumber(this BitInput input, Decode.Decode dec) + { return (uint)input.decodeNumber(dec); } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/BitInput.getbits_cpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/BitInput.getbits_cpp.cs index 9db7a17a..c1de6517 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/BitInput.getbits_cpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/BitInput.getbits_cpp.cs @@ -15,57 +15,57 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 internal partial class BitInput { -public BitInput(bool AllocBuffer) -{ - ExternalBuffer=false; - if (AllocBuffer) - { - // getbits32 attempts to read data from InAddr, ... InAddr+3 positions. - // So let's allocate 3 additional bytes for situation, when we need to - // read only 1 byte from the last position of buffer and avoid a crash - // from access to next 3 bytes, which contents we do not need. - size_t BufSize=MAX_SIZE+3; - InBuf=new byte[BufSize]; + public BitInput(bool AllocBuffer) + { + ExternalBuffer = false; + if (AllocBuffer) + { + // getbits32 attempts to read data from InAddr, ... InAddr+3 positions. + // So let's allocate 3 additional bytes for situation, when we need to + // read only 1 byte from the last position of buffer and avoid a crash + // from access to next 3 bytes, which contents we do not need. + size_t BufSize = MAX_SIZE + 3; + InBuf = new byte[BufSize]; - // Ensure that we get predictable results when accessing bytes in area - // not filled with read data. - //memset(InBuf,0,BufSize); - } - else - { - InBuf=null; - } -} + // Ensure that we get predictable results when accessing bytes in area + // not filled with read data. + //memset(InBuf,0,BufSize); + } + else + { + InBuf = null; + } + } -//BitInput::~BitInput() -//{ -// if (!ExternalBuffer) -// delete[] InBuf; -//} -// + //BitInput::~BitInput() + //{ + // if (!ExternalBuffer) + // delete[] InBuf; + //} + // -public -void faddbits(uint Bits) -{ - // Function wrapped version of inline addbits to save code size. - addbits(Bits); -} + public + void faddbits(uint Bits) + { + // Function wrapped version of inline addbits to save code size. + addbits(Bits); + } -public -uint fgetbits() -{ - // Function wrapped version of inline getbits to save code size. - return getbits(); -} + public + uint fgetbits() + { + // Function wrapped version of inline getbits to save code size. + return getbits(); + } - private void SetExternalBuffer(byte []Buf) -{ - //if (InBuf!=NULL && !ExternalBuffer) - // delete[] InBuf; - InBuf=Buf; - ExternalBuffer=true; -} + private void SetExternalBuffer(byte[] Buf) + { + //if (InBuf!=NULL && !ExternalBuffer) + // delete[] InBuf; + InBuf = Buf; + ExternalBuffer = true; + } } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/BitInput.getbits_hpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/BitInput.getbits_hpp.cs index 4f16592e..14867ed8 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/BitInput.getbits_hpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/BitInput.getbits_hpp.cs @@ -1,70 +1,70 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 { -internal partial class BitInput -{ - public const int MAX_SIZE=0x8000; // Size of input buffer. - - public int InAddr; // Curent byte position in the buffer. - public int InBit; // Current bit position in the current byte. - - public bool ExternalBuffer; - - //BitInput(bool AllocBuffer); - //~BitInput(); - - public byte[] InBuf; // Dynamically allocated input buffer. - - public - void InitBitInput() + internal partial class BitInput { - InAddr=InBit=0; - } - - // Move forward by 'Bits' bits. - public void addbits(uint _Bits) - { - var Bits = checked((int)_Bits); - Bits+=InBit; - InAddr+=Bits>>3; - InBit=Bits&7; - } - - // Return 16 bits from current position in the buffer. - // Bit at (InAddr,InBit) has the highest position in returning data. - public uint getbits() - { - uint BitField=(uint)InBuf[InAddr] << 16; - BitField|=(uint)InBuf[InAddr+1] << 8; - BitField|=(uint)InBuf[InAddr+2]; - BitField >>= (8-InBit); - return BitField & 0xffff; - } + public const int MAX_SIZE = 0x8000; // Size of input buffer. - // Return 32 bits from current position in the buffer. - // Bit at (InAddr,InBit) has the highest position in returning data. - public uint getbits32() - { - uint BitField=(uint)InBuf[InAddr] << 24; - BitField|=(uint)InBuf[InAddr+1] << 16; - BitField|=(uint)InBuf[InAddr+2] << 8; - BitField|=(uint)InBuf[InAddr+3]; - BitField <<= InBit; - BitField|=(uint)InBuf[InAddr+4] >> (8-InBit); - return BitField & 0xffffffff; - } - - //void faddbits(uint Bits); - //uint fgetbits(); - - // Check if buffer has enough space for IncPtr bytes. Returns 'true' - // if buffer will be overflown. - private bool Overflow(uint IncPtr) - { - return InAddr+IncPtr>=MAX_SIZE; - } + public int InAddr; // Curent byte position in the buffer. + public int InBit; // Current bit position in the current byte. - //void SetExternalBuffer(byte *Buf); -} + public bool ExternalBuffer; + + //BitInput(bool AllocBuffer); + //~BitInput(); + + public byte[] InBuf; // Dynamically allocated input buffer. + + public + void InitBitInput() + { + InAddr = InBit = 0; + } + + // Move forward by 'Bits' bits. + public void addbits(uint _Bits) + { + var Bits = checked((int)_Bits); + Bits += InBit; + InAddr += Bits >> 3; + InBit = Bits & 7; + } + + // Return 16 bits from current position in the buffer. + // Bit at (InAddr,InBit) has the highest position in returning data. + public uint getbits() + { + uint BitField = (uint)InBuf[InAddr] << 16; + BitField |= (uint)InBuf[InAddr + 1] << 8; + BitField |= (uint)InBuf[InAddr + 2]; + BitField >>= (8 - InBit); + return BitField & 0xffff; + } + + // Return 32 bits from current position in the buffer. + // Bit at (InAddr,InBit) has the highest position in returning data. + public uint getbits32() + { + uint BitField = (uint)InBuf[InAddr] << 24; + BitField |= (uint)InBuf[InAddr + 1] << 16; + BitField |= (uint)InBuf[InAddr + 2] << 8; + BitField |= (uint)InBuf[InAddr + 3]; + BitField <<= InBit; + BitField |= (uint)InBuf[InAddr + 4] >> (8 - InBit); + return BitField & 0xffffffff; + } + + //void faddbits(uint Bits); + //uint fgetbits(); + + // Check if buffer has enough space for IncPtr bytes. Returns 'true' + // if buffer will be overflown. + private bool Overflow(uint IncPtr) + { + return InAddr + IncPtr >= MAX_SIZE; + } + + //void SetExternalBuffer(byte *Buf); + } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/FragmentedWindow.unpack50frag_cpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/FragmentedWindow.unpack50frag_cpp.cs index 0c6edc60..66f8d06b 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/FragmentedWindow.unpack50frag_cpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/FragmentedWindow.unpack50frag_cpp.cs @@ -15,169 +15,178 @@ using System; namespace SharpCompress.Compressors.Rar.UnpackV2017 { - internal partial class FragmentedWindow + internal partial class FragmentedWindow { -public FragmentedWindow() -{ - //memset(Mem,0,sizeof(Mem)); - //memset(MemSize,0,sizeof(MemSize)); -} + public FragmentedWindow() + { + //memset(Mem,0,sizeof(Mem)); + //memset(MemSize,0,sizeof(MemSize)); + } -//FragmentedWindow::~FragmentedWindow() -//{ -// Reset(); -//} + //FragmentedWindow::~FragmentedWindow() + //{ + // Reset(); + //} - private void Reset() -{ - for (uint I=0;I=MinSize) - { - NewMem=new byte[Size]; - if (NewMem!=null) - { - break; - } + byte[] NewMem = null; + while (Size >= MinSize) + { + NewMem = new byte[Size]; + if (NewMem != null) + { + break; + } - Size-=Size/32; - } - if (NewMem==null) - //throw std::bad_alloc(); - { - throw new InvalidOperationException(); - } + Size -= Size / 32; + } + if (NewMem == null) + //throw std::bad_alloc(); + { + throw new InvalidOperationException(); + } - // Clean the window to generate the same output when unpacking corrupt - // RAR files, which may access to unused areas of sliding dictionary. - // sharpcompress: don't need this, freshly allocated above - //Utility.Memset(NewMem,0,Size); + // Clean the window to generate the same output when unpacking corrupt + // RAR files, which may access to unused areas of sliding dictionary. + // sharpcompress: don't need this, freshly allocated above + //Utility.Memset(NewMem,0,Size); - Mem[BlockNum]=NewMem; - TotalSize+=Size; - MemSize[BlockNum]=TotalSize; - BlockNum++; - } - if (TotalSize 0) - { - this[UnpPtr]=this[SrcPtr++ & MaxWinMask]; - // We need to have masked UnpPtr after quit from loop, so it must not - // be replaced with '(*this)[UnpPtr++ & MaxWinMask]' - UnpPtr=(UnpPtr+1) & MaxWinMask; - } -} + public void CopyString(uint Length, uint Distance, ref size_t UnpPtr, size_t MaxWinMask) + { + size_t SrcPtr = UnpPtr - Distance; + while (Length-- > 0) + { + this[UnpPtr] = this[SrcPtr++ & MaxWinMask]; + // We need to have masked UnpPtr after quit from loop, so it must not + // be replaced with '(*this)[UnpPtr++ & MaxWinMask]' + UnpPtr = (UnpPtr + 1) & MaxWinMask; + } + } -public void CopyData(byte[] Dest, size_t destOffset, size_t WinPos,size_t Size) -{ - for (size_t I=0;I DestUnpSize; } - public int Char + public int Char { get { @@ -97,9 +105,10 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 } } - public int PpmEscChar { get => PPMEscChar; set => PPMEscChar = value; } + public int PpmEscChar { get => PPMEscChar; set => PPMEscChar = value; } - public static byte[] EnsureCapacity(byte[] array, int length) { + public static byte[] EnsureCapacity(byte[] array, int length) + { return array.Length < length ? new byte[length] : array; } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.rawint_hpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.rawint_hpp.cs index 6f501e88..818d4295 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.rawint_hpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.rawint_hpp.cs @@ -14,109 +14,109 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 { internal partial class Unpack { -//#define rotls(x,n,xsize) (((x)<<(n)) | ((x)>>(xsize-(n)))) -//#define rotrs(x,n,xsize) (((x)>>(n)) | ((x)<<(xsize-(n)))) -//#define rotl32(x,n) rotls(x,n,32) -//#define rotr32(x,n) rotrs(x,n,32) -// -//inline uint RawGet2(const void *Data) -//{ -// byte *D=(byte *)Data; -// return D[0]+(D[1]<<8); -//} + //#define rotls(x,n,xsize) (((x)<<(n)) | ((x)>>(xsize-(n)))) + //#define rotrs(x,n,xsize) (((x)>>(n)) | ((x)<<(xsize-(n)))) + //#define rotl32(x,n) rotls(x,n,32) + //#define rotr32(x,n) rotrs(x,n,32) + // + //inline uint RawGet2(const void *Data) + //{ + // byte *D=(byte *)Data; + // return D[0]+(D[1]<<8); + //} private uint32 RawGet4(byte[] D, int offset) -{ - return (uint)(D[offset]+(D[offset+1]<<8)+(D[offset+2]<<16)+(D[offset+3]<<24)); -} + { + return (uint)(D[offset] + (D[offset + 1] << 8) + (D[offset + 2] << 16) + (D[offset + 3] << 24)); + } -//inline uint64 RawGet8(const void *Data) -//{ -//#if defined(BIG_ENDIAN) || !defined(ALLOW_MISALIGNED) -// byte *D=(byte *)Data; -// return INT32TO64(RawGet4(D+4),RawGet4(D)); -//#else -// return *(uint64 *)Data; -//#endif -//} -// -// -//inline void RawPut2(uint Field,void *Data) -//{ -// byte *D=(byte *)Data; -// D[0]=(byte)(Field); -// D[1]=(byte)(Field>>8); -//} + //inline uint64 RawGet8(const void *Data) + //{ + //#if defined(BIG_ENDIAN) || !defined(ALLOW_MISALIGNED) + // byte *D=(byte *)Data; + // return INT32TO64(RawGet4(D+4),RawGet4(D)); + //#else + // return *(uint64 *)Data; + //#endif + //} + // + // + //inline void RawPut2(uint Field,void *Data) + //{ + // byte *D=(byte *)Data; + // D[0]=(byte)(Field); + // D[1]=(byte)(Field>>8); + //} - private void RawPut4(uint32 Field,byte[] D, int offset) -{ - D[offset]=(byte)(Field); - D[offset+1]=(byte)(Field>>8); - D[offset+2]=(byte)(Field>>16); - D[offset+3]=(byte)(Field>>24); -} + private void RawPut4(uint32 Field, byte[] D, int offset) + { + D[offset] = (byte)(Field); + D[offset + 1] = (byte)(Field >> 8); + D[offset + 2] = (byte)(Field >> 16); + D[offset + 3] = (byte)(Field >> 24); + } -//inline void RawPut8(uint64 Field,void *Data) -//{ -//#if defined(BIG_ENDIAN) || !defined(ALLOW_MISALIGNED) -// byte *D=(byte *)Data; -// D[0]=(byte)(Field); -// D[1]=(byte)(Field>>8); -// D[2]=(byte)(Field>>16); -// D[3]=(byte)(Field>>24); -// D[4]=(byte)(Field>>32); -// D[5]=(byte)(Field>>40); -// D[6]=(byte)(Field>>48); -// D[7]=(byte)(Field>>56); -//#else -// *(uint64 *)Data=Field; -//#endif -//} + //inline void RawPut8(uint64 Field,void *Data) + //{ + //#if defined(BIG_ENDIAN) || !defined(ALLOW_MISALIGNED) + // byte *D=(byte *)Data; + // D[0]=(byte)(Field); + // D[1]=(byte)(Field>>8); + // D[2]=(byte)(Field>>16); + // D[3]=(byte)(Field>>24); + // D[4]=(byte)(Field>>32); + // D[5]=(byte)(Field>>40); + // D[6]=(byte)(Field>>48); + // D[7]=(byte)(Field>>56); + //#else + // *(uint64 *)Data=Field; + //#endif + //} -//#if defined(LITTLE_ENDIAN) && defined(ALLOW_MISALIGNED) -//#define USE_MEM_BYTESWAP -//#endif + //#if defined(LITTLE_ENDIAN) && defined(ALLOW_MISALIGNED) + //#define USE_MEM_BYTESWAP + //#endif -// Load 4 big endian bytes from memory and return uint32. -//inline uint32 RawGetBE4(const byte *m) -//{ -//#if defined(USE_MEM_BYTESWAP) && defined(_MSC_VER) -// return _byteswap_ulong(*(uint32 *)m); -//#elif defined(USE_MEM_BYTESWAP) && (__GNUC__ > 3) && (__GNUC_MINOR__ > 2) -// return __builtin_bswap32(*(uint32 *)m); -//#else -// return uint32(m[0]<<24) | uint32(m[1]<<16) | uint32(m[2]<<8) | m[3]; -//#endif -//} + // Load 4 big endian bytes from memory and return uint32. + //inline uint32 RawGetBE4(const byte *m) + //{ + //#if defined(USE_MEM_BYTESWAP) && defined(_MSC_VER) + // return _byteswap_ulong(*(uint32 *)m); + //#elif defined(USE_MEM_BYTESWAP) && (__GNUC__ > 3) && (__GNUC_MINOR__ > 2) + // return __builtin_bswap32(*(uint32 *)m); + //#else + // return uint32(m[0]<<24) | uint32(m[1]<<16) | uint32(m[2]<<8) | m[3]; + //#endif + //} -// Save integer to memory as big endian. -//inline void RawPutBE4(uint32 i,byte *mem) -//{ -//#if defined(USE_MEM_BYTESWAP) && defined(_MSC_VER) -// *(uint32*)mem = _byteswap_ulong(i); -//#elif defined(USE_MEM_BYTESWAP) && (__GNUC__ > 3) && (__GNUC_MINOR__ > 2) -// *(uint32*)mem = __builtin_bswap32(i); -//#else -// mem[0]=byte(i>>24); -// mem[1]=byte(i>>16); -// mem[2]=byte(i>>8); -// mem[3]=byte(i); -//#endif -//} + // Save integer to memory as big endian. + //inline void RawPutBE4(uint32 i,byte *mem) + //{ + //#if defined(USE_MEM_BYTESWAP) && defined(_MSC_VER) + // *(uint32*)mem = _byteswap_ulong(i); + //#elif defined(USE_MEM_BYTESWAP) && (__GNUC__ > 3) && (__GNUC_MINOR__ > 2) + // *(uint32*)mem = __builtin_bswap32(i); + //#else + // mem[0]=byte(i>>24); + // mem[1]=byte(i>>16); + // mem[2]=byte(i>>8); + // mem[3]=byte(i); + //#endif + //} -//inline uint32 ByteSwap32(uint32 i) -//{ -//#ifdef _MSC_VER -// return _byteswap_ulong(i); -//#elif (__GNUC__ > 3) && (__GNUC_MINOR__ > 2) -// return __builtin_bswap32(i); -//#else -// return (rotl32(i,24)&0xFF00FF00)|(rotl32(i,8)&0x00FF00FF); -//#endif -//} + //inline uint32 ByteSwap32(uint32 i) + //{ + //#ifdef _MSC_VER + // return _byteswap_ulong(i); + //#elif (__GNUC__ > 3) && (__GNUC_MINOR__ > 2) + // return __builtin_bswap32(i); + //#else + // return (rotl32(i,24)&0xFF00FF00)|(rotl32(i,8)&0x00FF00FF); + //#endif + //} } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack15_cpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack15_cpp.cs index 097dc1a0..d3f2bd3a 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack15_cpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack15_cpp.cs @@ -5,597 +5,598 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 { internal partial class Unpack { - private const int STARTL1 =2; + private const int STARTL1 = 2; - private static readonly uint[] DecL1={0x8000,0xa000,0xc000,0xd000,0xe000,0xea00, + private static readonly uint[] DecL1 ={0x8000,0xa000,0xc000,0xd000,0xe000,0xea00, 0xee00,0xf000,0xf200,0xf200,0xffff}; - private static readonly uint[] PosL1={0,0,0,2,3,5,7,11,16,20,24,32,32}; + private static readonly uint[] PosL1 = { 0, 0, 0, 2, 3, 5, 7, 11, 16, 20, 24, 32, 32 }; - private const int STARTL2 =3; + private const int STARTL2 = 3; - private static readonly uint[] DecL2={0xa000,0xc000,0xd000,0xe000,0xea00,0xee00, + private static readonly uint[] DecL2 ={0xa000,0xc000,0xd000,0xe000,0xea00,0xee00, 0xf000,0xf200,0xf240,0xffff}; - private static readonly uint[] PosL2={0,0,0,0,5,7,9,13,18,22,26,34,36}; + private static readonly uint[] PosL2 = { 0, 0, 0, 0, 5, 7, 9, 13, 18, 22, 26, 34, 36 }; - private const int STARTHF0 =4; + private const int STARTHF0 = 4; - private static readonly uint[] DecHf0={0x8000,0xc000,0xe000,0xf200,0xf200,0xf200, + private static readonly uint[] DecHf0 ={0x8000,0xc000,0xe000,0xf200,0xf200,0xf200, 0xf200,0xf200,0xffff}; - private static readonly uint[] PosHf0={0,0,0,0,0,8,16,24,33,33,33,33,33}; + private static readonly uint[] PosHf0 = { 0, 0, 0, 0, 0, 8, 16, 24, 33, 33, 33, 33, 33 }; - private const int STARTHF1 =5; + private const int STARTHF1 = 5; - private static readonly uint[] DecHf1={0x2000,0xc000,0xe000,0xf000,0xf200,0xf200, + private static readonly uint[] DecHf1 ={0x2000,0xc000,0xe000,0xf000,0xf200,0xf200, 0xf7e0,0xffff}; - private static readonly uint[] PosHf1={0,0,0,0,0,0,4,44,60,76,80,80,127}; + private static readonly uint[] PosHf1 = { 0, 0, 0, 0, 0, 0, 4, 44, 60, 76, 80, 80, 127 }; - private const int STARTHF2 =5; + private const int STARTHF2 = 5; - private static readonly uint[] DecHf2={0x1000,0x2400,0x8000,0xc000,0xfa00,0xffff, + private static readonly uint[] DecHf2 ={0x1000,0x2400,0x8000,0xc000,0xfa00,0xffff, 0xffff,0xffff}; - private static readonly uint[] PosHf2={0,0,0,0,0,0,2,7,53,117,233,0,0}; + private static readonly uint[] PosHf2 = { 0, 0, 0, 0, 0, 0, 2, 7, 53, 117, 233, 0, 0 }; - private const int STARTHF3 =6; + private const int STARTHF3 = 6; - private static readonly uint[] DecHf3={0x800,0x2400,0xee00,0xfe80,0xffff,0xffff, + private static readonly uint[] DecHf3 ={0x800,0x2400,0xee00,0xfe80,0xffff,0xffff, 0xffff}; - private static readonly uint[] PosHf3={0,0,0,0,0,0,0,2,16,218,251,0,0}; + private static readonly uint[] PosHf3 = { 0, 0, 0, 0, 0, 0, 0, 2, 16, 218, 251, 0, 0 }; - private const int STARTHF4 =8; - private static readonly uint[] DecHf4={0xff00,0xffff,0xffff,0xffff,0xffff,0xffff}; - private static readonly uint[] PosHf4={0,0,0,0,0,0,0,0,0,255,0,0,0}; + private const int STARTHF4 = 8; + private static readonly uint[] DecHf4 = { 0xff00, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff }; + private static readonly uint[] PosHf4 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0 }; - private void Unpack15(bool Solid) -{ - UnpInitData(Solid); - UnpInitData15(Solid); - UnpReadBuf(); - if (!Solid) - { - InitHuff(); - UnpPtr=0; - } - else - { - UnpPtr=WrPtr; - } - - --DestUnpSize; - if (DestUnpSize>=0) - { - GetFlagsBuf(); - FlagsCnt=8; - } - - while (DestUnpSize>=0) - { - UnpPtr&=MaxWinMask; - - if (Inp.InAddr>ReadTop-30 && !UnpReadBuf()) - { - break; - } - - if (((WrPtr-UnpPtr) & MaxWinMask)<270 && WrPtr!=UnpPtr) - { - UnpWriteBuf20(); - } - - if (StMode != 0) - { - HuffDecode(); - continue; - } - - if (--FlagsCnt < 0) - { - GetFlagsBuf(); - FlagsCnt=7; - } - - if ((FlagBuf & 0x80) != 0) - { - FlagBuf<<=1; - if (Nlzb > Nhfb) - { - LongLZ(); - } - else - { - HuffDecode(); - } - } - else - { - FlagBuf<<=1; - if (--FlagsCnt < 0) - { - GetFlagsBuf(); - FlagsCnt=7; - } - if ((FlagBuf & 0x80) != 0) - { - FlagBuf<<=1; - if (Nlzb > Nhfb) + private void Unpack15(bool Solid) { - HuffDecode(); + UnpInitData(Solid); + UnpInitData15(Solid); + UnpReadBuf(); + if (!Solid) + { + InitHuff(); + UnpPtr = 0; + } + else + { + UnpPtr = WrPtr; + } + + --DestUnpSize; + if (DestUnpSize >= 0) + { + GetFlagsBuf(); + FlagsCnt = 8; + } + + while (DestUnpSize >= 0) + { + UnpPtr &= MaxWinMask; + + if (Inp.InAddr > ReadTop - 30 && !UnpReadBuf()) + { + break; + } + + if (((WrPtr - UnpPtr) & MaxWinMask) < 270 && WrPtr != UnpPtr) + { + UnpWriteBuf20(); + } + + if (StMode != 0) + { + HuffDecode(); + continue; + } + + if (--FlagsCnt < 0) + { + GetFlagsBuf(); + FlagsCnt = 7; + } + + if ((FlagBuf & 0x80) != 0) + { + FlagBuf <<= 1; + if (Nlzb > Nhfb) + { + LongLZ(); + } + else + { + HuffDecode(); + } + } + else + { + FlagBuf <<= 1; + if (--FlagsCnt < 0) + { + GetFlagsBuf(); + FlagsCnt = 7; + } + if ((FlagBuf & 0x80) != 0) + { + FlagBuf <<= 1; + if (Nlzb > Nhfb) + { + HuffDecode(); + } + else + { + LongLZ(); + } + } + else + { + FlagBuf <<= 1; + ShortLZ(); + } + } + } + UnpWriteBuf20(); } - else + + + //#define GetShortLen1(pos) ((pos)==1 ? Buf60+3:ShortLen1[pos]) + private uint GetShortLen1(uint pos) { return ((pos) == 1 ? (uint)(Buf60 + 3) : ShortLen1[pos]); } + //#define GetShortLen2(pos) ((pos)==3 ? Buf60+3:ShortLen2[pos]) + private uint GetShortLen2(uint pos) { return ((pos) == 3 ? (uint)(Buf60 + 3) : ShortLen2[pos]); } + + internal static class Unpack15Local { - LongLZ(); - } - } - else - { - FlagBuf<<=1; - ShortLZ(); - } - } - } - UnpWriteBuf20(); -} - - -//#define GetShortLen1(pos) ((pos)==1 ? Buf60+3:ShortLen1[pos]) - private uint GetShortLen1(uint pos) { return ((pos)==1 ? (uint)(Buf60+3):ShortLen1[pos]); } -//#define GetShortLen2(pos) ((pos)==3 ? Buf60+3:ShortLen2[pos]) - private uint GetShortLen2(uint pos) { return ((pos)==3 ? (uint)(Buf60+3):ShortLen2[pos]); } - -internal static class Unpack15Local { - public static readonly uint[] ShortLen1={1,3,4,4,5,6,7,8,8,4,4,5,6,6,4,0}; - public static readonly uint[] ShortXor1={0,0xa0,0xd0,0xe0,0xf0,0xf8,0xfc,0xfe, + public static readonly uint[] ShortLen1 = { 1, 3, 4, 4, 5, 6, 7, 8, 8, 4, 4, 5, 6, 6, 4, 0 }; + public static readonly uint[] ShortXor1 ={0,0xa0,0xd0,0xe0,0xf0,0xf8,0xfc,0xfe, 0xff,0xc0,0x80,0x90,0x98,0x9c,0xb0}; - public static readonly uint[] ShortLen2={2,3,3,3,4,4,5,6,6,4,4,5,6,6,4,0}; - public static readonly uint[] ShortXor2={0,0x40,0x60,0xa0,0xd0,0xe0,0xf0,0xf8, + public static readonly uint[] ShortLen2 = { 2, 3, 3, 3, 4, 4, 5, 6, 6, 4, 4, 5, 6, 6, 4, 0 }; + public static readonly uint[] ShortXor2 ={0,0x40,0x60,0xa0,0xd0,0xe0,0xf0,0xf8, 0xfc,0xc0,0x80,0x90,0x98,0x9c,0xb0}; -} - - private void ShortLZ() -{ - uint Length,SaveLength; - uint LastDistance; - uint Distance; - int DistancePlace; - NumHuf=0; - - uint BitField=Inp.fgetbits(); - if (LCount==2) - { - Inp.faddbits(1); - if (BitField >= 0x8000) - { - CopyString15((uint)LastDist,LastLength); - return; - } - BitField <<= 1; - LCount=0; - } - - BitField>>=8; - -// not thread safe, replaced by GetShortLen1 and GetShortLen2 macro -// ShortLen1[1]=ShortLen2[3]=Buf60+3; - - if (AvrLn1<37) - { - for (Length=0;;Length++) - { - if (((BitField^ShortXor1[Length]) & (~(0xff>>(int)GetShortLen1(Length))))==0) - { - break; - } - } - - Inp.faddbits(GetShortLen1(Length)); - } - else - { - for (Length=0;;Length++) - { - if (((BitField^ShortXor2[Length]) & (~(0xff>>(int)GetShortLen2(Length))))==0) - { - break; - } - } - - Inp.faddbits(GetShortLen2(Length)); - } - - if (Length >= 9) - { - if (Length == 9) - { - LCount++; - CopyString15((uint)LastDist,LastLength); - return; - } - if (Length == 14) - { - LCount=0; - Length=DecodeNum(Inp.fgetbits(),STARTL2,DecL2,PosL2)+5; - Distance=(Inp.fgetbits()>>1) | 0x8000; - Inp.faddbits(15); - LastLength=Length; - LastDist=Distance; - CopyString15(Distance,Length); - return; - } - - LCount=0; - SaveLength=Length; - Distance=OldDist[(OldDistPtr-(Length-9)) & 3]; - Length=DecodeNum(Inp.fgetbits(),STARTL1,DecL1,PosL1)+2; - if (Length==0x101 && SaveLength==10) - { - Buf60 ^= 1; - return; - } - if (Distance > 256) - { - Length++; - } - - if (Distance >= MaxDist3) - { - Length++; - } - - OldDist[OldDistPtr++]=Distance; - OldDistPtr = OldDistPtr & 3; - LastLength=Length; - LastDist=Distance; - CopyString15(Distance,Length); - return; - } - - LCount=0; - AvrLn1 += Length; - AvrLn1 -= AvrLn1 >> 4; - - DistancePlace=(int)(DecodeNum(Inp.fgetbits(),STARTHF2,DecHf2,PosHf2) & 0xff); - Distance=ChSetA[DistancePlace]; - if (--DistancePlace != -1) - { - LastDistance=ChSetA[DistancePlace]; - ChSetA[DistancePlace+1]=(ushort)LastDistance; - ChSetA[DistancePlace]=(ushort)Distance; - } - Length+=2; - OldDist[OldDistPtr++] = ++Distance; - OldDistPtr = OldDistPtr & 3; - LastLength=Length; - LastDist=Distance; - CopyString15(Distance,Length); -} - - private void LongLZ() -{ - uint Length; - uint Distance; - uint DistancePlace,NewDistancePlace; - uint OldAvr2,OldAvr3; - - NumHuf=0; - Nlzb+=16; - if (Nlzb > 0xff) - { - Nlzb=0x90; - Nhfb >>= 1; - } - OldAvr2=AvrLn2; - - uint BitField=Inp.fgetbits(); - if (AvrLn2 >= 122) - { - Length=DecodeNum(BitField,STARTL2,DecL2,PosL2); - } - else - if (AvrLn2 >= 64) - { - Length=DecodeNum(BitField,STARTL1,DecL1,PosL1); - } - else - if (BitField < 0x100) - { - Length=BitField; - Inp.faddbits(16); - } - else - { - for (Length=0;((BitField<<(int)Length)&0x8000)==0;Length++) - { - ; } - Inp.faddbits(Length+1); - } - - AvrLn2 += Length; - AvrLn2 -= AvrLn2 >> 5; - - BitField=Inp.fgetbits(); - if (AvrPlcB > 0x28ff) - { - DistancePlace=DecodeNum(BitField,STARTHF2,DecHf2,PosHf2); - } - else - if (AvrPlcB > 0x6ff) - { - DistancePlace=DecodeNum(BitField,STARTHF1,DecHf1,PosHf1); - } - else - { - DistancePlace=DecodeNum(BitField,STARTHF0,DecHf0,PosHf0); - } - - AvrPlcB += DistancePlace; - AvrPlcB -= AvrPlcB >> 8; - while (true) - { - Distance = ChSetB[DistancePlace & 0xff]; - NewDistancePlace = NToPlB[Distance++ & 0xff]++; - if ((Distance & 0xff) != 0) - { - CorrHuff(ChSetB,NToPlB); - } - else - { - break; - } - } - - ChSetB[DistancePlace & 0xff]=ChSetB[NewDistancePlace]; - ChSetB[NewDistancePlace]=(ushort)Distance; - - Distance=((Distance & 0xff00) | (Inp.fgetbits() >> 8)) >> 1; - Inp.faddbits(7); - - OldAvr3=AvrLn3; - if (Length!=1 && Length!=4) - { - if (Length==0 && Distance <= MaxDist3) - { - AvrLn3++; - AvrLn3 -= AvrLn3 >> 8; - } - else - if (AvrLn3 > 0) - { - AvrLn3--; - } - } - - Length+=3; - if (Distance >= MaxDist3) - { - Length++; - } - - if (Distance <= 256) - { - Length+=8; - } - - if (OldAvr3 > 0xb0 || AvrPlc >= 0x2a00 && OldAvr2 < 0x40) - { - MaxDist3=0x7f00; - } - else - { - MaxDist3=0x2001; - } - - OldDist[OldDistPtr++]=Distance; - OldDistPtr = OldDistPtr & 3; - LastLength=Length; - LastDist=Distance; - CopyString15(Distance,Length); -} - - private void HuffDecode() -{ - uint CurByte,NewBytePlace; - uint Length; - uint Distance; - int BytePlace; - - uint BitField=Inp.fgetbits(); - - if (AvrPlc > 0x75ff) - { - BytePlace=(int)DecodeNum(BitField,STARTHF4,DecHf4,PosHf4); - } - else - if (AvrPlc > 0x5dff) - { - BytePlace=(int)DecodeNum(BitField,STARTHF3,DecHf3,PosHf3); - } - else - if (AvrPlc > 0x35ff) - { - BytePlace=(int)DecodeNum(BitField,STARTHF2,DecHf2,PosHf2); - } - else - if (AvrPlc > 0x0dff) + private void ShortLZ() { - BytePlace=(int)DecodeNum(BitField,STARTHF1,DecHf1,PosHf1); - } - else - { - BytePlace=(int)DecodeNum(BitField,STARTHF0,DecHf0,PosHf0); + uint Length, SaveLength; + uint LastDistance; + uint Distance; + int DistancePlace; + NumHuf = 0; + + uint BitField = Inp.fgetbits(); + if (LCount == 2) + { + Inp.faddbits(1); + if (BitField >= 0x8000) + { + CopyString15((uint)LastDist, LastLength); + return; + } + BitField <<= 1; + LCount = 0; + } + + BitField >>= 8; + + // not thread safe, replaced by GetShortLen1 and GetShortLen2 macro + // ShortLen1[1]=ShortLen2[3]=Buf60+3; + + if (AvrLn1 < 37) + { + for (Length = 0; ; Length++) + { + if (((BitField ^ ShortXor1[Length]) & (~(0xff >> (int)GetShortLen1(Length)))) == 0) + { + break; + } + } + + Inp.faddbits(GetShortLen1(Length)); + } + else + { + for (Length = 0; ; Length++) + { + if (((BitField ^ ShortXor2[Length]) & (~(0xff >> (int)GetShortLen2(Length)))) == 0) + { + break; + } + } + + Inp.faddbits(GetShortLen2(Length)); + } + + if (Length >= 9) + { + if (Length == 9) + { + LCount++; + CopyString15((uint)LastDist, LastLength); + return; + } + if (Length == 14) + { + LCount = 0; + Length = DecodeNum(Inp.fgetbits(), STARTL2, DecL2, PosL2) + 5; + Distance = (Inp.fgetbits() >> 1) | 0x8000; + Inp.faddbits(15); + LastLength = Length; + LastDist = Distance; + CopyString15(Distance, Length); + return; + } + + LCount = 0; + SaveLength = Length; + Distance = OldDist[(OldDistPtr - (Length - 9)) & 3]; + Length = DecodeNum(Inp.fgetbits(), STARTL1, DecL1, PosL1) + 2; + if (Length == 0x101 && SaveLength == 10) + { + Buf60 ^= 1; + return; + } + if (Distance > 256) + { + Length++; + } + + if (Distance >= MaxDist3) + { + Length++; + } + + OldDist[OldDistPtr++] = Distance; + OldDistPtr = OldDistPtr & 3; + LastLength = Length; + LastDist = Distance; + CopyString15(Distance, Length); + return; + } + + LCount = 0; + AvrLn1 += Length; + AvrLn1 -= AvrLn1 >> 4; + + DistancePlace = (int)(DecodeNum(Inp.fgetbits(), STARTHF2, DecHf2, PosHf2) & 0xff); + Distance = ChSetA[DistancePlace]; + if (--DistancePlace != -1) + { + LastDistance = ChSetA[DistancePlace]; + ChSetA[DistancePlace + 1] = (ushort)LastDistance; + ChSetA[DistancePlace] = (ushort)Distance; + } + Length += 2; + OldDist[OldDistPtr++] = ++Distance; + OldDistPtr = OldDistPtr & 3; + LastLength = Length; + LastDist = Distance; + CopyString15(Distance, Length); } - BytePlace&=0xff; - if (StMode != 0) - { - if (BytePlace==0 && BitField > 0xfff) - { - BytePlace=0x100; - } + private void LongLZ() + { + uint Length; + uint Distance; + uint DistancePlace, NewDistancePlace; + uint OldAvr2, OldAvr3; - if (--BytePlace==-1) - { - BitField=Inp.fgetbits(); - Inp.faddbits(1); - if ((BitField & 0x8000) != 0) - { - NumHuf=StMode=0; - return; - } - else - { - Length = (BitField & 0x4000) != 0 ? 4U : 3; - Inp.faddbits(1); - Distance=DecodeNum(Inp.fgetbits(),STARTHF2,DecHf2,PosHf2); - Distance = (Distance << 5) | (Inp.fgetbits() >> 11); - Inp.faddbits(5); - CopyString15(Distance,Length); - return; - } - } - } - else - if (NumHuf++ >= 16 && FlagsCnt==0) - { - StMode=1; - } + NumHuf = 0; + Nlzb += 16; + if (Nlzb > 0xff) + { + Nlzb = 0x90; + Nhfb >>= 1; + } + OldAvr2 = AvrLn2; - AvrPlc += (uint)BytePlace; - AvrPlc -= AvrPlc >> 8; - Nhfb+=16; - if (Nhfb > 0xff) - { - Nhfb=0x90; - Nlzb >>= 1; - } + uint BitField = Inp.fgetbits(); + if (AvrLn2 >= 122) + { + Length = DecodeNum(BitField, STARTL2, DecL2, PosL2); + } + else + if (AvrLn2 >= 64) + { + Length = DecodeNum(BitField, STARTL1, DecL1, PosL1); + } + else + if (BitField < 0x100) + { + Length = BitField; + Inp.faddbits(16); + } + else + { + for (Length = 0; ((BitField << (int)Length) & 0x8000) == 0; Length++) + { + ; + } - Window[UnpPtr++]=(byte)(ChSet[BytePlace]>>8); - --DestUnpSize; + Inp.faddbits(Length + 1); + } - while (true) - { - CurByte=ChSet[BytePlace]; - NewBytePlace=NToPl[CurByte++ & 0xff]++; - if ((CurByte & 0xff) > 0xa1) - { - CorrHuff(ChSet,NToPl); - } - else - { - break; - } - } + AvrLn2 += Length; + AvrLn2 -= AvrLn2 >> 5; - ChSet[BytePlace]=ChSet[NewBytePlace]; - ChSet[NewBytePlace]=(ushort)CurByte; -} + BitField = Inp.fgetbits(); + if (AvrPlcB > 0x28ff) + { + DistancePlace = DecodeNum(BitField, STARTHF2, DecHf2, PosHf2); + } + else + if (AvrPlcB > 0x6ff) + { + DistancePlace = DecodeNum(BitField, STARTHF1, DecHf1, PosHf1); + } + else + { + DistancePlace = DecodeNum(BitField, STARTHF0, DecHf0, PosHf0); + } - private void GetFlagsBuf() -{ - uint Flags,NewFlagsPlace; - uint FlagsPlace=DecodeNum(Inp.fgetbits(),STARTHF2,DecHf2,PosHf2); + AvrPlcB += DistancePlace; + AvrPlcB -= AvrPlcB >> 8; + while (true) + { + Distance = ChSetB[DistancePlace & 0xff]; + NewDistancePlace = NToPlB[Distance++ & 0xff]++; + if ((Distance & 0xff) != 0) + { + CorrHuff(ChSetB, NToPlB); + } + else + { + break; + } + } - // Our Huffman table stores 257 items and needs all them in other parts - // of code such as when StMode is on, so the first item is control item. - // While normally we do not use the last item to code the flags byte here, - // we need to check for value 256 when unpacking in case we unpack - // a corrupt archive. - if (FlagsPlace>=ChSetC.Length) - { - return; - } + ChSetB[DistancePlace & 0xff] = ChSetB[NewDistancePlace]; + ChSetB[NewDistancePlace] = (ushort)Distance; - while (true) - { - Flags=ChSetC[FlagsPlace]; - FlagBuf=Flags>>8; - NewFlagsPlace=NToPlC[Flags++ & 0xff]++; - if ((Flags & 0xff) != 0) - { - break; - } + Distance = ((Distance & 0xff00) | (Inp.fgetbits() >> 8)) >> 1; + Inp.faddbits(7); - CorrHuff(ChSetC,NToPlC); - } + OldAvr3 = AvrLn3; + if (Length != 1 && Length != 4) + { + if (Length == 0 && Distance <= MaxDist3) + { + AvrLn3++; + AvrLn3 -= AvrLn3 >> 8; + } + else + if (AvrLn3 > 0) + { + AvrLn3--; + } + } - ChSetC[FlagsPlace]=ChSetC[NewFlagsPlace]; - ChSetC[NewFlagsPlace]=(ushort)Flags; -} + Length += 3; + if (Distance >= MaxDist3) + { + Length++; + } - private void UnpInitData15(bool Solid) -{ - if (!Solid) - { - AvrPlcB=AvrLn1=AvrLn2=AvrLn3=0; - NumHuf=Buf60=0; - AvrPlc=0x3500; - MaxDist3=0x2001; - Nhfb=Nlzb=0x80; - } - FlagsCnt=0; - FlagBuf=0; - StMode=0; - LCount=0; - ReadTop=0; -} + if (Distance <= 256) + { + Length += 8; + } - private void InitHuff() -{ - for (uint I=0;I<256;I++) - { - ChSet[I]=ChSetB[I]=(ushort)(I<<8); - ChSetA[I]=(ushort)I; - ChSetC[I]=(ushort)(((~I+1) & 0xff)<<8); - } - new Span(NToPl).Clear(); - new Span(NToPlB).Clear(); - new Span(NToPlC).Clear(); - CorrHuff(ChSetB,NToPlB); -} + if (OldAvr3 > 0xb0 || AvrPlc >= 0x2a00 && OldAvr2 < 0x40) + { + MaxDist3 = 0x7f00; + } + else + { + MaxDist3 = 0x2001; + } - private void CorrHuff(ushort[] CharSet,byte[] NumToPlace) -{ - int I,J; - for (I=7;I>=0;I--) - for (J=0;J<32;J++) - { - CharSet[J]=(ushort)((CharSet[J] & ~0xff) | I); - } + OldDist[OldDistPtr++] = Distance; + OldDistPtr = OldDistPtr & 3; + LastLength = Length; + LastDist = Distance; + CopyString15(Distance, Length); + } - new Span(NumToPlace, 0, NToPl.Length).Clear(); - for (I=6;I>=0;I--) - { - NumToPlace[I]=(byte)((7-I)*32); - } -} + private void HuffDecode() + { + uint CurByte, NewBytePlace; + uint Length; + uint Distance; + int BytePlace; - private void CopyString15(uint Distance,uint Length) -{ - DestUnpSize-=Length; - while (Length-- != 0) - { - Window[UnpPtr]=Window[(UnpPtr-Distance) & MaxWinMask]; - UnpPtr=(UnpPtr+1) & MaxWinMask; - } -} + uint BitField = Inp.fgetbits(); - private uint DecodeNum(uint Num,uint StartPos,uint[] DecTab,uint[] PosTab) -{ - int I; - for (Num&=0xfff0,I=0;DecTab[I]<=Num;I++) - { - StartPos++; - } + if (AvrPlc > 0x75ff) + { + BytePlace = (int)DecodeNum(BitField, STARTHF4, DecHf4, PosHf4); + } + else + if (AvrPlc > 0x5dff) + { + BytePlace = (int)DecodeNum(BitField, STARTHF3, DecHf3, PosHf3); + } + else + if (AvrPlc > 0x35ff) + { + BytePlace = (int)DecodeNum(BitField, STARTHF2, DecHf2, PosHf2); + } + else + if (AvrPlc > 0x0dff) + { + BytePlace = (int)DecodeNum(BitField, STARTHF1, DecHf1, PosHf1); + } + else + { + BytePlace = (int)DecodeNum(BitField, STARTHF0, DecHf0, PosHf0); + } - Inp.faddbits(StartPos); - return(((Num-(I != 0 ? DecTab[I-1]:0))>>(int)(16-StartPos))+PosTab[StartPos]); -} + BytePlace &= 0xff; + if (StMode != 0) + { + if (BytePlace == 0 && BitField > 0xfff) + { + BytePlace = 0x100; + } + + if (--BytePlace == -1) + { + BitField = Inp.fgetbits(); + Inp.faddbits(1); + if ((BitField & 0x8000) != 0) + { + NumHuf = StMode = 0; + return; + } + else + { + Length = (BitField & 0x4000) != 0 ? 4U : 3; + Inp.faddbits(1); + Distance = DecodeNum(Inp.fgetbits(), STARTHF2, DecHf2, PosHf2); + Distance = (Distance << 5) | (Inp.fgetbits() >> 11); + Inp.faddbits(5); + CopyString15(Distance, Length); + return; + } + } + } + else + if (NumHuf++ >= 16 && FlagsCnt == 0) + { + StMode = 1; + } + + AvrPlc += (uint)BytePlace; + AvrPlc -= AvrPlc >> 8; + Nhfb += 16; + if (Nhfb > 0xff) + { + Nhfb = 0x90; + Nlzb >>= 1; + } + + Window[UnpPtr++] = (byte)(ChSet[BytePlace] >> 8); + --DestUnpSize; + + while (true) + { + CurByte = ChSet[BytePlace]; + NewBytePlace = NToPl[CurByte++ & 0xff]++; + if ((CurByte & 0xff) > 0xa1) + { + CorrHuff(ChSet, NToPl); + } + else + { + break; + } + } + + ChSet[BytePlace] = ChSet[NewBytePlace]; + ChSet[NewBytePlace] = (ushort)CurByte; + } + + private void GetFlagsBuf() + { + uint Flags, NewFlagsPlace; + uint FlagsPlace = DecodeNum(Inp.fgetbits(), STARTHF2, DecHf2, PosHf2); + + // Our Huffman table stores 257 items and needs all them in other parts + // of code such as when StMode is on, so the first item is control item. + // While normally we do not use the last item to code the flags byte here, + // we need to check for value 256 when unpacking in case we unpack + // a corrupt archive. + if (FlagsPlace >= ChSetC.Length) + { + return; + } + + while (true) + { + Flags = ChSetC[FlagsPlace]; + FlagBuf = Flags >> 8; + NewFlagsPlace = NToPlC[Flags++ & 0xff]++; + if ((Flags & 0xff) != 0) + { + break; + } + + CorrHuff(ChSetC, NToPlC); + } + + ChSetC[FlagsPlace] = ChSetC[NewFlagsPlace]; + ChSetC[NewFlagsPlace] = (ushort)Flags; + } + + private void UnpInitData15(bool Solid) + { + if (!Solid) + { + AvrPlcB = AvrLn1 = AvrLn2 = AvrLn3 = 0; + NumHuf = Buf60 = 0; + AvrPlc = 0x3500; + MaxDist3 = 0x2001; + Nhfb = Nlzb = 0x80; + } + FlagsCnt = 0; + FlagBuf = 0; + StMode = 0; + LCount = 0; + ReadTop = 0; + } + + private void InitHuff() + { + for (uint I = 0; I < 256; I++) + { + ChSet[I] = ChSetB[I] = (ushort)(I << 8); + ChSetA[I] = (ushort)I; + ChSetC[I] = (ushort)(((~I + 1) & 0xff) << 8); + } + new Span(NToPl).Clear(); + new Span(NToPlB).Clear(); + new Span(NToPlC).Clear(); + CorrHuff(ChSetB, NToPlB); + } + + private void CorrHuff(ushort[] CharSet, byte[] NumToPlace) + { + int I, J; + for (I = 7; I >= 0; I--) + for (J = 0; J < 32; J++) + { + CharSet[J] = (ushort)((CharSet[J] & ~0xff) | I); + } + + new Span(NumToPlace, 0, NToPl.Length).Clear(); + for (I = 6; I >= 0; I--) + { + NumToPlace[I] = (byte)((7 - I) * 32); + } + } + + private void CopyString15(uint Distance, uint Length) + { + DestUnpSize -= Length; + while (Length-- != 0) + { + Window[UnpPtr] = Window[(UnpPtr - Distance) & MaxWinMask]; + UnpPtr = (UnpPtr + 1) & MaxWinMask; + } + } + + private uint DecodeNum(uint Num, uint StartPos, uint[] DecTab, uint[] PosTab) + { + int I; + for (Num &= 0xfff0, I = 0; DecTab[I] <= Num; I++) + { + StartPos++; + } + + Inp.faddbits(StartPos); + return (((Num - (I != 0 ? DecTab[I - 1] : 0)) >> (int)(16 - StartPos)) + PosTab[StartPos]); + } } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack20_cpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack20_cpp.cs index 56a65c5c..7f59f6dd 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack20_cpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack20_cpp.cs @@ -17,484 +17,485 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 { internal partial class Unpack { - private void CopyString20(uint Length,uint Distance) -{ - LastDist=OldDist[OldDistPtr++ & 3]=Distance; - LastLength=Length; - DestUnpSize-=Length; - CopyString(Length,Distance); -} - - -internal static class Unpack20Local { - public static readonly byte[] LDecode={0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224}; - public static readonly byte[] LBits= {0,0,0,0,0,0,0,0,1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5}; - public static readonly uint[] DDecode={0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096,6144,8192,12288,16384,24576,32768U,49152U,65536,98304,131072,196608,262144,327680,393216,458752,524288,589824,655360,720896,786432,851968,917504,983040}; - public static readonly byte[] DBits= {0,0,0,0,1,1,2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16}; - public static readonly byte[] SDDecode={0,4,8,16,32,64,128,192}; - public static readonly byte[] SDBits= {2,2,3, 4, 5, 6, 6, 6}; -} - - private void Unpack20(bool Solid) -{ - uint Bits; - - if (Suspended) - { - UnpPtr=WrPtr; - } - else - { - UnpInitData(Solid); - if (!UnpReadBuf()) - { - return; - } - - if ((!Solid || !TablesRead2) && !ReadTables20()) - { - return; - } - - --DestUnpSize; - } - - while (DestUnpSize>=0) - { - UnpPtr&=MaxWinMask; - - if (Inp.InAddr>ReadTop-30) - { - if (!UnpReadBuf()) - { - break; - } - } - - if (((WrPtr-UnpPtr) & MaxWinMask)<270 && WrPtr!=UnpPtr) - { - UnpWriteBuf20(); - if (Suspended) - { - return; - } - } - if (UnpAudioBlock) - { - uint AudioNumber=DecodeNumber(Inp,MD[UnpCurChannel]); - - if (AudioNumber==256) - { - if (!ReadTables20()) + private void CopyString20(uint Length, uint Distance) { - break; + LastDist = OldDist[OldDistPtr++ & 3] = Distance; + LastLength = Length; + DestUnpSize -= Length; + CopyString(Length, Distance); } - continue; - } - Window[UnpPtr++]=DecodeAudio((int)AudioNumber); - if (++UnpCurChannel==UnpChannels) - { - UnpCurChannel=0; - } - --DestUnpSize; - continue; - } - - uint Number=DecodeNumber(Inp,BlockTables.LD); - if (Number<256) - { - Window[UnpPtr++]=(byte)Number; - --DestUnpSize; - continue; - } - if (Number>269) - { - uint Length=(uint)(LDecode[Number-=270]+3); - if ((Bits=LBits[Number])>0) - { - Length+=Inp.getbits()>>(int)(16-Bits); - Inp.addbits(Bits); - } - - uint DistNumber=DecodeNumber(Inp,BlockTables.DD); - uint Distance=DDecode[DistNumber]+1; - if ((Bits=DBits[DistNumber])>0) - { - Distance+=Inp.getbits()>>(int)(16-Bits); - Inp.addbits(Bits); - } - - if (Distance>=0x2000) - { - Length++; - if (Distance>=0x40000L) + internal static class Unpack20Local { - Length++; - } - } - - CopyString20(Length,Distance); - continue; - } - if (Number==269) - { - if (!ReadTables20()) - { - break; - } - - continue; - } - if (Number==256) - { - CopyString20(LastLength,LastDist); - continue; - } - if (Number<261) - { - uint Distance=OldDist[(OldDistPtr-(Number-256)) & 3]; - uint LengthNumber=DecodeNumber(Inp,BlockTables.RD); - uint Length=(uint)(LDecode[LengthNumber]+2); - if ((Bits=LBits[LengthNumber])>0) - { - Length+=Inp.getbits()>>(int)(16-Bits); - Inp.addbits(Bits); - } - if (Distance>=0x101) - { - Length++; - if (Distance>=0x2000) - { - Length++; - if (Distance>=0x40000) - { - Length++; - } - } - } - CopyString20(Length,Distance); - continue; - } - if (Number<270) - { - uint Distance=(uint)(SDDecode[Number-=261]+1); - if ((Bits=SDBits[Number])>0) - { - Distance+=Inp.getbits()>>(int)(16-Bits); - Inp.addbits(Bits); - } - CopyString20(2,Distance); - continue; - } - } - ReadLastTables(); - UnpWriteBuf20(); -} - - private void UnpWriteBuf20() -{ - if (UnpPtr!=WrPtr) - { - UnpSomeRead=true; - } - - if (UnpPtrReadTop-25) - { - if (!UnpReadBuf()) - { - return false; - } - } - - uint BitField=Inp.getbits(); - UnpAudioBlock=(BitField & 0x8000)!=0; - - if ((BitField & 0x4000) != 0) - { - new Span(UnpOldTable20).Clear(); - } - - Inp.addbits(2); - - uint TableSize; - if (UnpAudioBlock) - { - UnpChannels=((BitField>>12) & 3)+1; - if (UnpCurChannel>=UnpChannels) - { - UnpCurChannel=0; - } - - Inp.addbits(2); - TableSize=MC20*UnpChannels; - } - else - { - TableSize=NC20+DC20+RC20; - } - - for (uint I=0;I> 12); - Inp.addbits(4); - } - MakeDecodeTables(BitLength,0,BlockTables.BD,BC20); - for (uint I=0;IReadTop-5) - { - if (!UnpReadBuf()) - { - return false; - } - } - - uint Number=DecodeNumber(Inp,BlockTables.BD); - if (Number<16) - { - Table[I]=(byte)((Number+UnpOldTable20[I]) & 0xf); - I++; - } - else - if (Number==16) - { - uint N=(Inp.getbits() >> 14)+3; - Inp.addbits(2); - if (I==0) - { - return false; // We cannot have "repeat previous" code at the first position. - } - else - { - while (N-- > 0 && I> 13)+3; - Inp.addbits(3); - } - else - { - N=(Inp.getbits() >> 9)+11; - Inp.addbits(7); - } - while (N-- > 0 && IReadTop) - { - return true; - } - - if (UnpAudioBlock) - { - for (uint I=0;I=Inp.InAddr+5) - { - if (UnpAudioBlock) - { - if (DecodeNumber(Inp,MD[UnpCurChannel])==256) - { - ReadTables20(); - } - } - else - if (DecodeNumber(Inp,BlockTables.LD)==269) - { - ReadTables20(); - } - } -} - - private void UnpInitData20(bool Solid) -{ - if (!Solid) - { - TablesRead2=false; - UnpAudioBlock=false; - UnpChannelDelta=0; - UnpCurChannel=0; - UnpChannels=1; - - //memset(AudV,0,sizeof(AudV)); - AudV = new AudioVariables[4]; - new Span(UnpOldTable20).Clear(); - //memset(MD,0,sizeof(MD)); - MD = new DecodeTable[4]; - } -} - - private byte DecodeAudio(int Delta) -{ - AudioVariables V=AudV[UnpCurChannel]; - V.ByteCount++; - V.D4=V.D3; - V.D3=V.D2; - V.D2=V.LastDelta-V.D1; - V.D1=V.LastDelta; - int PCh=8*V.LastChar+V.K1*V.D1+V.K2*V.D2+V.K3*V.D3+V.K4*V.D4+V.K5*UnpChannelDelta; - PCh=(PCh>>3) & 0xFF; - - uint Ch=(uint)(PCh-Delta); - - int D=(sbyte)Delta; - // Left shift of negative value is undefined behavior in C++, - // so we cast it to unsigned to follow the standard. - D=(int)((uint)D<<3); - - V.Dif[0]+=(uint)Math.Abs(D); - V.Dif[1]+=(uint)Math.Abs(D-V.D1); - V.Dif[2]+=(uint)Math.Abs(D+V.D1); - V.Dif[3]+=(uint)Math.Abs(D-V.D2); - V.Dif[4]+=(uint)Math.Abs(D+V.D2); - V.Dif[5]+=(uint)Math.Abs(D-V.D3); - V.Dif[6]+=(uint)Math.Abs(D+V.D3); - V.Dif[7]+=(uint)Math.Abs(D-V.D4); - V.Dif[8]+=(uint)Math.Abs(D+V.D4); - V.Dif[9]+=(uint)Math.Abs(D-UnpChannelDelta); - V.Dif[10]+=(uint)Math.Abs(D+UnpChannelDelta); - - UnpChannelDelta=V.LastDelta=(sbyte)(Ch-V.LastChar); - V.LastChar=(int)Ch; - - if ((V.ByteCount & 0x1F)==0) - { - uint MinDif=V.Dif[0],NumMinDif=0; - V.Dif[0]=0; - for (uint I=1;I=-16) - { - V.K1--; + public static readonly byte[] LDecode = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224 }; + public static readonly byte[] LBits = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; + public static readonly uint[] DDecode = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576, 32768U, 49152U, 65536, 98304, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 655360, 720896, 786432, 851968, 917504, 983040 }; + public static readonly byte[] DBits = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; + public static readonly byte[] SDDecode = { 0, 4, 8, 16, 32, 64, 128, 192 }; + public static readonly byte[] SDBits = { 2, 2, 3, 4, 5, 6, 6, 6 }; } - break; - case 2: - if (V.K1<16) + private void Unpack20(bool Solid) { - V.K1++; + uint Bits; + + if (Suspended) + { + UnpPtr = WrPtr; + } + else + { + UnpInitData(Solid); + if (!UnpReadBuf()) + { + return; + } + + if ((!Solid || !TablesRead2) && !ReadTables20()) + { + return; + } + + --DestUnpSize; + } + + while (DestUnpSize >= 0) + { + UnpPtr &= MaxWinMask; + + if (Inp.InAddr > ReadTop - 30) + { + if (!UnpReadBuf()) + { + break; + } + } + + if (((WrPtr - UnpPtr) & MaxWinMask) < 270 && WrPtr != UnpPtr) + { + UnpWriteBuf20(); + if (Suspended) + { + return; + } + } + if (UnpAudioBlock) + { + uint AudioNumber = DecodeNumber(Inp, MD[UnpCurChannel]); + + if (AudioNumber == 256) + { + if (!ReadTables20()) + { + break; + } + + continue; + } + Window[UnpPtr++] = DecodeAudio((int)AudioNumber); + if (++UnpCurChannel == UnpChannels) + { + UnpCurChannel = 0; + } + + --DestUnpSize; + continue; + } + + uint Number = DecodeNumber(Inp, BlockTables.LD); + if (Number < 256) + { + Window[UnpPtr++] = (byte)Number; + --DestUnpSize; + continue; + } + if (Number > 269) + { + uint Length = (uint)(LDecode[Number -= 270] + 3); + if ((Bits = LBits[Number]) > 0) + { + Length += Inp.getbits() >> (int)(16 - Bits); + Inp.addbits(Bits); + } + + uint DistNumber = DecodeNumber(Inp, BlockTables.DD); + uint Distance = DDecode[DistNumber] + 1; + if ((Bits = DBits[DistNumber]) > 0) + { + Distance += Inp.getbits() >> (int)(16 - Bits); + Inp.addbits(Bits); + } + + if (Distance >= 0x2000) + { + Length++; + if (Distance >= 0x40000L) + { + Length++; + } + } + + CopyString20(Length, Distance); + continue; + } + if (Number == 269) + { + if (!ReadTables20()) + { + break; + } + + continue; + } + if (Number == 256) + { + CopyString20(LastLength, LastDist); + continue; + } + if (Number < 261) + { + uint Distance = OldDist[(OldDistPtr - (Number - 256)) & 3]; + uint LengthNumber = DecodeNumber(Inp, BlockTables.RD); + uint Length = (uint)(LDecode[LengthNumber] + 2); + if ((Bits = LBits[LengthNumber]) > 0) + { + Length += Inp.getbits() >> (int)(16 - Bits); + Inp.addbits(Bits); + } + if (Distance >= 0x101) + { + Length++; + if (Distance >= 0x2000) + { + Length++; + if (Distance >= 0x40000) + { + Length++; + } + } + } + CopyString20(Length, Distance); + continue; + } + if (Number < 270) + { + uint Distance = (uint)(SDDecode[Number -= 261] + 1); + if ((Bits = SDBits[Number]) > 0) + { + Distance += Inp.getbits() >> (int)(16 - Bits); + Inp.addbits(Bits); + } + CopyString20(2, Distance); + continue; + } + } + ReadLastTables(); + UnpWriteBuf20(); } - break; - case 3: - if (V.K2>=-16) + private void UnpWriteBuf20() { - V.K2--; + if (UnpPtr != WrPtr) + { + UnpSomeRead = true; + } + + if (UnpPtr < WrPtr) + { + UnpIO_UnpWrite(Window, WrPtr, (uint)(-(int)WrPtr & MaxWinMask)); + UnpIO_UnpWrite(Window, 0, UnpPtr); + UnpAllBuf = true; + } + else + { + UnpIO_UnpWrite(Window, WrPtr, UnpPtr - WrPtr); + } + + WrPtr = UnpPtr; } - break; - case 4: - if (V.K2<16) + private bool ReadTables20() { - V.K2++; + byte[] BitLength = new byte[BC20]; + byte[] Table = new byte[MC20 * 4]; + if (Inp.InAddr > ReadTop - 25) + { + if (!UnpReadBuf()) + { + return false; + } + } + + uint BitField = Inp.getbits(); + UnpAudioBlock = (BitField & 0x8000) != 0; + + if ((BitField & 0x4000) != 0) + { + new Span(UnpOldTable20).Clear(); + } + + Inp.addbits(2); + + uint TableSize; + if (UnpAudioBlock) + { + UnpChannels = ((BitField >> 12) & 3) + 1; + if (UnpCurChannel >= UnpChannels) + { + UnpCurChannel = 0; + } + + Inp.addbits(2); + TableSize = MC20 * UnpChannels; + } + else + { + TableSize = NC20 + DC20 + RC20; + } + + for (uint I = 0; I < BC20; I++) + { + BitLength[I] = (byte)(Inp.getbits() >> 12); + Inp.addbits(4); + } + MakeDecodeTables(BitLength, 0, BlockTables.BD, BC20); + for (uint I = 0; I < TableSize;) + { + if (Inp.InAddr > ReadTop - 5) + { + if (!UnpReadBuf()) + { + return false; + } + } + + uint Number = DecodeNumber(Inp, BlockTables.BD); + if (Number < 16) + { + Table[I] = (byte)((Number + UnpOldTable20[I]) & 0xf); + I++; + } + else + if (Number == 16) + { + uint N = (Inp.getbits() >> 14) + 3; + Inp.addbits(2); + if (I == 0) + { + return false; // We cannot have "repeat previous" code at the first position. + } + else + { + while (N-- > 0 && I < TableSize) + { + Table[I] = Table[I - 1]; + I++; + } + } + } + else + { + uint N; + if (Number == 17) + { + N = (Inp.getbits() >> 13) + 3; + Inp.addbits(3); + } + else + { + N = (Inp.getbits() >> 9) + 11; + Inp.addbits(7); + } + while (N-- > 0 && I < TableSize) + { + Table[I++] = 0; + } + } + } + TablesRead2 = true; + if (Inp.InAddr > ReadTop) + { + return true; + } + + if (UnpAudioBlock) + { + for (uint I = 0; I < UnpChannels; I++) + { + MakeDecodeTables(Table, (int)(I * MC20), MD[I], MC20); + } + } + else + { + MakeDecodeTables(Table, 0, BlockTables.LD, NC20); + MakeDecodeTables(Table, (int)NC20, BlockTables.DD, DC20); + MakeDecodeTables(Table, (int)(NC20 + DC20), BlockTables.RD, RC20); + } + //x memcpy(UnpOldTable20,Table,sizeof(UnpOldTable20)); + Array.Copy(Table, UnpOldTable20, UnpOldTable20.Length); + return true; } - break; - case 5: - if (V.K3>=-16) + private void ReadLastTables() { - V.K3--; + if (ReadTop >= Inp.InAddr + 5) + { + if (UnpAudioBlock) + { + if (DecodeNumber(Inp, MD[UnpCurChannel]) == 256) + { + ReadTables20(); + } + } + else + if (DecodeNumber(Inp, BlockTables.LD) == 269) + { + ReadTables20(); + } + } } - break; - case 6: - if (V.K3<16) + private void UnpInitData20(bool Solid) { - V.K3++; + if (!Solid) + { + TablesRead2 = false; + UnpAudioBlock = false; + UnpChannelDelta = 0; + UnpCurChannel = 0; + UnpChannels = 1; + + //memset(AudV,0,sizeof(AudV)); + AudV = new AudioVariables[4]; + new Span(UnpOldTable20).Clear(); + //memset(MD,0,sizeof(MD)); + MD = new DecodeTable[4]; + } } - break; - case 7: - if (V.K4>=-16) + private byte DecodeAudio(int Delta) { - V.K4--; - } + AudioVariables V = AudV[UnpCurChannel]; + V.ByteCount++; + V.D4 = V.D3; + V.D3 = V.D2; + V.D2 = V.LastDelta - V.D1; + V.D1 = V.LastDelta; + int PCh = 8 * V.LastChar + V.K1 * V.D1 + V.K2 * V.D2 + V.K3 * V.D3 + V.K4 * V.D4 + V.K5 * UnpChannelDelta; + PCh = (PCh >> 3) & 0xFF; - break; - case 8: - if (V.K4<16) - { - V.K4++; - } + uint Ch = (uint)(PCh - Delta); - break; - case 9: - if (V.K5>=-16) - { - V.K5--; - } + int D = (sbyte)Delta; + // Left shift of negative value is undefined behavior in C++, + // so we cast it to unsigned to follow the standard. + D = (int)((uint)D << 3); - break; - case 10: - if (V.K5<16) - { - V.K5++; - } + V.Dif[0] += (uint)Math.Abs(D); + V.Dif[1] += (uint)Math.Abs(D - V.D1); + V.Dif[2] += (uint)Math.Abs(D + V.D1); + V.Dif[3] += (uint)Math.Abs(D - V.D2); + V.Dif[4] += (uint)Math.Abs(D + V.D2); + V.Dif[5] += (uint)Math.Abs(D - V.D3); + V.Dif[6] += (uint)Math.Abs(D + V.D3); + V.Dif[7] += (uint)Math.Abs(D - V.D4); + V.Dif[8] += (uint)Math.Abs(D + V.D4); + V.Dif[9] += (uint)Math.Abs(D - UnpChannelDelta); + V.Dif[10] += (uint)Math.Abs(D + UnpChannelDelta); - break; - } - } - return (byte)Ch; -} + UnpChannelDelta = V.LastDelta = (sbyte)(Ch - V.LastChar); + V.LastChar = (int)Ch; + + if ((V.ByteCount & 0x1F) == 0) + { + uint MinDif = V.Dif[0], NumMinDif = 0; + V.Dif[0] = 0; + for (uint I = 1; I < V.Dif.Length; I++) + { + if (V.Dif[I] < MinDif) + { + MinDif = V.Dif[I]; + NumMinDif = I; + } + V.Dif[I] = 0; + } + switch (NumMinDif) + { + case 1: + if (V.K1 >= -16) + { + V.K1--; + } + + break; + case 2: + if (V.K1 < 16) + { + V.K1++; + } + + break; + case 3: + if (V.K2 >= -16) + { + V.K2--; + } + + break; + case 4: + if (V.K2 < 16) + { + V.K2++; + } + + break; + case 5: + if (V.K3 >= -16) + { + V.K3--; + } + + break; + case 6: + if (V.K3 < 16) + { + V.K3++; + } + + break; + case 7: + if (V.K4 >= -16) + { + V.K4--; + } + + break; + case 8: + if (V.K4 < 16) + { + V.K4++; + } + + break; + case 9: + if (V.K5 >= -16) + { + V.K5--; + } + + break; + case 10: + if (V.K5 < 16) + { + V.K5++; + } + + break; + } + } + return (byte)Ch; + } } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack50_cpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack50_cpp.cs index a7001205..c0a286df 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack50_cpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack50_cpp.cs @@ -19,838 +19,838 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 { internal partial class Unpack { - private void Unpack5(bool Solid) -{ - FileExtracted=true; - - if (!Suspended) - { - UnpInitData(Solid); - if (!UnpReadBuf()) - { - return; - } - - // Check TablesRead5 to be sure that we read tables at least once - // regardless of current block header TablePresent flag. - // So we can safefly use these tables below. - if (!ReadBlockHeader(Inp,ref BlockHeader) || - !ReadTables(Inp,ref BlockHeader, ref BlockTables) || !TablesRead5) - { - return; - } - } - - while (true) - { - UnpPtr&=MaxWinMask; - - if (Inp.InAddr>=ReadBorder) - { - bool FileDone=false; - - // We use 'while', because for empty block containing only Huffman table, - // we'll be on the block border once again just after reading the table. - while (Inp.InAddr>BlockHeader.BlockStart+BlockHeader.BlockSize-1 || - Inp.InAddr==BlockHeader.BlockStart+BlockHeader.BlockSize-1 && - Inp.InBit>=BlockHeader.BlockBitSize) - { - if (BlockHeader.LastBlockInFile) + private void Unpack5(bool Solid) { - FileDone=true; - break; + FileExtracted = true; + + if (!Suspended) + { + UnpInitData(Solid); + if (!UnpReadBuf()) + { + return; + } + + // Check TablesRead5 to be sure that we read tables at least once + // regardless of current block header TablePresent flag. + // So we can safefly use these tables below. + if (!ReadBlockHeader(Inp, ref BlockHeader) || + !ReadTables(Inp, ref BlockHeader, ref BlockTables) || !TablesRead5) + { + return; + } + } + + while (true) + { + UnpPtr &= MaxWinMask; + + if (Inp.InAddr >= ReadBorder) + { + bool FileDone = false; + + // We use 'while', because for empty block containing only Huffman table, + // we'll be on the block border once again just after reading the table. + while (Inp.InAddr > BlockHeader.BlockStart + BlockHeader.BlockSize - 1 || + Inp.InAddr == BlockHeader.BlockStart + BlockHeader.BlockSize - 1 && + Inp.InBit >= BlockHeader.BlockBitSize) + { + if (BlockHeader.LastBlockInFile) + { + FileDone = true; + break; + } + if (!ReadBlockHeader(Inp, ref BlockHeader) || !ReadTables(Inp, ref BlockHeader, ref BlockTables)) + { + return; + } + } + if (FileDone || !UnpReadBuf()) + { + break; + } + } + + if (((WriteBorder - UnpPtr) & MaxWinMask) < MAX_LZ_MATCH + 3 && WriteBorder != UnpPtr) + { + UnpWriteBuf(); + if (WrittenFileSize > DestUnpSize) + { + return; + } + + if (Suspended) + { + FileExtracted = false; + return; + } + } + + uint MainSlot = DecodeNumber(Inp, BlockTables.LD); + if (MainSlot < 256) + { + if (Fragmented) + { + FragWindow[UnpPtr++] = (byte)MainSlot; + } + else + { + Window[UnpPtr++] = (byte)MainSlot; + } + + continue; + } + if (MainSlot >= 262) + { + uint Length = SlotToLength(Inp, MainSlot - 262); + + uint DBits, Distance = 1, DistSlot = DecodeNumber(Inp, BlockTables.DD); + if (DistSlot < 4) + { + DBits = 0; + Distance += DistSlot; + } + else + { + DBits = DistSlot / 2 - 1; + Distance += (2 | (DistSlot & 1)) << (int)DBits; + } + + if (DBits > 0) + { + if (DBits >= 4) + { + if (DBits > 4) + { + Distance += ((Inp.getbits32() >> (int)(36 - DBits)) << 4); + Inp.addbits(DBits - 4); + } + uint LowDist = DecodeNumber(Inp, BlockTables.LDD); + Distance += LowDist; + } + else + { + Distance += Inp.getbits32() >> (int)(32 - DBits); + Inp.addbits(DBits); + } + } + + if (Distance > 0x100) + { + Length++; + if (Distance > 0x2000) + { + Length++; + if (Distance > 0x40000) + { + Length++; + } + } + } + + InsertOldDist(Distance); + LastLength = Length; + if (Fragmented) + { + FragWindow.CopyString(Length, Distance, ref UnpPtr, MaxWinMask); + } + else + { + CopyString(Length, Distance); + } + + continue; + } + if (MainSlot == 256) + { + UnpackFilter Filter = new UnpackFilter(); + if (!ReadFilter(Inp, Filter) || !AddFilter(Filter)) + { + break; + } + + continue; + } + if (MainSlot == 257) + { + if (LastLength != 0) + { + if (Fragmented) + { + FragWindow.CopyString(LastLength, OldDist[0], ref UnpPtr, MaxWinMask); + } + else + { + CopyString(LastLength, OldDist[0]); + } + } + + continue; + } + if (MainSlot < 262) + { + uint DistNum = MainSlot - 258; + uint Distance = OldDist[DistNum]; + for (uint I = DistNum; I > 0; I--) + { + OldDist[I] = OldDist[I - 1]; + } + + OldDist[0] = Distance; + + uint LengthSlot = DecodeNumber(Inp, BlockTables.RD); + uint Length = SlotToLength(Inp, LengthSlot); + LastLength = Length; + if (Fragmented) + { + FragWindow.CopyString(Length, Distance, ref UnpPtr, MaxWinMask); + } + else + { + CopyString(Length, Distance); + } + + continue; + } + } + UnpWriteBuf(); } - if (!ReadBlockHeader(Inp,ref BlockHeader) || !ReadTables(Inp, ref BlockHeader, ref BlockTables)) + + private uint ReadFilterData(BitInput Inp) { - return; + uint ByteCount = (Inp.fgetbits() >> 14) + 1; + Inp.addbits(2); + + uint Data = 0; + for (uint I = 0; I < ByteCount; I++) + { + Data += (Inp.fgetbits() >> 8) << (int)(I * 8); + Inp.addbits(8); + } + return Data; } - } - if (FileDone || !UnpReadBuf()) - { - break; - } - } - if (((WriteBorder-UnpPtr) & MaxWinMask)DestUnpSize) - { - return; - } - - if (Suspended) - { - FileExtracted=false; - return; - } - } - - uint MainSlot=DecodeNumber(Inp,BlockTables.LD); - if (MainSlot<256) - { - if (Fragmented) - { - FragWindow[UnpPtr++]=(byte)MainSlot; - } - else - { - Window[UnpPtr++]=(byte)MainSlot; - } - - continue; - } - if (MainSlot>=262) - { - uint Length=SlotToLength(Inp,MainSlot-262); - - uint DBits,Distance=1,DistSlot=DecodeNumber(Inp,BlockTables.DD); - if (DistSlot<4) - { - DBits=0; - Distance+=DistSlot; - } - else - { - DBits=DistSlot/2 - 1; - Distance+=(2 | (DistSlot & 1)) << (int)DBits; - } - - if (DBits>0) - { - if (DBits>=4) + private bool ReadFilter(BitInput Inp, UnpackFilter Filter) { - if (DBits>4) - { - Distance+=((Inp.getbits32()>>(int)(36-DBits))<<4); - Inp.addbits(DBits-4); - } - uint LowDist=DecodeNumber(Inp,BlockTables.LDD); - Distance+=LowDist; + if (!Inp.ExternalBuffer && Inp.InAddr > ReadTop - 16) + { + if (!UnpReadBuf()) + { + return false; + } + } + + Filter.BlockStart = ReadFilterData(Inp); + Filter.BlockLength = ReadFilterData(Inp); + if (Filter.BlockLength > MAX_FILTER_BLOCK_SIZE) + { + Filter.BlockLength = 0; + } + + Filter.Type = (byte)(Inp.fgetbits() >> 13); + Inp.faddbits(3); + + if (Filter.Type == FILTER_DELTA) + { + Filter.Channels = (byte)((Inp.fgetbits() >> 11) + 1); + Inp.faddbits(5); + } + + return true; } - else + + private bool AddFilter(UnpackFilter Filter) { - Distance+=Inp.getbits32()>>(int)(32-DBits); - Inp.addbits(DBits); + if (Filters.Count >= MAX_UNPACK_FILTERS) + { + UnpWriteBuf(); // Write data, apply and flush filters. + if (Filters.Count >= MAX_UNPACK_FILTERS) + { + InitFilters(); // Still too many filters, prevent excessive memory use. + } + } + + // If distance to filter start is that large that due to circular dictionary + // mode now it points to old not written yet data, then we set 'NextWindow' + // flag and process this filter only after processing that older data. + Filter.NextWindow = WrPtr != UnpPtr && ((WrPtr - UnpPtr) & MaxWinMask) <= Filter.BlockStart; + + Filter.BlockStart = (uint)((Filter.BlockStart + UnpPtr) & MaxWinMask); + Filters.Add(Filter); + return true; } - } - if (Distance>0x100) - { - Length++; - if (Distance>0x2000) + private bool UnpReadBuf() { - Length++; - if (Distance>0x40000) - { - Length++; - } + int DataSize = ReadTop - Inp.InAddr; // Data left to process. + if (DataSize < 0) + { + return false; + } + + BlockHeader.BlockSize -= Inp.InAddr - BlockHeader.BlockStart; + if (Inp.InAddr > MAX_SIZE / 2) + { + // If we already processed more than half of buffer, let's move + // remaining data into beginning to free more space for new data + // and ensure that calling function does not cross the buffer border + // even if we did not read anything here. Also it ensures that read size + // is not less than CRYPT_BLOCK_SIZE, so we can align it without risk + // to make it zero. + if (DataSize > 0) + //x memmove(Inp.InBuf,Inp.InBuf+Inp.InAddr,DataSize); + { + Buffer.BlockCopy(Inp.InBuf, Inp.InAddr, Inp.InBuf, 0, DataSize); + } + + Inp.InAddr = 0; + ReadTop = DataSize; + } + else + { + DataSize = ReadTop; + } + + int ReadCode = 0; + if (MAX_SIZE != DataSize) + { + ReadCode = UnpIO_UnpRead(Inp.InBuf, DataSize, MAX_SIZE - DataSize); + } + + if (ReadCode > 0) // Can be also -1. + { + ReadTop += ReadCode; + } + + ReadBorder = ReadTop - 30; + BlockHeader.BlockStart = Inp.InAddr; + if (BlockHeader.BlockSize != -1) // '-1' means not defined yet. + { + // We may need to quit from main extraction loop and read new block header + // and trees earlier than data in input buffer ends. + ReadBorder = Math.Min(ReadBorder, BlockHeader.BlockStart + BlockHeader.BlockSize - 1); + } + return ReadCode != -1; } - } - InsertOldDist(Distance); - LastLength=Length; - if (Fragmented) - { - FragWindow.CopyString(Length,Distance,ref UnpPtr,MaxWinMask); - } - else - { - CopyString(Length,Distance); - } - - continue; - } - if (MainSlot==256) - { - UnpackFilter Filter = new UnpackFilter(); - if (!ReadFilter(Inp,Filter) || !AddFilter(Filter)) - { - break; - } - - continue; - } - if (MainSlot==257) - { - if (LastLength!=0) - { - if (Fragmented) + private void UnpWriteBuf() { - FragWindow.CopyString(LastLength,OldDist[0],ref UnpPtr,MaxWinMask); + size_t WrittenBorder = WrPtr; + size_t FullWriteSize = (UnpPtr - WrittenBorder) & MaxWinMask; + size_t WriteSizeLeft = FullWriteSize; + bool NotAllFiltersProcessed = false; + //for (size_t I=0;I int + for (int I = 0; I < Filters.Count; I++) + { + // Here we apply filters to data which we need to write. + // We always copy data to another memory block before processing. + // We cannot process them just in place in Window buffer, because + // these data can be used for future string matches, so we must + // preserve them in original form. + + UnpackFilter flt = Filters[I]; + if (flt.Type == FILTER_NONE) + { + continue; + } + + if (flt.NextWindow) + { + // Here we skip filters which have block start in current data range + // due to address wrap around in circular dictionary, but actually + // belong to next dictionary block. If such filter start position + // is included to current write range, then we reset 'NextWindow' flag. + // In fact we can reset it even without such check, because current + // implementation seems to guarantee 'NextWindow' flag reset after + // buffer writing for all existing filters. But let's keep this check + // just in case. Compressor guarantees that distance between + // filter block start and filter storing position cannot exceed + // the dictionary size. So if we covered the filter block start with + // our write here, we can safely assume that filter is applicable + // to next block on no further wrap arounds is possible. + if (((flt.BlockStart - WrPtr) & MaxWinMask) <= FullWriteSize) + { + flt.NextWindow = false; + } + + continue; + } + uint BlockStart = flt.BlockStart; + uint BlockLength = flt.BlockLength; + if (((BlockStart - WrittenBorder) & MaxWinMask) < WriteSizeLeft) + { + if (WrittenBorder != BlockStart) + { + UnpWriteArea(WrittenBorder, BlockStart); + WrittenBorder = BlockStart; + WriteSizeLeft = (UnpPtr - WrittenBorder) & MaxWinMask; + } + if (BlockLength <= WriteSizeLeft) + { + if (BlockLength > 0) // We set it to 0 also for invalid filters. + { + uint BlockEnd = (BlockStart + BlockLength) & MaxWinMask; + + //x FilterSrcMemory.Alloc(BlockLength); + FilterSrcMemory = EnsureCapacity(FilterSrcMemory, checked((int)BlockLength)); + byte[] Mem = FilterSrcMemory; + if (BlockStart < BlockEnd || BlockEnd == 0) + { + if (Fragmented) + { + FragWindow.CopyData(Mem, 0, BlockStart, BlockLength); + } + else + //x memcpy(Mem,Window+BlockStart,BlockLength); + { + Utility.Copy(Window, BlockStart, Mem, 0, BlockLength); + } + } + else + { + size_t FirstPartLength = (size_t)(MaxWinSize - BlockStart); + if (Fragmented) + { + FragWindow.CopyData(Mem, 0, BlockStart, FirstPartLength); + FragWindow.CopyData(Mem, FirstPartLength, 0, BlockEnd); + } + else + { + //x memcpy(Mem,Window+BlockStart,FirstPartLength); + Utility.Copy(Window, BlockStart, Mem, 0, FirstPartLength); + //x memcpy(Mem+FirstPartLength,Window,BlockEnd); + Utility.Copy(Window, 0, Mem, FirstPartLength, BlockEnd); + } + } + + byte[] OutMem = ApplyFilter(Mem, BlockLength, flt); + + Filters[I].Type = FILTER_NONE; + + if (OutMem != null) + { + UnpIO_UnpWrite(OutMem, 0, BlockLength); + } + + UnpSomeRead = true; + WrittenFileSize += BlockLength; + WrittenBorder = BlockEnd; + WriteSizeLeft = (UnpPtr - WrittenBorder) & MaxWinMask; + } + } + else + { + // Current filter intersects the window write border, so we adjust + // the window border to process this filter next time, not now. + WrPtr = WrittenBorder; + + // Since Filter start position can only increase, we quit processing + // all following filters for this data block and reset 'NextWindow' + // flag for them. + //for (size_t J=I;J int + for (int J = I; J < Filters.Count; J++) + { + UnpackFilter _flt = Filters[J]; + if (_flt.Type != FILTER_NONE) + { + _flt.NextWindow = false; + } + } + + // Do not write data left after current filter now. + NotAllFiltersProcessed = true; + break; + } + } + } + + // Remove processed filters from queue. + // sharpcompress: size_t -> int + int EmptyCount = 0; + // sharpcompress: size_t -> int + for (int I = 0; I < Filters.Count; I++) + { + if (EmptyCount > 0) + { + Filters[I - EmptyCount] = Filters[I]; + } + + if (Filters[I].Type == FILTER_NONE) + { + EmptyCount++; + } + } + if (EmptyCount > 0) + //Filters.Alloc(Filters.Count-EmptyCount); + { + Filters.RemoveRange(Filters.Count - EmptyCount, EmptyCount); + } + + if (!NotAllFiltersProcessed) // Only if all filters are processed. + { + // Write data left after last filter. + UnpWriteArea(WrittenBorder, UnpPtr); + WrPtr = UnpPtr; + } + + // We prefer to write data in blocks not exceeding UNPACK_MAX_WRITE + // instead of potentially huge MaxWinSize blocks. It also allows us + // to keep the size of Filters array reasonable. + WriteBorder = (UnpPtr + Math.Min(MaxWinSize, UNPACK_MAX_WRITE)) & MaxWinMask; + + // Choose the nearest among WriteBorder and WrPtr actual written border. + // If border is equal to UnpPtr, it means that we have MaxWinSize data ahead. + if (WriteBorder == UnpPtr || + WrPtr != UnpPtr && ((WrPtr - UnpPtr) & MaxWinMask) < ((WriteBorder - UnpPtr) & MaxWinMask)) + { + WriteBorder = WrPtr; + } } - else + + private byte[] ApplyFilter(byte[] __d, uint DataSize, UnpackFilter Flt) { - CopyString(LastLength,OldDist[0]); + int Data = 0; + byte[] SrcData = __d; + switch (Flt.Type) + { + case FILTER_E8: + case FILTER_E8E9: + { + uint FileOffset = (uint)WrittenFileSize; + + const uint FileSize = 0x1000000; + byte CmpByte2 = Flt.Type == FILTER_E8E9 ? (byte)0xe9 : (byte)0xe8; + // DataSize is unsigned, so we use "CurPos+4" and not "DataSize-4" + // to avoid overflow for DataSize<4. + for (uint CurPos = 0; CurPos + 4 < DataSize;) + { + //x byte CurByte=*(Data++); + byte CurByte = __d[Data++]; + CurPos++; + if (CurByte == 0xe8 || CurByte == CmpByte2) + { + uint Offset = (CurPos + FileOffset) % FileSize; + uint Addr = RawGet4(__d, Data); + + // We check 0x80000000 bit instead of '< 0' comparison + // not assuming int32 presence or uint size and endianness. + if ((Addr & 0x80000000) != 0) // Addr<0 + { + if (((Addr + Offset) & 0x80000000) == 0) // Addr+Offset>=0 + { + RawPut4(Addr + FileSize, __d, Data); + } + } + else + if (((Addr - FileSize) & 0x80000000) != 0) // Addr> 8); + __d[D + 2] = (byte)(Offset >> 16); + } + } + } + return SrcData; + case FILTER_DELTA: + { + // Unlike RAR3, we do not need to reject excessive channel + // values here, since RAR5 uses only 5 bits to store channel. + uint Channels = Flt.Channels, SrcPos = 0; + + //x FilterDstMemory.Alloc(DataSize); + FilterDstMemory = EnsureCapacity(FilterDstMemory, checked((int)DataSize)); + + byte[] DstData = FilterDstMemory; + + // Bytes from same channels are grouped to continual data blocks, + // so we need to place them back to their interleaving positions. + for (uint CurChannel = 0; CurChannel < Channels; CurChannel++) + { + byte PrevByte = 0; + for (uint DestPos = CurChannel; DestPos < DataSize; DestPos += Channels) + { + DstData[DestPos] = (PrevByte -= __d[Data + SrcPos++]); + } + } + return DstData; + } + + } + return null; } - } - continue; - } - if (MainSlot<262) - { - uint DistNum=MainSlot-258; - uint Distance=OldDist[DistNum]; - for (uint I=DistNum;I>0;I--) - { - OldDist[I]=OldDist[I-1]; - } - - OldDist[0]=Distance; - - uint LengthSlot=DecodeNumber(Inp,BlockTables.RD); - uint Length=SlotToLength(Inp,LengthSlot); - LastLength=Length; - if (Fragmented) - { - FragWindow.CopyString(Length,Distance,ref UnpPtr,MaxWinMask); - } - else - { - CopyString(Length,Distance); - } - - continue; - } - } - UnpWriteBuf(); -} - - private uint ReadFilterData(BitInput Inp) -{ - uint ByteCount=(Inp.fgetbits()>>14)+1; - Inp.addbits(2); - - uint Data=0; - for (uint I=0;I>8)<<(int)(I*8); - Inp.addbits(8); - } - return Data; -} - - private bool ReadFilter(BitInput Inp,UnpackFilter Filter) -{ - if (!Inp.ExternalBuffer && Inp.InAddr>ReadTop-16) - { - if (!UnpReadBuf()) - { - return false; - } - } - - Filter.BlockStart=ReadFilterData(Inp); - Filter.BlockLength=ReadFilterData(Inp); - if (Filter.BlockLength>MAX_FILTER_BLOCK_SIZE) - { - Filter.BlockLength=0; - } - - Filter.Type=(byte)(Inp.fgetbits()>>13); - Inp.faddbits(3); - - if (Filter.Type==FILTER_DELTA) - { - Filter.Channels=(byte)((Inp.fgetbits()>>11)+1); - Inp.faddbits(5); - } - - return true; -} - - private bool AddFilter(UnpackFilter Filter) -{ - if (Filters.Count>=MAX_UNPACK_FILTERS) - { - UnpWriteBuf(); // Write data, apply and flush filters. - if (Filters.Count>=MAX_UNPACK_FILTERS) - { - InitFilters(); // Still too many filters, prevent excessive memory use. - } - } - - // If distance to filter start is that large that due to circular dictionary - // mode now it points to old not written yet data, then we set 'NextWindow' - // flag and process this filter only after processing that older data. - Filter.NextWindow=WrPtr!=UnpPtr && ((WrPtr-UnpPtr)&MaxWinMask)<=Filter.BlockStart; - - Filter.BlockStart=(uint)((Filter.BlockStart+UnpPtr)&MaxWinMask); - Filters.Add(Filter); - return true; -} - - private bool UnpReadBuf() -{ - int DataSize=ReadTop-Inp.InAddr; // Data left to process. - if (DataSize<0) - { - return false; - } - - BlockHeader.BlockSize-=Inp.InAddr-BlockHeader.BlockStart; - if (Inp.InAddr>MAX_SIZE/2) - { - // If we already processed more than half of buffer, let's move - // remaining data into beginning to free more space for new data - // and ensure that calling function does not cross the buffer border - // even if we did not read anything here. Also it ensures that read size - // is not less than CRYPT_BLOCK_SIZE, so we can align it without risk - // to make it zero. - if (DataSize>0) - //x memmove(Inp.InBuf,Inp.InBuf+Inp.InAddr,DataSize); - { - Buffer.BlockCopy(Inp.InBuf, Inp.InAddr, Inp.InBuf, 0, DataSize); - } - - Inp.InAddr=0; - ReadTop=DataSize; - } - else - { - DataSize=ReadTop; - } - - int ReadCode=0; - if (MAX_SIZE!=DataSize) - { - ReadCode=UnpIO_UnpRead(Inp.InBuf,DataSize,MAX_SIZE-DataSize); - } - - if (ReadCode>0) // Can be also -1. - { - ReadTop+=ReadCode; - } - - ReadBorder=ReadTop-30; - BlockHeader.BlockStart=Inp.InAddr; - if (BlockHeader.BlockSize!=-1) // '-1' means not defined yet. - { - // We may need to quit from main extraction loop and read new block header - // and trees earlier than data in input buffer ends. - ReadBorder=Math.Min(ReadBorder,BlockHeader.BlockStart+BlockHeader.BlockSize-1); - } - return ReadCode!=-1; -} - - private void UnpWriteBuf() -{ - size_t WrittenBorder=WrPtr; - size_t FullWriteSize=(UnpPtr-WrittenBorder)&MaxWinMask; - size_t WriteSizeLeft=FullWriteSize; - bool NotAllFiltersProcessed=false; - //for (size_t I=0;I int - for (int I=0;I0) // We set it to 0 also for invalid filters. + private void UnpWriteArea(size_t StartPtr, size_t EndPtr) { - uint BlockEnd=(BlockStart+BlockLength)&MaxWinMask; + if (EndPtr != StartPtr) + { + UnpSomeRead = true; + } + + if (EndPtr < StartPtr) + { + UnpAllBuf = true; + } - //x FilterSrcMemory.Alloc(BlockLength); - FilterSrcMemory = EnsureCapacity(FilterSrcMemory, checked((int)BlockLength)); - byte[] Mem= FilterSrcMemory; - if (BlockStart 0) + { + size_t BlockSize = FragWindow.GetBlockSize(StartPtr, SizeToWrite); + //UnpWriteData(&FragWindow[StartPtr],BlockSize); + FragWindow.GetBuffer(StartPtr, out var __buffer, out var __offset); + UnpWriteData(__buffer, __offset, BlockSize); + SizeToWrite -= BlockSize; + StartPtr = (StartPtr + BlockSize) & MaxWinMask; + } } else - //x memcpy(Mem,Window+BlockStart,BlockLength); + if (EndPtr < StartPtr) { - Utility.Copy(Window, BlockStart, Mem, 0, BlockLength); - } - } - else - { - size_t FirstPartLength=(size_t)(MaxWinSize-BlockStart); - if (Fragmented) - { - FragWindow.CopyData(Mem,0,BlockStart,FirstPartLength); - FragWindow.CopyData(Mem,FirstPartLength,0,BlockEnd); + UnpWriteData(Window, StartPtr, MaxWinSize - StartPtr); + UnpWriteData(Window, 0, EndPtr); } else { - //x memcpy(Mem,Window+BlockStart,FirstPartLength); - Utility.Copy(Window, BlockStart, Mem, 0, FirstPartLength); - //x memcpy(Mem+FirstPartLength,Window,BlockEnd); - Utility.Copy(Window, 0, Mem, FirstPartLength,BlockEnd); + UnpWriteData(Window, StartPtr, EndPtr - StartPtr); } - } - - byte[] OutMem=ApplyFilter(Mem,BlockLength,flt); - - Filters[I].Type=FILTER_NONE; - - if (OutMem!=null) - { - UnpIO_UnpWrite(OutMem,0,BlockLength); - } - - UnpSomeRead=true; - WrittenFileSize+=BlockLength; - WrittenBorder=BlockEnd; - WriteSizeLeft=(UnpPtr-WrittenBorder)&MaxWinMask; - } - } - else - { - // Current filter intersects the window write border, so we adjust - // the window border to process this filter next time, not now. - WrPtr=WrittenBorder; - - // Since Filter start position can only increase, we quit processing - // all following filters for this data block and reset 'NextWindow' - // flag for them. - //for (size_t J=I;J int - for (int J=I;J int - int EmptyCount=0; - // sharpcompress: size_t -> int - for (int I=0;I0) - { - Filters[I-EmptyCount]=Filters[I]; - } - - if (Filters[I].Type==FILTER_NONE) - { - EmptyCount++; - } - } - if (EmptyCount>0) - //Filters.Alloc(Filters.Count-EmptyCount); - { - Filters.RemoveRange(Filters.Count-EmptyCount, EmptyCount); - } - - if (!NotAllFiltersProcessed) // Only if all filters are processed. - { - // Write data left after last filter. - UnpWriteArea(WrittenBorder,UnpPtr); - WrPtr=UnpPtr; - } - - // We prefer to write data in blocks not exceeding UNPACK_MAX_WRITE - // instead of potentially huge MaxWinSize blocks. It also allows us - // to keep the size of Filters array reasonable. - WriteBorder=(UnpPtr+Math.Min(MaxWinSize,UNPACK_MAX_WRITE))&MaxWinMask; - - // Choose the nearest among WriteBorder and WrPtr actual written border. - // If border is equal to UnpPtr, it means that we have MaxWinSize data ahead. - if (WriteBorder==UnpPtr || - WrPtr!=UnpPtr && ((WrPtr-UnpPtr)&MaxWinMask)<((WriteBorder-UnpPtr)&MaxWinMask)) - { - WriteBorder=WrPtr; - } -} - - private byte[] ApplyFilter(byte[] __d,uint DataSize,UnpackFilter Flt) -{ - int Data = 0; - byte[] SrcData=__d; - switch(Flt.Type) - { - case FILTER_E8: - case FILTER_E8E9: - { - uint FileOffset=(uint)WrittenFileSize; - - const uint FileSize=0x1000000; - byte CmpByte2=Flt.Type==FILTER_E8E9 ? (byte)0xe9 : (byte)0xe8; - // DataSize is unsigned, so we use "CurPos+4" and not "DataSize-4" - // to avoid overflow for DataSize<4. - for (uint CurPos=0;CurPos+4= DestUnpSize) { - if (((Addr+Offset) & 0x80000000)==0) // Addr+Offset>=0 - { - RawPut4(Addr+FileSize,__d,Data); - } + return; } - else - if (((Addr-FileSize) & 0x80000000)!=0) // Addr LeftToWrite) + { + WriteSize = (size_t)LeftToWrite; + } + + UnpIO_UnpWrite(Data, offset, WriteSize); + WrittenFileSize += Size; } - } - return SrcData; - case FILTER_ARM: - { - uint FileOffset=(uint)WrittenFileSize; - // DataSize is unsigned, so we use "CurPos+3" and not "DataSize-3" - // to avoid overflow for DataSize<3. - for (uint CurPos=0;CurPos+3>8); - __d[D+2]=(byte)(Offset>>16); - } + if (!Solid) + { + TablesRead5 = false; + } } - } - return SrcData; - case FILTER_DELTA: - { - // Unlike RAR3, we do not need to reject excessive channel - // values here, since RAR5 uses only 5 bits to store channel. - uint Channels=Flt.Channels,SrcPos=0; - //x FilterDstMemory.Alloc(DataSize); - FilterDstMemory = EnsureCapacity(FilterDstMemory, checked((int)DataSize)); - - byte[] DstData=FilterDstMemory; - - // Bytes from same channels are grouped to continual data blocks, - // so we need to place them back to their interleaving positions. - for (uint CurChannel=0;CurChannel ReadTop - 7) + { + if (!UnpReadBuf()) + { + return false; + } + } + + Inp.faddbits((uint)((8 - Inp.InBit) & 7)); + + byte BlockFlags = (byte)(Inp.fgetbits() >> 8); + Inp.faddbits(8); + uint ByteCount = (uint)(((BlockFlags >> 3) & 3) + 1); // Block size byte count. + + if (ByteCount == 4) + { + return false; + } + + Header.HeaderSize = (int)(2 + ByteCount); + + Header.BlockBitSize = (BlockFlags & 7) + 1; + + byte SavedCheckSum = (byte)(Inp.fgetbits() >> 8); + Inp.faddbits(8); + + int BlockSize = 0; + for (uint I = 0; I < ByteCount; I++) + { + BlockSize += (int)((Inp.fgetbits() >> 8) << (int)(I * 8)); + Inp.addbits(8); + } + + Header.BlockSize = BlockSize; + byte CheckSum = (byte)(0x5a ^ BlockFlags ^ BlockSize ^ (BlockSize >> 8) ^ (BlockSize >> 16)); + if (CheckSum != SavedCheckSum) + { + return false; + } + + Header.BlockStart = Inp.InAddr; + ReadBorder = Math.Min(ReadBorder, Header.BlockStart + Header.BlockSize - 1); + + Header.LastBlockInFile = (BlockFlags & 0x40) != 0; + Header.TablePresent = (BlockFlags & 0x80) != 0; + return true; } - return DstData; - } - } - return null; -} - - private void UnpWriteArea(size_t StartPtr,size_t EndPtr) -{ - if (EndPtr!=StartPtr) - { - UnpSomeRead=true; - } - - if (EndPtr0) - { - size_t BlockSize=FragWindow.GetBlockSize(StartPtr,SizeToWrite); - //UnpWriteData(&FragWindow[StartPtr],BlockSize); - FragWindow.GetBuffer(StartPtr, out var __buffer, out var __offset); - UnpWriteData(__buffer, __offset, BlockSize); - SizeToWrite-=BlockSize; - StartPtr=(StartPtr+BlockSize) & MaxWinMask; - } - } - else - if (EndPtr=DestUnpSize) - { - return; - } - - size_t WriteSize=Size; - int64 LeftToWrite=DestUnpSize-WrittenFileSize; - if ((int64)WriteSize>LeftToWrite) - { - WriteSize=(size_t)LeftToWrite; - } - - UnpIO_UnpWrite(Data, offset, WriteSize); - WrittenFileSize+=Size; -} - - private void UnpInitData50(bool Solid) -{ - if (!Solid) - { - TablesRead5=false; - } -} - - private bool ReadBlockHeader(BitInput Inp,ref UnpackBlockHeader Header) -{ - Header.HeaderSize=0; - - if (!Inp.ExternalBuffer && Inp.InAddr>ReadTop-7) - { - if (!UnpReadBuf()) - { - return false; - } - } - - Inp.faddbits((uint)((8-Inp.InBit)&7)); - - byte BlockFlags=(byte)(Inp.fgetbits()>>8); - Inp.faddbits(8); - uint ByteCount=(uint)(((BlockFlags>>3)&3)+1); // Block size byte count. - - if (ByteCount==4) - { - return false; - } - - Header.HeaderSize=(int)(2+ByteCount); - - Header.BlockBitSize=(BlockFlags&7)+1; - - byte SavedCheckSum=(byte)(Inp.fgetbits()>>8); - Inp.faddbits(8); - - int BlockSize=0; - for (uint I=0;I>8)<<(int)(I*8)); - Inp.addbits(8); - } - - Header.BlockSize=BlockSize; - byte CheckSum=(byte)(0x5a^BlockFlags^BlockSize^(BlockSize>>8)^(BlockSize>>16)); - if (CheckSum!=SavedCheckSum) - { - return false; - } - - Header.BlockStart=Inp.InAddr; - ReadBorder=Math.Min(ReadBorder,Header.BlockStart+Header.BlockSize-1); - - Header.LastBlockInFile=(BlockFlags & 0x40)!=0; - Header.TablePresent=(BlockFlags & 0x80)!=0; - return true; -} - - private bool ReadTables(BitInput Inp,ref UnpackBlockHeader Header, ref UnpackBlockTables Tables) -{ - if (!Header.TablePresent) - { - return true; - } - - if (!Inp.ExternalBuffer && Inp.InAddr>ReadTop-25) - { - if (!UnpReadBuf()) - { - return false; - } - } - - byte[] BitLength = new byte[BC]; - for (uint I=0;I> 12); - Inp.faddbits(4); - if (Length==15) - { - uint ZeroCount=(byte)(Inp.fgetbits() >> 12); - Inp.faddbits(4); - if (ZeroCount==0) - { - BitLength[I]=15; - } - else - { - ZeroCount+=2; - while (ZeroCount-- > 0 && I ReadTop - 25) + { + if (!UnpReadBuf()) + { + return false; + } + } + + byte[] BitLength = new byte[BC]; + for (uint I = 0; I < BC; I++) + { + uint Length = (byte)(Inp.fgetbits() >> 12); + Inp.faddbits(4); + if (Length == 15) + { + uint ZeroCount = (byte)(Inp.fgetbits() >> 12); + Inp.faddbits(4); + if (ZeroCount == 0) + { + BitLength[I] = 15; + } + else + { + ZeroCount += 2; + while (ZeroCount-- > 0 && I < BitLength.Length) + { + BitLength[I++] = 0; + } + + I--; + } + } + else + { + BitLength[I] = (byte)Length; + } + } + + MakeDecodeTables(BitLength, 0, Tables.BD, BC); + + byte[] Table = new byte[HUFF_TABLE_SIZE]; + const uint TableSize = HUFF_TABLE_SIZE; + for (uint I = 0; I < TableSize;) + { + if (!Inp.ExternalBuffer && Inp.InAddr > ReadTop - 5) + { + if (!UnpReadBuf()) + { + return false; + } + } + + uint Number = DecodeNumber(Inp, Tables.BD); + if (Number < 16) + { + Table[I] = (byte)Number; + I++; + } + else + if (Number < 18) + { + uint N; + if (Number == 16) + { + N = (Inp.fgetbits() >> 13) + 3; + Inp.faddbits(3); + } + else + { + N = (Inp.fgetbits() >> 9) + 11; + Inp.faddbits(7); + } + if (I == 0) + { + // We cannot have "repeat previous" code at the first position. + // Multiple such codes would shift Inp position without changing I, + // which can lead to reading beyond of Inp boundary in mutithreading + // mode, where Inp.ExternalBuffer disables bounds check and we just + // reserve a lot of buffer space to not need such check normally. + return false; + } + else + { + while (N-- > 0 && I < TableSize) + { + Table[I] = Table[I - 1]; + I++; + } + } + } + else + { + uint N; + if (Number == 18) + { + N = (Inp.fgetbits() >> 13) + 3; + Inp.faddbits(3); + } + else + { + N = (Inp.fgetbits() >> 9) + 11; + Inp.faddbits(7); + } + while (N-- > 0 && I < TableSize) + { + Table[I++] = 0; + } + } + } + TablesRead5 = true; + if (!Inp.ExternalBuffer && Inp.InAddr > ReadTop) + { + return false; + } + + MakeDecodeTables(Table, 0, Tables.LD, NC); + MakeDecodeTables(Table, (int)NC, Tables.DD, DC); + MakeDecodeTables(Table, (int)(NC + DC), Tables.LDD, LDC); + MakeDecodeTables(Table, (int)(NC + DC + LDC), Tables.RD, RC); + return true; } - I--; - } - } - else - { - BitLength[I]=(byte)Length; - } - } - - MakeDecodeTables(BitLength,0,Tables.BD,BC); - - byte[] Table = new byte[HUFF_TABLE_SIZE]; - const uint TableSize=HUFF_TABLE_SIZE; - for (uint I=0;IReadTop-5) - { - if (!UnpReadBuf()) - { - return false; - } - } - - uint Number=DecodeNumber(Inp,Tables.BD); - if (Number<16) - { - Table[I]=(byte)Number; - I++; - } - else - if (Number<18) - { - uint N; - if (Number==16) + private void InitFilters() { - N=(Inp.fgetbits() >> 13)+3; - Inp.faddbits(3); + //Filters.SoftReset(); + Filters.Clear(); } - else - { - N=(Inp.fgetbits() >> 9)+11; - Inp.faddbits(7); - } - if (I==0) - { - // We cannot have "repeat previous" code at the first position. - // Multiple such codes would shift Inp position without changing I, - // which can lead to reading beyond of Inp boundary in mutithreading - // mode, where Inp.ExternalBuffer disables bounds check and we just - // reserve a lot of buffer space to not need such check normally. - return false; - } - else - { - while (N-- > 0 && I> 13)+3; - Inp.faddbits(3); - } - else - { - N=(Inp.fgetbits() >> 9)+11; - Inp.faddbits(7); - } - while (N-- > 0 && IReadTop) - { - return false; - } - - MakeDecodeTables(Table, 0, Tables.LD,NC); - MakeDecodeTables(Table, (int)NC,Tables.DD,DC); - MakeDecodeTables(Table, (int)(NC+DC),Tables.LDD,LDC); - MakeDecodeTables(Table, (int)(NC+DC+LDC),Tables.RD,RC); - return true; -} - - private void InitFilters() -{ - //Filters.SoftReset(); - Filters.Clear(); -} } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack_cpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack_cpp.cs index e6f73a19..48df0608 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack_cpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack_cpp.cs @@ -20,183 +20,183 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 internal sealed partial class Unpack : BitInput { -public Unpack(/* ComprDataIO *DataIO */) -//:Inp(true),VMCodeInp(true) -: base(true) -{ - _UnpackCtor(); + public Unpack(/* ComprDataIO *DataIO */) + //:Inp(true),VMCodeInp(true) + : base(true) + { + _UnpackCtor(); - //UnpIO=DataIO; - Window=null; - Fragmented=false; - Suspended=false; - UnpAllBuf=false; - UnpSomeRead=false; + //UnpIO=DataIO; + Window = null; + Fragmented = false; + Suspended = false; + UnpAllBuf = false; + UnpSomeRead = false; #if RarV2017_RAR_SMP MaxUserThreads=1; UnpThreadPool=CreateThreadPool(); ReadBufMT=null; UnpThreadData=null; #endif - MaxWinSize=0; - MaxWinMask=0; + MaxWinSize = 0; + MaxWinMask = 0; - // Perform initialization, which should be done only once for all files. - // It prevents crash if first DoUnpack call is later made with wrong - // (true) 'Solid' value. - UnpInitData(false); + // Perform initialization, which should be done only once for all files. + // It prevents crash if first DoUnpack call is later made with wrong + // (true) 'Solid' value. + UnpInitData(false); #if !RarV2017_SFX_MODULE - // RAR 1.5 decompression initialization - UnpInitData15(false); - InitHuff(); + // RAR 1.5 decompression initialization + UnpInitData15(false); + InitHuff(); #endif -} + } -// later: may need Dispose() if we support thread pool -//Unpack::~Unpack() -//{ -// InitFilters30(false); -// -// if (Window!=null) -// free(Window); -//#if RarV2017_RAR_SMP -// DestroyThreadPool(UnpThreadPool); -// delete[] ReadBufMT; -// delete[] UnpThreadData; -//#endif -//} + // later: may need Dispose() if we support thread pool + //Unpack::~Unpack() + //{ + // InitFilters30(false); + // + // if (Window!=null) + // free(Window); + //#if RarV2017_RAR_SMP + // DestroyThreadPool(UnpThreadPool); + // delete[] ReadBufMT; + // delete[] UnpThreadData; + //#endif + //} - private void Init(size_t WinSize,bool Solid) -{ - // If 32-bit RAR unpacks an archive with 4 GB dictionary, the window size - // will be 0 because of size_t overflow. Let's issue the memory error. - if (WinSize==0) - //ErrHandler.MemoryError(); - { - throw new InvalidFormatException("invalid window size (possibly due to a rar file with a 4GB being unpacked on a 32-bit platform)"); - } + private void Init(size_t WinSize, bool Solid) + { + // If 32-bit RAR unpacks an archive with 4 GB dictionary, the window size + // will be 0 because of size_t overflow. Let's issue the memory error. + if (WinSize == 0) + //ErrHandler.MemoryError(); + { + throw new InvalidFormatException("invalid window size (possibly due to a rar file with a 4GB being unpacked on a 32-bit platform)"); + } - // Minimum window size must be at least twice more than maximum possible - // size of filter block, which is 0x10000 in RAR now. If window size is - // smaller, we can have a block with never cleared flt->NextWindow flag - // in UnpWriteBuf(). Minimum window size 0x20000 would be enough, but let's - // use 0x40000 for extra safety and possible filter area size expansion. - const size_t MinAllocSize=0x40000; - if (WinSizeNextWindow flag + // in UnpWriteBuf(). Minimum window size 0x20000 would be enough, but let's + // use 0x40000 for extra safety and possible filter area size expansion. + const size_t MinAllocSize = 0x40000; + if (WinSize < MinAllocSize) + { + WinSize = MinAllocSize; + } - if (WinSize<=MaxWinSize) // Use the already allocated window. - { - return; - } + if (WinSize <= MaxWinSize) // Use the already allocated window. + { + return; + } - if ((WinSize>>16)>0x10000) // Window size must not exceed 4 GB. - { - return; - } + if ((WinSize >> 16) > 0x10000) // Window size must not exceed 4 GB. + { + return; + } - // Archiving code guarantees that window size does not grow in the same - // solid stream. So if we are here, we are either creating a new window - // or increasing the size of non-solid window. So we could safely reject - // current window data without copying them to a new window, though being - // extra cautious, we still handle the solid window grow case below. - bool Grow=Solid && (Window!=null || Fragmented); + // Archiving code guarantees that window size does not grow in the same + // solid stream. So if we are here, we are either creating a new window + // or increasing the size of non-solid window. So we could safely reject + // current window data without copying them to a new window, though being + // extra cautious, we still handle the solid window grow case below. + bool Grow = Solid && (Window != null || Fragmented); - // We do not handle growth for existing fragmented window. - if (Grow && Fragmented) - //throw std::bad_alloc(); - { - throw new InvalidFormatException("Grow && Fragmented"); - } + // We do not handle growth for existing fragmented window. + if (Grow && Fragmented) + //throw std::bad_alloc(); + { + throw new InvalidFormatException("Grow && Fragmented"); + } - byte[] NewWindow=Fragmented ? null : new byte[WinSize]; + byte[] NewWindow = Fragmented ? null : new byte[WinSize]; - if (NewWindow==null) - { - if (Grow || WinSize<0x1000000) - { - // We do not support growth for new fragmented window. - // Also exclude RAR4 and small dictionaries. - //throw std::bad_alloc(); - throw new InvalidFormatException("Grow || WinSize<0x1000000"); - } - else - { - if (Window!=null) // If allocated by preceding files. - { - //free(Window); - Window=null; - } - FragWindow.Init(WinSize); - Fragmented=true; - } - } + if (NewWindow == null) + { + if (Grow || WinSize < 0x1000000) + { + // We do not support growth for new fragmented window. + // Also exclude RAR4 and small dictionaries. + //throw std::bad_alloc(); + throw new InvalidFormatException("Grow || WinSize<0x1000000"); + } + else + { + if (Window != null) // If allocated by preceding files. + { + //free(Window); + Window = null; + } + FragWindow.Init(WinSize); + Fragmented = true; + } + } - if (!Fragmented) - { - // Clean the window to generate the same output when unpacking corrupt - // RAR files, which may access unused areas of sliding dictionary. - // sharpcompress: don't need this, freshly allocated above - //memset(NewWindow,0,WinSize); + if (!Fragmented) + { + // Clean the window to generate the same output when unpacking corrupt + // RAR files, which may access unused areas of sliding dictionary. + // sharpcompress: don't need this, freshly allocated above + //memset(NewWindow,0,WinSize); - // If Window is not NULL, it means that window size has grown. - // In solid streams we need to copy data to a new window in such case. - // RAR archiving code does not allow it in solid streams now, - // but let's implement it anyway just in case we'll change it sometimes. - if (Grow) - { - for (size_t I=1;I<=MaxWinSize;I++) - { - NewWindow[(UnpPtr-I)&(WinSize-1)]=Window[(UnpPtr-I)&(MaxWinSize-1)]; - } - } + // If Window is not NULL, it means that window size has grown. + // In solid streams we need to copy data to a new window in such case. + // RAR archiving code does not allow it in solid streams now, + // but let's implement it anyway just in case we'll change it sometimes. + if (Grow) + { + for (size_t I = 1; I <= MaxWinSize; I++) + { + NewWindow[(UnpPtr - I) & (WinSize - 1)] = Window[(UnpPtr - I) & (MaxWinSize - 1)]; + } + } - //if (Window!=null) - // free(Window); - Window=NewWindow; - } + //if (Window!=null) + // free(Window); + Window = NewWindow; + } - MaxWinSize=WinSize; - MaxWinMask=MaxWinSize-1; -} + MaxWinSize = WinSize; + MaxWinMask = MaxWinSize - 1; + } - private void DoUnpack(uint Method,bool Solid) -{ - // Methods <50 will crash in Fragmented mode when accessing NULL Window. - // They cannot be called in such mode now, but we check it below anyway - // just for extra safety. - switch(Method) - { + private void DoUnpack(uint Method, bool Solid) + { + // Methods <50 will crash in Fragmented mode when accessing NULL Window. + // They cannot be called in such mode now, but we check it below anyway + // just for extra safety. + switch (Method) + { #if !RarV2017_SFX_MODULE - case 15: // rar 1.5 compression - if (!Fragmented) - { - Unpack15(Solid); - } + case 15: // rar 1.5 compression + if (!Fragmented) + { + Unpack15(Solid); + } - break; - case 20: // rar 2.x compression - case 26: // files larger than 2GB - if (!Fragmented) - { - Unpack20(Solid); - } + break; + case 20: // rar 2.x compression + case 26: // files larger than 2GB + if (!Fragmented) + { + Unpack20(Solid); + } - break; + break; #endif #if !RarV2017_RAR5ONLY - case 29: // rar 3.x compression - if (!Fragmented) - { - throw new NotImplementedException(); - } + case 29: // rar 3.x compression + if (!Fragmented) + { + throw new NotImplementedException(); + } - break; + break; #endif - case 50: // RAR 5.0 compression algorithm. + case 50: // RAR 5.0 compression algorithm. #if RarV2017_RAR_SMP if (MaxUserThreads>1) { @@ -212,198 +212,198 @@ public Unpack(/* ComprDataIO *DataIO */) } } #endif - Unpack5(Solid); - break; + Unpack5(Solid); + break; #if !Rar2017_NOSTRICT - default: throw new InvalidFormatException("unknown compression method " + Method); + default: throw new InvalidFormatException("unknown compression method " + Method); #endif - } -} + } + } - private void UnpInitData(bool Solid) -{ - if (!Solid) - { - new Span(OldDist).Clear(); - OldDistPtr=0; - LastDist=LastLength=0; -// memset(Window,0,MaxWinSize); - //memset(&BlockTables,0,sizeof(BlockTables)); - BlockTables = new UnpackBlockTables(); - // sharpcompress: no default ctor for struct - BlockTables.Init(); - UnpPtr=WrPtr=0; - WriteBorder=Math.Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; - } - // Filters never share several solid files, so we can safely reset them - // even in solid archive. - InitFilters(); + private void UnpInitData(bool Solid) + { + if (!Solid) + { + new Span(OldDist).Clear(); + OldDistPtr = 0; + LastDist = LastLength = 0; + // memset(Window,0,MaxWinSize); + //memset(&BlockTables,0,sizeof(BlockTables)); + BlockTables = new UnpackBlockTables(); + // sharpcompress: no default ctor for struct + BlockTables.Init(); + UnpPtr = WrPtr = 0; + WriteBorder = Math.Min(MaxWinSize, UNPACK_MAX_WRITE) & MaxWinMask; + } + // Filters never share several solid files, so we can safely reset them + // even in solid archive. + InitFilters(); - Inp.InitBitInput(); - WrittenFileSize=0; - ReadTop=0; - ReadBorder=0; + Inp.InitBitInput(); + WrittenFileSize = 0; + ReadTop = 0; + ReadBorder = 0; - //memset(&BlockHeader,0,sizeof(BlockHeader)); - BlockHeader = new UnpackBlockHeader(); - BlockHeader.BlockSize=-1; // '-1' means not defined yet. + //memset(&BlockHeader,0,sizeof(BlockHeader)); + BlockHeader = new UnpackBlockHeader(); + BlockHeader.BlockSize = -1; // '-1' means not defined yet. #if !RarV2017_SFX_MODULE - UnpInitData20(Solid); + UnpInitData20(Solid); #endif - //UnpInitData30(Solid); - UnpInitData50(Solid); -} + //UnpInitData30(Solid); + UnpInitData50(Solid); + } -// LengthTable contains the length in bits for every element of alphabet. -// Dec is the structure to decode Huffman code/ -// Size is size of length table and DecodeNum field in Dec structure, - private void MakeDecodeTables(byte[] LengthTable, int offset, DecodeTable Dec,uint Size) -{ - // Size of alphabet and DecodePos array. - Dec.MaxNum=Size; + // LengthTable contains the length in bits for every element of alphabet. + // Dec is the structure to decode Huffman code/ + // Size is size of length table and DecodeNum field in Dec structure, + private void MakeDecodeTables(byte[] LengthTable, int offset, DecodeTable Dec, uint Size) + { + // Size of alphabet and DecodePos array. + Dec.MaxNum = Size; - // Calculate how many entries for every bit length in LengthTable we have. - uint[] LengthCount = new uint[16]; - //memset(LengthCount,0,sizeof(LengthCount)); - for (size_t I=0;IDecodeNum,0,Size*sizeof(*Dec->DecodeNum)); - new Span(Dec.DecodeNum).Clear(); + // Set the entire DecodeNum to zero. + //memset(Dec->DecodeNum,0,Size*sizeof(*Dec->DecodeNum)); + new Span(Dec.DecodeNum).Clear(); - // Initialize not really used entry for zero length code. - Dec.DecodePos[0]=0; + // Initialize not really used entry for zero length code. + Dec.DecodePos[0] = 0; - // Start code for bit length 1 is 0. - Dec.DecodeLen[0]=0; + // Start code for bit length 1 is 0. + Dec.DecodeLen[0] = 0; - // Right aligned upper limit code for current bit length. - uint UpperLimit=0; + // Right aligned upper limit code for current bit length. + uint UpperLimit = 0; - for (int I=1;I<16;I++) - { - // Adjust the upper limit code. - UpperLimit+=LengthCount[I]; + for (int I = 1; I < 16; I++) + { + // Adjust the upper limit code. + UpperLimit += LengthCount[I]; - // Left aligned upper limit code. - uint LeftAligned=UpperLimit<<(16-I); + // Left aligned upper limit code. + uint LeftAligned = UpperLimit << (16 - I); - // Prepare the upper limit code for next bit length. - UpperLimit*=2; + // Prepare the upper limit code for next bit length. + UpperLimit *= 2; - // Store the left aligned upper limit code. - Dec.DecodeLen[I]=(uint)LeftAligned; + // Store the left aligned upper limit code. + Dec.DecodeLen[I] = (uint)LeftAligned; - // Every item of this array contains the sum of all preceding items. - // So it contains the start position in code list for every bit length. - Dec.DecodePos[I]=Dec.DecodePos[I-1]+LengthCount[I-1]; - } + // Every item of this array contains the sum of all preceding items. + // So it contains the start position in code list for every bit length. + Dec.DecodePos[I] = Dec.DecodePos[I - 1] + LengthCount[I - 1]; + } - // Prepare the copy of DecodePos. We'll modify this copy below, - // so we cannot use the original DecodePos. - uint[] CopyDecodePos = new uint[Dec.DecodePos.Length]; - //memcpy(CopyDecodePos,Dec->DecodePos,sizeof(CopyDecodePos)); - Array.Copy(Dec.DecodePos, CopyDecodePos, CopyDecodePos.Length); + // Prepare the copy of DecodePos. We'll modify this copy below, + // so we cannot use the original DecodePos. + uint[] CopyDecodePos = new uint[Dec.DecodePos.Length]; + //memcpy(CopyDecodePos,Dec->DecodePos,sizeof(CopyDecodePos)); + Array.Copy(Dec.DecodePos, CopyDecodePos, CopyDecodePos.Length); - // For every bit length in the bit length table and so for every item - // of alphabet. - for (uint I=0;I=Dec.DecodeLen[CurBitLength]) - { - CurBitLength++; - } + // Find the upper limit for current bit field and adjust the bit length + // accordingly if necessary. + while (CurBitLength < Dec.DecodeLen.Length && BitField >= Dec.DecodeLen[CurBitLength]) + { + CurBitLength++; + } - // Translation of right aligned bit string to bit length. - Dec.QuickLen[Code]=CurBitLength; + // Translation of right aligned bit string to bit length. + Dec.QuickLen[Code] = CurBitLength; - // Prepare the table for quick translation of position in code list - // to position in alphabet. + // Prepare the table for quick translation of position in code list + // to position in alphabet. - // Calculate the distance from the start code for current bit length. - uint Dist=BitField-Dec.DecodeLen[CurBitLength-1]; + // Calculate the distance from the start code for current bit length. + uint Dist = BitField - Dec.DecodeLen[CurBitLength - 1]; - // Right align the distance. - Dist>>=(16-CurBitLength); + // Right align the distance. + Dist >>= (16 - CurBitLength); - // Now we can calculate the position in the code list. It is the sum - // of first position for current bit length and right aligned distance - // between our bit field and start code for current bit length. - uint Pos; - if (CurBitLength 0) - { - Window[UnpPtr++] = Window[SrcPtr++]; - } + // TODO: sharpcompress: non-optimized loop, we may be able to unroll and speed up + var Window = this.Window; + while (Length-- > 0) + { + Window[UnpPtr++] = Window[SrcPtr++]; + } -// byte *Src=Window+SrcPtr; -// byte *Dest=Window+UnpPtr; -// UnpPtr+=Length; -// -//#if FAST_MEMCPY -// if (Distance=8) -// { -// Dest[0]=Src[0]; -// Dest[1]=Src[1]; -// Dest[2]=Src[2]; -// Dest[3]=Src[3]; -// Dest[4]=Src[4]; -// Dest[5]=Src[5]; -// Dest[6]=Src[6]; -// Dest[7]=Src[7]; -// -// Src+=8; -// Dest+=8; -// Length-=8; -// } -//#if FAST_MEMCPY -// else -// while (Length>=8) -// { -// // In theory we still could overlap here. -// // Supposing Distance == MaxWinSize - 1 we have memcpy(Src, Src + 1, 8). -// // But for real RAR archives Distance <= MaxWinSize - MAX_LZ_MATCH -// // always, so overlap here is impossible. -// -// // This memcpy expanded inline by MSVC. We could also use uint64 -// // assignment, which seems to provide about the same speed. -// memcpy(Dest,Src,8); -// -// Src+=8; -// Dest+=8; -// Length-=8; -// } -//#endif -// -// // Unroll the loop for 0 - 7 bytes left. Note that we use nested "if"s. -// if (Length>0) { Dest[0]=Src[0]; -// if (Length>1) { Dest[1]=Src[1]; -// if (Length>2) { Dest[2]=Src[2]; -// if (Length>3) { Dest[3]=Src[3]; -// if (Length>4) { Dest[4]=Src[4]; -// if (Length>5) { Dest[5]=Src[5]; -// if (Length>6) { Dest[6]=Src[6]; } } } } } } } // Close all nested "if"s. - } - else - { - while (Length-- > 0) // Slow copying with all possible precautions. - { - Window[UnpPtr]=Window[SrcPtr++ & MaxWinMask]; - // We need to have masked UnpPtr after quit from loop, so it must not - // be replaced with 'Window[UnpPtr++ & MaxWinMask]' - UnpPtr=(UnpPtr+1) & MaxWinMask; - } - } -} + // byte *Src=Window+SrcPtr; + // byte *Dest=Window+UnpPtr; + // UnpPtr+=Length; + // + //#if FAST_MEMCPY + // if (Distance=8) + // { + // Dest[0]=Src[0]; + // Dest[1]=Src[1]; + // Dest[2]=Src[2]; + // Dest[3]=Src[3]; + // Dest[4]=Src[4]; + // Dest[5]=Src[5]; + // Dest[6]=Src[6]; + // Dest[7]=Src[7]; + // + // Src+=8; + // Dest+=8; + // Length-=8; + // } + //#if FAST_MEMCPY + // else + // while (Length>=8) + // { + // // In theory we still could overlap here. + // // Supposing Distance == MaxWinSize - 1 we have memcpy(Src, Src + 1, 8). + // // But for real RAR archives Distance <= MaxWinSize - MAX_LZ_MATCH + // // always, so overlap here is impossible. + // + // // This memcpy expanded inline by MSVC. We could also use uint64 + // // assignment, which seems to provide about the same speed. + // memcpy(Dest,Src,8); + // + // Src+=8; + // Dest+=8; + // Length-=8; + // } + //#endif + // + // // Unroll the loop for 0 - 7 bytes left. Note that we use nested "if"s. + // if (Length>0) { Dest[0]=Src[0]; + // if (Length>1) { Dest[1]=Src[1]; + // if (Length>2) { Dest[2]=Src[2]; + // if (Length>3) { Dest[3]=Src[3]; + // if (Length>4) { Dest[4]=Src[4]; + // if (Length>5) { Dest[5]=Src[5]; + // if (Length>6) { Dest[6]=Src[6]; } } } } } } } // Close all nested "if"s. + } + else + { + while (Length-- > 0) // Slow copying with all possible precautions. + { + Window[UnpPtr] = Window[SrcPtr++ & MaxWinMask]; + // We need to have masked UnpPtr after quit from loop, so it must not + // be replaced with 'Window[UnpPtr++ & MaxWinMask]' + UnpPtr = (UnpPtr + 1) & MaxWinMask; + } + } + } - private uint DecodeNumber(BitInput Inp,DecodeTable Dec) -{ - // Left aligned 15 bit length raw bit field. - uint BitField=Inp.getbits() & 0xfffe; + private uint DecodeNumber(BitInput Inp, DecodeTable Dec) + { + // Left aligned 15 bit length raw bit field. + uint BitField = Inp.getbits() & 0xfffe; - if (BitField>(int)(16-Dec.QuickBits); - Inp.addbits(Dec.QuickLen[Code]); - return Dec.QuickNum[Code]; - } + if (BitField < Dec.DecodeLen[Dec.QuickBits]) + { + uint Code = BitField >> (int)(16 - Dec.QuickBits); + Inp.addbits(Dec.QuickLen[Code]); + return Dec.QuickNum[Code]; + } - // Detect the real bit length for current code. - uint Bits=15; - for (uint I=Dec.QuickBits+1;I<15;I++) - { - if (BitField>=(int)(16-Bits); + // Calculate the distance from the start code for current bit length. + uint Dist = BitField - Dec.DecodeLen[Bits - 1]; - // Now we can calculate the position in the code list. It is the sum - // of first position for current bit length and right aligned distance - // between our bit field and start code for current bit length. - uint Pos=Dec.DecodePos[Bits]+Dist; + // Start codes are left aligned, but we need the normal right aligned + // number. So we shift the distance to the right. + Dist >>= (int)(16 - Bits); - // Out of bounds safety check required for damaged archives. - if (Pos>=Dec.MaxNum) - { - Pos=0; - } + // Now we can calculate the position in the code list. It is the sum + // of first position for current bit length and right aligned distance + // between our bit field and start code for current bit length. + uint Pos = Dec.DecodePos[Bits] + Dist; - // Convert the position in the code list to position in alphabet - // and return it. - return Dec.DecodeNum[Pos]; -} + // Out of bounds safety check required for damaged archives. + if (Pos >= Dec.MaxNum) + { + Pos = 0; + } - private uint SlotToLength(BitInput Inp,uint Slot) -{ - uint LBits,Length=2; - if (Slot<8) - { - LBits=0; - Length+=Slot; - } - else - { - LBits=Slot/4-1; - Length+=(4 | (Slot & 3)) << (int)LBits; - } + // Convert the position in the code list to position in alphabet + // and return it. + return Dec.DecodeNum[Pos]; + } - if (LBits>0) - { - Length+=Inp.getbits()>>(int)(16-LBits); - Inp.addbits(LBits); - } - return Length; -} + private uint SlotToLength(BitInput Inp, uint Slot) + { + uint LBits, Length = 2; + if (Slot < 8) + { + LBits = 0; + Length += Slot; + } + else + { + LBits = Slot / 4 - 1; + Length += (4 | (Slot & 3)) << (int)LBits; + } + + if (LBits > 0) + { + Length += Inp.getbits() >> (int)(16 - LBits); + Inp.addbits(LBits); + } + return Length; + } } } diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/unpack_hpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/unpack_hpp.cs index f525622b..e28720d6 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/unpack_hpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/unpack_hpp.cs @@ -24,101 +24,102 @@ namespace SharpCompress.Compressors.Rar.UnpackV2017 { -// Maximum allowed number of compressed bits processed in quick mode. -public const int MAX_QUICK_DECODE_BITS =10; + // Maximum allowed number of compressed bits processed in quick mode. + public const int MAX_QUICK_DECODE_BITS = 10; -// Maximum number of filters per entire data block. Must be at least -// twice more than MAX_PACK_FILTERS to store filters from two data blocks. -public const int MAX_UNPACK_FILTERS =8192; + // Maximum number of filters per entire data block. Must be at least + // twice more than MAX_PACK_FILTERS to store filters from two data blocks. + public const int MAX_UNPACK_FILTERS = 8192; -// Maximum number of filters per entire data block for RAR3 unpack. -// Must be at least twice more than v3_MAX_PACK_FILTERS to store filters -// from two data blocks. -public const int MAX3_UNPACK_FILTERS =8192; + // Maximum number of filters per entire data block for RAR3 unpack. + // Must be at least twice more than v3_MAX_PACK_FILTERS to store filters + // from two data blocks. + public const int MAX3_UNPACK_FILTERS = 8192; -// Limit maximum number of channels in RAR3 delta filter to some reasonable -// value to prevent too slow processing of corrupt archives with invalid -// channels number. Must be equal or larger than v3_MAX_FILTER_CHANNELS. -// No need to provide it for RAR5, which uses only 5 bits to store channels. -private const int MAX3_UNPACK_CHANNELS =1024; + // Limit maximum number of channels in RAR3 delta filter to some reasonable + // value to prevent too slow processing of corrupt archives with invalid + // channels number. Must be equal or larger than v3_MAX_FILTER_CHANNELS. + // No need to provide it for RAR5, which uses only 5 bits to store channels. + private const int MAX3_UNPACK_CHANNELS = 1024; -// Maximum size of single filter block. We restrict it to limit memory -// allocation. Must be equal or larger than MAX_ANALYZE_SIZE. -public const int MAX_FILTER_BLOCK_SIZE =0x400000; + // Maximum size of single filter block. We restrict it to limit memory + // allocation. Must be equal or larger than MAX_ANALYZE_SIZE. + public const int MAX_FILTER_BLOCK_SIZE = 0x400000; -// Write data in 4 MB or smaller blocks. Must not exceed PACK_MAX_WRITE, -// so we keep number of buffered filter in unpacker reasonable. -public const int UNPACK_MAX_WRITE =0x400000; + // Write data in 4 MB or smaller blocks. Must not exceed PACK_MAX_WRITE, + // so we keep number of buffered filter in unpacker reasonable. + public const int UNPACK_MAX_WRITE = 0x400000; } -// Decode compressed bit fields to alphabet numbers. + // Decode compressed bit fields to alphabet numbers. internal sealed class DecodeTable -{ - // Real size of DecodeNum table. - public uint MaxNum; + { + // Real size of DecodeNum table. + public uint MaxNum; - // Left aligned start and upper limit codes defining code space - // ranges for bit lengths. DecodeLen[BitLength-1] defines the start of - // range for bit length and DecodeLen[BitLength] defines next code - // after the end of range or in other words the upper limit code - // for specified bit length. - public readonly uint[] DecodeLen = new uint[16]; + // Left aligned start and upper limit codes defining code space + // ranges for bit lengths. DecodeLen[BitLength-1] defines the start of + // range for bit length and DecodeLen[BitLength] defines next code + // after the end of range or in other words the upper limit code + // for specified bit length. + public readonly uint[] DecodeLen = new uint[16]; - // Every item of this array contains the sum of all preceding items. - // So it contains the start position in code list for every bit length. - public readonly uint[] DecodePos = new uint[16]; + // Every item of this array contains the sum of all preceding items. + // So it contains the start position in code list for every bit length. + public readonly uint[] DecodePos = new uint[16]; - // Number of compressed bits processed in quick mode. - // Must not exceed MAX_QUICK_DECODE_BITS. - public uint QuickBits; + // Number of compressed bits processed in quick mode. + // Must not exceed MAX_QUICK_DECODE_BITS. + public uint QuickBits; - // Translates compressed bits (up to QuickBits length) - // to bit length in quick mode. - public readonly byte[] QuickLen = new byte[1<(); - private byte[] FilterDstMemory = Array.Empty(); + private byte[] FilterSrcMemory = Array.Empty(); + private byte[] FilterDstMemory = Array.Empty(); - // Filters code, one entry per filter. - private readonly List Filters = new List(); + // Filters code, one entry per filter. + private readonly List Filters = new List(); - private readonly uint[] OldDist = new uint[4]; - private uint OldDistPtr; - private uint LastLength; + private readonly uint[] OldDist = new uint[4]; + private uint OldDistPtr; + private uint LastLength; - // LastDist is necessary only for RAR2 and older with circular OldDist - // array. In RAR3 last distance is always stored in OldDist[0]. - private uint LastDist; + // LastDist is necessary only for RAR2 and older with circular OldDist + // array. In RAR3 last distance is always stored in OldDist[0]. + private uint LastDist; - private size_t UnpPtr,WrPtr; - - // Top border of read packed data. - private int ReadTop; + private size_t UnpPtr, WrPtr; - // Border to call UnpReadBuf. We use it instead of (ReadTop-C) - // for optimization reasons. Ensures that we have C bytes in buffer - // unless we are at the end of file. - private int ReadBorder; + // Top border of read packed data. + private int ReadTop; - private UnpackBlockHeader BlockHeader; - private UnpackBlockTables BlockTables; + // Border to call UnpReadBuf. We use it instead of (ReadTop-C) + // for optimization reasons. Ensures that we have C bytes in buffer + // unless we are at the end of file. + private int ReadBorder; - private size_t WriteBorder; + private UnpackBlockHeader BlockHeader; + private UnpackBlockTables BlockTables; - private byte[] Window; + private size_t WriteBorder; - private readonly FragmentedWindow FragWindow = new FragmentedWindow(); - private bool Fragmented; + private byte[] Window; - private int64 DestUnpSize; + private readonly FragmentedWindow FragWindow = new FragmentedWindow(); + private bool Fragmented; - //bool Suspended; - private bool UnpAllBuf; - private bool UnpSomeRead; - private int64 WrittenFileSize; - private bool FileExtracted; + private int64 DestUnpSize; + + //bool Suspended; + private bool UnpAllBuf; + private bool UnpSomeRead; + private int64 WrittenFileSize; + private bool FileExtracted; -/***************************** Unpack v 1.5 *********************************/ - //void Unpack15(bool Solid); - //void ShortLZ(); - //void LongLZ(); - //void HuffDecode(); - //void GetFlagsBuf(); - //void UnpInitData15(int Solid); - //void InitHuff(); - //void CorrHuff(ushort *CharSet,byte *NumToPlace); - //void CopyString15(uint Distance,uint Length); - //uint DecodeNum(uint Num,uint StartPos,uint *DecTab,uint *PosTab); + /***************************** Unpack v 1.5 *********************************/ + //void Unpack15(bool Solid); + //void ShortLZ(); + //void LongLZ(); + //void HuffDecode(); + //void GetFlagsBuf(); + //void UnpInitData15(int Solid); + //void InitHuff(); + //void CorrHuff(ushort *CharSet,byte *NumToPlace); + //void CopyString15(uint Distance,uint Length); + //uint DecodeNum(uint Num,uint StartPos,uint *DecTab,uint *PosTab); - private readonly ushort[] ChSet = new ushort[256],ChSetA = new ushort[256],ChSetB = new ushort[256],ChSetC = new ushort[256]; - private readonly byte[] NToPl = new byte[256],NToPlB = new byte[256],NToPlC = new byte[256]; - private uint FlagBuf,AvrPlc,AvrPlcB,AvrLn1,AvrLn2,AvrLn3; - private int Buf60,NumHuf,StMode,LCount,FlagsCnt; + private readonly ushort[] ChSet = new ushort[256], ChSetA = new ushort[256], ChSetB = new ushort[256], ChSetC = new ushort[256]; + private readonly byte[] NToPl = new byte[256], NToPlB = new byte[256], NToPlC = new byte[256]; + private uint FlagBuf, AvrPlc, AvrPlcB, AvrLn1, AvrLn2, AvrLn3; + private int Buf60, NumHuf, StMode, LCount, FlagsCnt; - private uint Nhfb,Nlzb,MaxDist3; -/***************************** Unpack v 1.5 *********************************/ + private uint Nhfb, Nlzb, MaxDist3; + /***************************** Unpack v 1.5 *********************************/ -/***************************** Unpack v 2.0 *********************************/ - //void Unpack20(bool Solid); + /***************************** Unpack v 2.0 *********************************/ + //void Unpack20(bool Solid); - private DecodeTable[] MD = new DecodeTable[4]; // Decode multimedia data, up to 4 channels. + private DecodeTable[] MD = new DecodeTable[4]; // Decode multimedia data, up to 4 channels. - private readonly byte[] UnpOldTable20 = new byte[MC20*4]; - private bool UnpAudioBlock; - private uint UnpChannels,UnpCurChannel; + private readonly byte[] UnpOldTable20 = new byte[MC20 * 4]; + private bool UnpAudioBlock; + private uint UnpChannels, UnpCurChannel; - private int UnpChannelDelta; - //void CopyString20(uint Length,uint Distance); - //bool ReadTables20(); - //void UnpWriteBuf20(); - //void UnpInitData20(int Solid); - //void ReadLastTables(); - //byte DecodeAudio(int Delta); - private AudioVariables[] AudV = new AudioVariables[4]; -/***************************** Unpack v 2.0 *********************************/ + private int UnpChannelDelta; + //void CopyString20(uint Length,uint Distance); + //bool ReadTables20(); + //void UnpWriteBuf20(); + //void UnpInitData20(int Solid); + //void ReadLastTables(); + //byte DecodeAudio(int Delta); + private AudioVariables[] AudV = new AudioVariables[4]; + /***************************** Unpack v 2.0 *********************************/ -/***************************** Unpack v 3.0 *********************************/ - public const int BLOCK_LZ = 0; - public const int BLOCK_PPM = 1; + /***************************** Unpack v 3.0 *********************************/ + public const int BLOCK_LZ = 0; + public const int BLOCK_PPM = 1; - //void UnpInitData30(bool Solid); - //void Unpack29(bool Solid); - //void InitFilters30(bool Solid); - //bool ReadEndOfBlock(); - //bool ReadVMCode(); - //bool ReadVMCodePPM(); - //bool AddVMCode(uint FirstByte,byte *Code,int CodeSize); - //int SafePPMDecodeChar(); - //bool ReadTables30(); - //bool UnpReadBuf30(); - //void UnpWriteBuf30(); - //void ExecuteCode(VM_PreparedProgram *Prg); + //void UnpInitData30(bool Solid); + //void Unpack29(bool Solid); + //void InitFilters30(bool Solid); + //bool ReadEndOfBlock(); + //bool ReadVMCode(); + //bool ReadVMCodePPM(); + //bool AddVMCode(uint FirstByte,byte *Code,int CodeSize); + //int SafePPMDecodeChar(); + //bool ReadTables30(); + //bool UnpReadBuf30(); + //void UnpWriteBuf30(); + //void ExecuteCode(VM_PreparedProgram *Prg); - private int PrevLowDist,LowDistRepCount; + private int PrevLowDist, LowDistRepCount; -/*#if !RarV2017_RAR5ONLY - ModelPPM PPM; -#endif*/ - private int PPMEscChar; + /*#if !RarV2017_RAR5ONLY + ModelPPM PPM; + #endif*/ + private int PPMEscChar; - private readonly byte [] UnpOldTable = new byte[HUFF_TABLE_SIZE30]; - private int UnpBlockType; + private readonly byte[] UnpOldTable = new byte[HUFF_TABLE_SIZE30]; + private int UnpBlockType; - // If we already read decoding tables for Unpack v2,v3,v5. - // We should not use a single variable for all algorithm versions, - // because we can have a corrupt archive with one algorithm file - // followed by another algorithm file with "solid" flag and we do not - // want to reuse tables from one algorithm in another. - private bool TablesRead2,TablesRead3,TablesRead5; + // If we already read decoding tables for Unpack v2,v3,v5. + // We should not use a single variable for all algorithm versions, + // because we can have a corrupt archive with one algorithm file + // followed by another algorithm file with "solid" flag and we do not + // want to reuse tables from one algorithm in another. + private bool TablesRead2, TablesRead3, TablesRead5; - // Virtual machine to execute filters code. -/*#if !RarV2017_RAR5ONLY - RarVM VM; -#endif*/ - - // Buffer to read VM filters code. We moved it here from AddVMCode - // function to reduce time spent in BitInput constructor. - private readonly BitInput VMCodeInp = new BitInput(true); + // Virtual machine to execute filters code. + /*#if !RarV2017_RAR5ONLY + RarVM VM; + #endif*/ - // Filters code, one entry per filter. - private readonly List Filters30 = new List(); + // Buffer to read VM filters code. We moved it here from AddVMCode + // function to reduce time spent in BitInput constructor. + private readonly BitInput VMCodeInp = new BitInput(true); - // Filters stack, several entrances of same filter are possible. - private readonly List PrgStack = new List(); + // Filters code, one entry per filter. + private readonly List Filters30 = new List(); - // Lengths of preceding data blocks, one length of one last block - // for every filter. Used to reduce the size required to write - // the data block length if lengths are repeating. - private readonly List OldFilterLengths = new List(); + // Filters stack, several entrances of same filter are possible. + private readonly List PrgStack = new List(); - private int LastFilter; -/***************************** Unpack v 3.0 *********************************/ + // Lengths of preceding data blocks, one length of one last block + // for every filter. Used to reduce the size required to write + // the data block length if lengths are repeating. + private readonly List OldFilterLengths = new List(); - //Unpack(ComprDataIO *DataIO); - //~Unpack(); - //void Init(size_t WinSize,bool Solid); - //void DoUnpack(uint Method,bool Solid); - private bool IsFileExtracted() {return(FileExtracted);} - private void SetDestSize(int64 DestSize) {DestUnpSize=DestSize;FileExtracted=false;} - private void SetSuspended(bool Suspended) {this.Suspended=Suspended;} + private int LastFilter; + /***************************** Unpack v 3.0 *********************************/ + + //Unpack(ComprDataIO *DataIO); + //~Unpack(); + //void Init(size_t WinSize,bool Solid); + //void DoUnpack(uint Method,bool Solid); + private bool IsFileExtracted() { return (FileExtracted); } + private void SetDestSize(int64 DestSize) { DestUnpSize = DestSize; FileExtracted = false; } + private void SetSuspended(bool Suspended) { this.Suspended = Suspended; } #if RarV2017_RAR_SMP // More than 8 threads are unlikely to provide a noticeable gain @@ -427,18 +428,18 @@ internal partial class Unpack void UnpackDecode(UnpackThreadData &D); #endif - private size_t MaxWinSize; - private size_t MaxWinMask; + private size_t MaxWinSize; + private size_t MaxWinMask; - private uint GetChar() - { - if (Inp.InAddr>MAX_SIZE-30) - { - UnpReadBuf(); - } + private uint GetChar() + { + if (Inp.InAddr > MAX_SIZE - 30) + { + UnpReadBuf(); + } - return(Inp.InBuf[Inp.InAddr++]); - } + return (Inp.InBuf[Inp.InAddr++]); + } } diff --git a/src/SharpCompress/Compressors/Rar/VM/BitInput.cs b/src/SharpCompress/Compressors/Rar/VM/BitInput.cs index 82575912..c0656086 100644 --- a/src/SharpCompress/Compressors/Rar/VM/BitInput.cs +++ b/src/SharpCompress/Compressors/Rar/VM/BitInput.cs @@ -8,9 +8,9 @@ namespace SharpCompress.Compressors.Rar.VM public int inAddr; public int inBit; -// TODO: rename var - public int InAddr { get { return inAddr; } set { inAddr = value; } } - public int InBit { get { return inBit; } set { inBit = value; } } + // TODO: rename var + public int InAddr { get { return inAddr; } set { inAddr = value; } } + public int InBit { get { return inBit; } set { inBit = value; } } public bool ExternalBuffer; @@ -28,7 +28,8 @@ namespace SharpCompress.Compressors.Rar.VM inBit = 0; } - internal void faddbits(uint bits) { + internal void faddbits(uint bits) + { // TODO uint AddBits((int)bits); } @@ -44,12 +45,14 @@ namespace SharpCompress.Compressors.Rar.VM inBit = bits & 7; } - internal uint fgetbits() { + internal uint fgetbits() + { // TODO uint return (uint)GetBits(); } - internal uint getbits() { + internal uint getbits() + { // TODO uint return (uint)GetBits(); } diff --git a/src/SharpCompress/Compressors/Rar/VM/RarVM.cs b/src/SharpCompress/Compressors/Rar/VM/RarVM.cs index d2a90440..d7180efb 100644 --- a/src/SharpCompress/Compressors/Rar/VM/RarVM.cs +++ b/src/SharpCompress/Compressors/Rar/VM/RarVM.cs @@ -51,7 +51,7 @@ namespace SharpCompress.Compressors.Rar.VM internal void init() { - Mem ??= new byte[VM_MEMSIZE + 4]; + Mem ??= new byte[VM_MEMSIZE + 4]; } private bool IsVMMem(byte[] mem) @@ -133,7 +133,7 @@ namespace SharpCompress.Compressors.Rar.VM { for (int i = 0; i < prg.InitR.Length; i++) - // memcpy(R,Prg->InitR,sizeof(Prg->InitR)); + // memcpy(R,Prg->InitR,sizeof(Prg->InitR)); { R[i] = prg.InitR[i]; } @@ -143,7 +143,7 @@ namespace SharpCompress.Compressors.Rar.VM { for (int i = 0; i < globalSize; i++) - // memcpy(Mem+VM_GLOBALMEMADDR,&Prg->GlobalData[0],GlobalSize); + // memcpy(Mem+VM_GLOBALMEMADDR,&Prg->GlobalData[0],GlobalSize); { Mem[VM_GLOBALMEMADDR + i] = prg.GlobalData[i]; } @@ -153,7 +153,7 @@ namespace SharpCompress.Compressors.Rar.VM { for (int i = 0; i < staticSize; i++) - // memcpy(Mem+VM_GLOBALMEMADDR+GlobalSize,&Prg->StaticData[0],StaticSize); + // memcpy(Mem+VM_GLOBALMEMADDR+GlobalSize,&Prg->StaticData[0],StaticSize); { Mem[VM_GLOBALMEMADDR + (int)globalSize + i] = prg.StaticData[i]; } @@ -192,7 +192,7 @@ namespace SharpCompress.Compressors.Rar.VM prg.GlobalData.Capacity = dataSize + VM_FIXEDGLOBALSIZE; for (int i = 0; i < dataSize + VM_FIXEDGLOBALSIZE; i++) - // memcpy(&Prg->GlobalData[0],&Mem[VM_GLOBALMEMADDR],DataSize+VM_FIXEDGLOBALSIZE); + // memcpy(&Prg->GlobalData[0],&Mem[VM_GLOBALMEMADDR],DataSize+VM_FIXEDGLOBALSIZE); { prg.GlobalData.Add(Mem[VM_GLOBALMEMADDR + i]); } @@ -244,83 +244,83 @@ namespace SharpCompress.Compressors.Rar.VM break; case VMCommands.VM_CMP: - { - VMFlags value1 = (VMFlags)GetValue(cmd.IsByteMode, Mem, op1); - VMFlags result = value1 - GetValue(cmd.IsByteMode, Mem, op2); + { + VMFlags value1 = (VMFlags)GetValue(cmd.IsByteMode, Mem, op1); + VMFlags result = value1 - GetValue(cmd.IsByteMode, Mem, op2); - if (result == 0) - { - flags = VMFlags.VM_FZ; + if (result == 0) + { + flags = VMFlags.VM_FZ; + } + else + { + flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + } } - else - { - flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); - } - } break; case VMCommands.VM_CMPB: - { - VMFlags value1 = (VMFlags)GetValue(true, Mem, op1); - VMFlags result = value1 - GetValue(true, Mem, op2); - if (result == 0) { - flags = VMFlags.VM_FZ; + VMFlags value1 = (VMFlags)GetValue(true, Mem, op1); + VMFlags result = value1 - GetValue(true, Mem, op2); + if (result == 0) + { + flags = VMFlags.VM_FZ; + } + else + { + flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + } } - else - { - flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); - } - } break; case VMCommands.VM_CMPD: - { - VMFlags value1 = (VMFlags)GetValue(false, Mem, op1); - VMFlags result = value1 - GetValue(false, Mem, op2); - if (result == 0) { - flags = VMFlags.VM_FZ; + VMFlags value1 = (VMFlags)GetValue(false, Mem, op1); + VMFlags result = value1 - GetValue(false, Mem, op2); + if (result == 0) + { + flags = VMFlags.VM_FZ; + } + else + { + flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + } } - else - { - flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); - } - } break; case VMCommands.VM_ADD: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int result = - (int) - (((value1 + (long)GetValue(cmd.IsByteMode, Mem, op2))) & - unchecked((int)0xffffffff)); - if (cmd.IsByteMode) { - result &= 0xff; - flags = - (VMFlags) - ((result < value1) - ? 1 - : 0 | - (result == 0 - ? (int)VMFlags.VM_FZ - : (((result & 0x80) != 0) ? (int)VMFlags.VM_FS : 0))); + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int result = + (int) + (((value1 + (long)GetValue(cmd.IsByteMode, Mem, op2))) & + unchecked((int)0xffffffff)); + if (cmd.IsByteMode) + { + result &= 0xff; + flags = + (VMFlags) + ((result < value1) + ? 1 + : 0 | + (result == 0 + ? (int)VMFlags.VM_FZ + : (((result & 0x80) != 0) ? (int)VMFlags.VM_FS : 0))); - // Flags=(Result value1) ? 1 : 0 | (result & (int)VMFlags.VM_FS))); - SetValue(cmd.IsByteMode, Mem, op1, result); // (Cmd->ByteMode,Op1,Result); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int result = + (int) + (value1 & 0xffFFffFF - GetValue(cmd.IsByteMode, Mem, op2) & + unchecked((int)0xFFffFFff)); + flags = + (VMFlags) + ((result == 0) + ? (int)VMFlags.VM_FZ + : ((result > value1) ? 1 : 0 | (result & (int)VMFlags.VM_FS))); + SetValue(cmd.IsByteMode, Mem, op1, result); // (Cmd->ByteMode,Op1,Result); + } break; case VMCommands.VM_SUBB: @@ -384,16 +384,16 @@ namespace SharpCompress.Compressors.Rar.VM break; case VMCommands.VM_INC: - { - int result = (int)(GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFffL + 1L); - if (cmd.IsByteMode) { - result &= 0xff; - } + int result = (int)(GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFffL + 1L); + if (cmd.IsByteMode) + { + result &= 0xff; + } - SetValue(cmd.IsByteMode, Mem, op1, result); - flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); - } + SetValue(cmd.IsByteMode, Mem, op1, result); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + } break; case VMCommands.VM_INCB: @@ -405,11 +405,11 @@ namespace SharpCompress.Compressors.Rar.VM break; case VMCommands.VM_DEC: - { - int result = (int)(GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFff - 1); - SetValue(cmd.IsByteMode, Mem, op1, result); - flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); - } + { + int result = (int)(GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFff - 1); + SetValue(cmd.IsByteMode, Mem, op1, result); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + } break; case VMCommands.VM_DECB: @@ -425,34 +425,34 @@ namespace SharpCompress.Compressors.Rar.VM continue; case VMCommands.VM_XOR: - { - int result = GetValue(cmd.IsByteMode, Mem, op1) ^ GetValue(cmd.IsByteMode, Mem, op2); - flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = GetValue(cmd.IsByteMode, Mem, op1) ^ GetValue(cmd.IsByteMode, Mem, op2); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_AND: - { - int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2); - flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_OR: - { - int result = GetValue(cmd.IsByteMode, Mem, op1) | GetValue(cmd.IsByteMode, Mem, op2); - flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = GetValue(cmd.IsByteMode, Mem, op1) | GetValue(cmd.IsByteMode, Mem, op2); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_TEST: - { - int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2); - flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); - } + { + int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + } break; case VMCommands.VM_JS: @@ -524,56 +524,56 @@ namespace SharpCompress.Compressors.Rar.VM break; case VMCommands.VM_SHL: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int value2 = GetValue(cmd.IsByteMode, Mem, op2); - int result = value1 << value2; - flags = - (VMFlags) - ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | - (((value1 << (value2 - 1)) & unchecked((int)0x80000000)) != 0 - ? (int)VMFlags.VM_FC - : 0)); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int value2 = GetValue(cmd.IsByteMode, Mem, op2); + int result = value1 << value2; + flags = + (VMFlags) + ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | + (((value1 << (value2 - 1)) & unchecked((int)0x80000000)) != 0 + ? (int)VMFlags.VM_FC + : 0)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_SHR: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int value2 = GetValue(cmd.IsByteMode, Mem, op2); - int result = Utility.URShift(value1, value2); - flags = - (VMFlags) - ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | - ((Utility.URShift(value1, (value2 - 1))) & (int)VMFlags.VM_FC)); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int value2 = GetValue(cmd.IsByteMode, Mem, op2); + int result = Utility.URShift(value1, value2); + flags = + (VMFlags) + ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | + ((Utility.URShift(value1, (value2 - 1))) & (int)VMFlags.VM_FC)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_SAR: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int value2 = GetValue(cmd.IsByteMode, Mem, op2); - int result = value1 >> value2; - flags = - (VMFlags) - ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | - ((value1 >> (value2 - 1)) & (int)VMFlags.VM_FC)); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int value2 = GetValue(cmd.IsByteMode, Mem, op2); + int result = value1 >> value2; + flags = + (VMFlags) + ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | + ((value1 >> (value2 - 1)) & (int)VMFlags.VM_FC)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_NEG: - { - int result = -GetValue(cmd.IsByteMode, Mem, op1); - flags = - (VMFlags) - (result == 0 - ? (int)VMFlags.VM_FZ - : (int)VMFlags.VM_FC | (result & (int)VMFlags.VM_FS)); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = -GetValue(cmd.IsByteMode, Mem, op1); + flags = + (VMFlags) + (result == 0 + ? (int)VMFlags.VM_FZ + : (int)VMFlags.VM_FC | (result & (int)VMFlags.VM_FS)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_NEGB: @@ -585,22 +585,22 @@ namespace SharpCompress.Compressors.Rar.VM break; case VMCommands.VM_PUSHA: - { - for (int i = 0, SP = R[7] - 4; i < regCount; i++, SP -= 4) { - SetValue(false, Mem, SP & VM_MEMMASK, R[i]); + for (int i = 0, SP = R[7] - 4; i < regCount; i++, SP -= 4) + { + SetValue(false, Mem, SP & VM_MEMMASK, R[i]); + } + R[7] -= regCount * 4; } - R[7] -= regCount * 4; - } break; case VMCommands.VM_POPA: - { - for (int i = 0, SP = R[7]; i < regCount; i++, SP += 4) { - R[7 - i] = GetValue(false, Mem, SP & VM_MEMMASK); + for (int i = 0, SP = R[7]; i < regCount; i++, SP += 4) + { + R[7 - i] = GetValue(false, Mem, SP & VM_MEMMASK); + } } - } break; case VMCommands.VM_PUSHF: @@ -622,76 +622,76 @@ namespace SharpCompress.Compressors.Rar.VM break; case VMCommands.VM_XCHG: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2)); - SetValue(cmd.IsByteMode, Mem, op2, value1); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2)); + SetValue(cmd.IsByteMode, Mem, op2, value1); + } break; case VMCommands.VM_MUL: - { - int result = - (int) - ((GetValue(cmd.IsByteMode, Mem, op1) & - 0xFFffFFff * GetValue(cmd.IsByteMode, Mem, op2) & unchecked((int)0xFFffFFff)) & - unchecked((int)0xFFffFFff)); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = + (int) + ((GetValue(cmd.IsByteMode, Mem, op1) & + 0xFFffFFff * GetValue(cmd.IsByteMode, Mem, op2) & unchecked((int)0xFFffFFff)) & + unchecked((int)0xFFffFFff)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_DIV: - { - int divider = GetValue(cmd.IsByteMode, Mem, op2); - if (divider != 0) { - int result = GetValue(cmd.IsByteMode, Mem, op1) / divider; - SetValue(cmd.IsByteMode, Mem, op1, result); + int divider = GetValue(cmd.IsByteMode, Mem, op2); + if (divider != 0) + { + int result = GetValue(cmd.IsByteMode, Mem, op1) / divider; + SetValue(cmd.IsByteMode, Mem, op1, result); + } } - } break; case VMCommands.VM_ADC: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int FC = (int)(flags & VMFlags.VM_FC); - int result = - (int) - (value1 & 0xFFffFFff + GetValue(cmd.IsByteMode, Mem, op2) & - 0xFFffFFff + FC & unchecked((int)0xFFffFFff)); - if (cmd.IsByteMode) { - result &= 0xff; - } + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int FC = (int)(flags & VMFlags.VM_FC); + int result = + (int) + (value1 & 0xFFffFFff + GetValue(cmd.IsByteMode, Mem, op2) & + 0xFFffFFff + FC & unchecked((int)0xFFffFFff)); + if (cmd.IsByteMode) + { + result &= 0xff; + } - flags = - (VMFlags) - ((result < value1 || result == value1 && FC != 0) - ? 1 - : 0 | (result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS))); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + flags = + (VMFlags) + ((result < value1 || result == value1 && FC != 0) + ? 1 + : 0 | (result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS))); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_SBB: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int FC = (int)(flags & VMFlags.VM_FC); - int result = - (int) - (value1 & 0xFFffFFff - GetValue(cmd.IsByteMode, Mem, op2) & - 0xFFffFFff - FC & unchecked((int)0xFFffFFff)); - if (cmd.IsByteMode) { - result &= 0xff; + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int FC = (int)(flags & VMFlags.VM_FC); + int result = + (int) + (value1 & 0xFFffFFff - GetValue(cmd.IsByteMode, Mem, op2) & + 0xFFffFFff - FC & unchecked((int)0xFFffFFff)); + if (cmd.IsByteMode) + { + result &= 0xff; + } + flags = + (VMFlags) + ((result > value1 || result == value1 && FC != 0) + ? 1 + : 0 | (result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS))); + SetValue(cmd.IsByteMode, Mem, op1, result); } - flags = - (VMFlags) - ((result > value1 || result == value1 && FC != 0) - ? 1 - : 0 | (result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS))); - SetValue(cmd.IsByteMode, Mem, op1, result); - } break; case VMCommands.VM_RET: @@ -1071,330 +1071,330 @@ namespace SharpCompress.Compressors.Rar.VM { case VMStandardFilters.VMSF_E8: case VMStandardFilters.VMSF_E8E9: - { - int dataSize = R[4]; - long fileOffset = R[6] & unchecked((int)0xFFffFFff); + { + int dataSize = R[4]; + long fileOffset = R[6] & unchecked((int)0xFFffFFff); - if (dataSize >= VM_GLOBALMEMADDR) - { - break; - } - int fileSize = 0x1000000; - byte cmpByte2 = (byte)((filterType == VMStandardFilters.VMSF_E8E9) ? 0xe9 : 0xe8); - for (int curPos = 0; curPos < dataSize - 4;) - { - byte curByte = Mem[curPos++]; - if (curByte == 0xe8 || curByte == cmpByte2) + if (dataSize >= VM_GLOBALMEMADDR) { - // #ifdef PRESENT_INT32 - // sint32 Offset=CurPos+FileOffset; - // sint32 Addr=GET_VALUE(false,Data); - // if (Addr<0) - // { - // if (Addr+Offset>=0) - // SET_VALUE(false,Data,Addr+FileSize); - // } - // else - // if (Addr= VM_GLOBALMEMADDR) - { - break; - } - int curPos = 0; - - //UPGRADE_NOTE: Final was removed from the declaration of 'Masks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - byte[] Masks = {4, 4, 6, 6, 0, 0, 7, 7, 4, 4, 0, 0, 4, 4, 0, 0}; - fileOffset = Utility.URShift(fileOffset, 4); - - while (curPos < dataSize - 21) - { - int Byte = (Mem[curPos] & 0x1f) - 0x10; - if (Byte >= 0) + int fileSize = 0x1000000; + byte cmpByte2 = (byte)((filterType == VMStandardFilters.VMSF_E8E9) ? 0xe9 : 0xe8); + for (int curPos = 0; curPos < dataSize - 4;) { - byte cmdMask = Masks[Byte]; - if (cmdMask != 0) + byte curByte = Mem[curPos++]; + if (curByte == 0xe8 || curByte == cmpByte2) { - for (int i = 0; i <= 2; i++) + // #ifdef PRESENT_INT32 + // sint32 Offset=CurPos+FileOffset; + // sint32 Addr=GET_VALUE(false,Data); + // if (Addr<0) + // { + // if (Addr+Offset>=0) + // SET_VALUE(false,Data,Addr+FileSize); + // } + // else + // if (Addr= VM_GLOBALMEMADDR / 2) - { - break; - } - - // bytes from same channels are grouped to continual data blocks, - // so we need to place them back to their interleaving positions - - for (int curChannel = 0; curChannel < channels; curChannel++) - { - byte PrevByte = 0; - for (int destPos = dataSize + curChannel; destPos < border; destPos += channels) - { - Mem[destPos] = (PrevByte = (byte)(PrevByte - Mem[srcPos++])); - } - } - } - break; - - case VMStandardFilters.VMSF_RGB: - { - // byte *SrcData=Mem,*DestData=SrcData+DataSize; - int dataSize = R[4], width = R[0] - 3, posR = R[1]; - int channels = 3; - int srcPos = 0; - int destDataPos = dataSize; - SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); - if (dataSize >= VM_GLOBALMEMADDR / 2 || posR < 0) - { - break; - } - for (int curChannel = 0; curChannel < channels; curChannel++) - { - long prevByte = 0; - - for (int i = curChannel; i < dataSize; i += channels) - { - long predicted; - int upperPos = i - width; - if (upperPos >= 3) - { - int upperDataPos = destDataPos + upperPos; - int upperByte = Mem[upperDataPos] & 0xff; - int upperLeftByte = Mem[upperDataPos - 3] & 0xff; - predicted = prevByte + upperByte - upperLeftByte; - int pa = Math.Abs((int)(predicted - prevByte)); - int pb = Math.Abs((int)(predicted - upperByte)); - int pc = Math.Abs((int)(predicted - upperLeftByte)); - if (pa <= pb && pa <= pc) - { - predicted = prevByte; - } else { - if (pb <= pc) + if (((Addr - fileSize) & unchecked((int)0x80000000)) != 0) { - predicted = upperByte; + SetValue(false, Mem, curPos, (int)(Addr - offset)); + } + } + + // #endif + curPos += 4; + } + } + } + break; + + case VMStandardFilters.VMSF_ITANIUM: + { + int dataSize = R[4]; + long fileOffset = R[6] & unchecked((int)0xFFffFFff); + + if (dataSize >= VM_GLOBALMEMADDR) + { + break; + } + int curPos = 0; + + //UPGRADE_NOTE: Final was removed from the declaration of 'Masks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + byte[] Masks = { 4, 4, 6, 6, 0, 0, 7, 7, 4, 4, 0, 0, 4, 4, 0, 0 }; + fileOffset = Utility.URShift(fileOffset, 4); + + while (curPos < dataSize - 21) + { + int Byte = (Mem[curPos] & 0x1f) - 0x10; + if (Byte >= 0) + { + byte cmdMask = Masks[Byte]; + if (cmdMask != 0) + { + for (int i = 0; i <= 2; i++) + { + if ((cmdMask & (1 << i)) != 0) + { + int startPos = i * 41 + 5; + int opType = filterItanium_GetBits(curPos, startPos + 37, 4); + if (opType == 5) + { + int offset = filterItanium_GetBits(curPos, startPos + 13, 20); + filterItanium_SetBits(curPos, (int)(offset - fileOffset) & 0xfffff, + startPos + 13, 20); + } + } + } + } + } + curPos += 16; + fileOffset++; + } + } + break; + + case VMStandardFilters.VMSF_DELTA: + { + int dataSize = R[4] & unchecked((int)0xFFffFFff); + int channels = R[0] & unchecked((int)0xFFffFFff); + int srcPos = 0; + int border = (dataSize * 2) & unchecked((int)0xFFffFFff); + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); + if (dataSize >= VM_GLOBALMEMADDR / 2) + { + break; + } + + // bytes from same channels are grouped to continual data blocks, + // so we need to place them back to their interleaving positions + + for (int curChannel = 0; curChannel < channels; curChannel++) + { + byte PrevByte = 0; + for (int destPos = dataSize + curChannel; destPos < border; destPos += channels) + { + Mem[destPos] = (PrevByte = (byte)(PrevByte - Mem[srcPos++])); + } + } + } + break; + + case VMStandardFilters.VMSF_RGB: + { + // byte *SrcData=Mem,*DestData=SrcData+DataSize; + int dataSize = R[4], width = R[0] - 3, posR = R[1]; + int channels = 3; + int srcPos = 0; + int destDataPos = dataSize; + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); + if (dataSize >= VM_GLOBALMEMADDR / 2 || posR < 0) + { + break; + } + for (int curChannel = 0; curChannel < channels; curChannel++) + { + long prevByte = 0; + + for (int i = curChannel; i < dataSize; i += channels) + { + long predicted; + int upperPos = i - width; + if (upperPos >= 3) + { + int upperDataPos = destDataPos + upperPos; + int upperByte = Mem[upperDataPos] & 0xff; + int upperLeftByte = Mem[upperDataPos - 3] & 0xff; + predicted = prevByte + upperByte - upperLeftByte; + int pa = Math.Abs((int)(predicted - prevByte)); + int pb = Math.Abs((int)(predicted - upperByte)); + int pc = Math.Abs((int)(predicted - upperLeftByte)); + if (pa <= pb && pa <= pc) + { + predicted = prevByte; } else { - predicted = upperLeftByte; + if (pb <= pc) + { + predicted = upperByte; + } + else + { + predicted = upperLeftByte; + } } } - } - else - { - predicted = prevByte; - } + else + { + predicted = prevByte; + } - prevByte = (predicted - Mem[srcPos++] & 0xff) & 0xff; - Mem[destDataPos + i] = (byte)(prevByte & 0xff); + prevByte = (predicted - Mem[srcPos++] & 0xff) & 0xff; + Mem[destDataPos + i] = (byte)(prevByte & 0xff); + } + } + for (int i = posR, border = dataSize - 2; i < border; i += 3) + { + byte G = Mem[destDataPos + i + 1]; + Mem[destDataPos + i] = (byte)(Mem[destDataPos + i] + G); + Mem[destDataPos + i + 2] = (byte)(Mem[destDataPos + i + 2] + G); } } - for (int i = posR, border = dataSize - 2; i < border; i += 3) - { - byte G = Mem[destDataPos + i + 1]; - Mem[destDataPos + i] = (byte)(Mem[destDataPos + i] + G); - Mem[destDataPos + i + 2] = (byte)(Mem[destDataPos + i + 2] + G); - } - } break; case VMStandardFilters.VMSF_AUDIO: - { - int dataSize = R[4], channels = R[0]; - int srcPos = 0; - int destDataPos = dataSize; - - //byte *SrcData=Mem,*DestData=SrcData+DataSize; - SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); - if (dataSize >= VM_GLOBALMEMADDR / 2) { - break; - } - for (int curChannel = 0; curChannel < channels; curChannel++) - { - long prevByte = 0; - long prevDelta = 0; - long[] Dif = new long[7]; - int D1 = 0, D2 = 0, D3; - int K1 = 0, K2 = 0, K3 = 0; + int dataSize = R[4], channels = R[0]; + int srcPos = 0; + int destDataPos = dataSize; - for (int i = curChannel, byteCount = 0; i < dataSize; i += channels, byteCount++) + //byte *SrcData=Mem,*DestData=SrcData+DataSize; + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); + if (dataSize >= VM_GLOBALMEMADDR / 2) { - D3 = D2; - D2 = (int)(prevDelta - D1); - D1 = (int)prevDelta; + break; + } + for (int curChannel = 0; curChannel < channels; curChannel++) + { + long prevByte = 0; + long prevDelta = 0; + long[] Dif = new long[7]; + int D1 = 0, D2 = 0, D3; + int K1 = 0, K2 = 0, K3 = 0; - long predicted = 8 * prevByte + K1 * D1 + K2 * D2 + K3 * D3; - predicted = Utility.URShift(predicted, 3) & 0xff; - - long curByte = Mem[srcPos++]; - - predicted -= curByte; - Mem[destDataPos + i] = (byte)predicted; - prevDelta = (byte)(predicted - prevByte); - - //fix java byte - if (prevDelta >= 128) + for (int i = curChannel, byteCount = 0; i < dataSize; i += channels, byteCount++) { - prevDelta = 0 - (256 - prevDelta); - } - prevByte = predicted; + D3 = D2; + D2 = (int)(prevDelta - D1); + D1 = (int)prevDelta; - //fix java byte - if (curByte >= 128) - { - curByte = 0 - (256 - curByte); - } - int D = ((int)curByte) << 3; + long predicted = 8 * prevByte + K1 * D1 + K2 * D2 + K3 * D3; + predicted = Utility.URShift(predicted, 3) & 0xff; - Dif[0] += Math.Abs(D); - Dif[1] += Math.Abs(D - D1); - Dif[2] += Math.Abs(D + D1); - Dif[3] += Math.Abs(D - D2); - Dif[4] += Math.Abs(D + D2); - Dif[5] += Math.Abs(D - D3); - Dif[6] += Math.Abs(D + D3); + long curByte = Mem[srcPos++]; - if ((byteCount & 0x1f) == 0) - { - long minDif = Dif[0], numMinDif = 0; - Dif[0] = 0; - for (int j = 1; j < Dif.Length; j++) + predicted -= curByte; + Mem[destDataPos + i] = (byte)predicted; + prevDelta = (byte)(predicted - prevByte); + + //fix java byte + if (prevDelta >= 128) { - if (Dif[j] < minDif) - { - minDif = Dif[j]; - numMinDif = j; - } - Dif[j] = 0; + prevDelta = 0 - (256 - prevDelta); } - switch ((int)numMinDif) + prevByte = predicted; + + //fix java byte + if (curByte >= 128) { - case 1: - if (K1 >= -16) - { - K1--; - } - break; + curByte = 0 - (256 - curByte); + } + int D = ((int)curByte) << 3; - case 2: - if (K1 < 16) - { - K1++; - } - break; + Dif[0] += Math.Abs(D); + Dif[1] += Math.Abs(D - D1); + Dif[2] += Math.Abs(D + D1); + Dif[3] += Math.Abs(D - D2); + Dif[4] += Math.Abs(D + D2); + Dif[5] += Math.Abs(D - D3); + Dif[6] += Math.Abs(D + D3); - case 3: - if (K2 >= -16) + if ((byteCount & 0x1f) == 0) + { + long minDif = Dif[0], numMinDif = 0; + Dif[0] = 0; + for (int j = 1; j < Dif.Length; j++) + { + if (Dif[j] < minDif) { - K2--; + minDif = Dif[j]; + numMinDif = j; } - break; + Dif[j] = 0; + } + switch ((int)numMinDif) + { + case 1: + if (K1 >= -16) + { + K1--; + } + break; - case 4: - if (K2 < 16) - { - K2++; - } - break; + case 2: + if (K1 < 16) + { + K1++; + } + break; - case 5: - if (K3 >= -16) - { - K3--; - } - break; + case 3: + if (K2 >= -16) + { + K2--; + } + break; - case 6: - if (K3 < 16) - { - K3++; - } - break; + case 4: + if (K2 < 16) + { + K2++; + } + break; + + case 5: + if (K3 >= -16) + { + K3--; + } + break; + + case 6: + if (K3 < 16) + { + K3++; + } + break; + } } } } } - } break; case VMStandardFilters.VMSF_UPCASE: - { - int dataSize = R[4], srcPos = 0, destPos = dataSize; - if (dataSize >= VM_GLOBALMEMADDR / 2) { - break; - } - while (srcPos < dataSize) - { - byte curByte = Mem[srcPos++]; - if (curByte == 2 && (curByte = Mem[srcPos++]) != 2) + int dataSize = R[4], srcPos = 0, destPos = dataSize; + if (dataSize >= VM_GLOBALMEMADDR / 2) { - curByte = (byte)(curByte - 32); + break; } - Mem[destPos++] = curByte; + while (srcPos < dataSize) + { + byte curByte = Mem[srcPos++]; + if (curByte == 2 && (curByte = Mem[srcPos++]) != 2) + { + curByte = (byte)(curByte - 32); + } + Mem[destPos++] = curByte; + } + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x1c, destPos - dataSize); + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); } - SetValue(false, Mem, VM_GLOBALMEMADDR + 0x1c, destPos - dataSize); - SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); - } break; } } diff --git a/src/SharpCompress/Compressors/Xz/CheckType.cs b/src/SharpCompress/Compressors/Xz/CheckType.cs index b8184451..19c8019a 100644 --- a/src/SharpCompress/Compressors/Xz/CheckType.cs +++ b/src/SharpCompress/Compressors/Xz/CheckType.cs @@ -2,9 +2,9 @@ namespace SharpCompress.Compressors.Xz { public enum CheckType : byte { - NONE = 0x00, - CRC32 = 0x01, - CRC64 = 0x04, + NONE = 0x00, + CRC32 = 0x01, + CRC64 = 0x04, SHA256 = 0x0A } } \ No newline at end of file diff --git a/src/SharpCompress/Compressors/Xz/Crc64.cs b/src/SharpCompress/Compressors/Xz/Crc64.cs index 12435d67..340d0895 100644 --- a/src/SharpCompress/Compressors/Xz/Crc64.cs +++ b/src/SharpCompress/Compressors/Xz/Crc64.cs @@ -21,7 +21,7 @@ namespace SharpCompress.Compressors.Xz public static UInt64 Compute(UInt64 seed, byte[] buffer) { Table ??= CreateTable(Iso3309Polynomial); - + return CalculateHash(seed, Table, buffer, 0, buffer.Length); } diff --git a/src/SharpCompress/Compressors/Xz/XZBlock.cs b/src/SharpCompress/Compressors/Xz/XZBlock.cs index 5daa6ce5..6827093b 100644 --- a/src/SharpCompress/Compressors/Xz/XZBlock.cs +++ b/src/SharpCompress/Compressors/Xz/XZBlock.cs @@ -25,7 +25,7 @@ namespace SharpCompress.Compressors.Xz private bool _crcChecked; private ulong _bytesRead; - public XZBlock(Stream stream, CheckType checkType, int checkSize) + public XZBlock(Stream stream, CheckType checkType, int checkSize) : base(stream) { _checkType = checkType; diff --git a/src/SharpCompress/Compressors/Xz/XZStream.cs b/src/SharpCompress/Compressors/Xz/XZStream.cs index fb064fcf..49b5e801 100644 --- a/src/SharpCompress/Compressors/Xz/XZStream.cs +++ b/src/SharpCompress/Compressors/Xz/XZStream.cs @@ -98,7 +98,7 @@ namespace SharpCompress.Compressors.Xz NextBlock(); } - for (;;) + for (; ; ) { try { diff --git a/src/SharpCompress/Crypto/Crc32Stream.cs b/src/SharpCompress/Crypto/Crc32Stream.cs index 0423b49e..fe3cd00c 100644 --- a/src/SharpCompress/Crypto/Crc32Stream.cs +++ b/src/SharpCompress/Crypto/Crc32Stream.cs @@ -11,7 +11,7 @@ namespace SharpCompress.Crypto public const uint DefaultSeed = 0xffffffffu; private static uint[] defaultTable; - + private readonly uint[] table; private uint hash; diff --git a/src/SharpCompress/IO/MarkingBinaryReader.cs b/src/SharpCompress/IO/MarkingBinaryReader.cs index 789de070..5b3e7ffe 100644 --- a/src/SharpCompress/IO/MarkingBinaryReader.cs +++ b/src/SharpCompress/IO/MarkingBinaryReader.cs @@ -132,25 +132,30 @@ namespace SharpCompress.IO // and highest bit in every byte is the continuation flag. If highest bit is 0, this is the last byte in sequence. // So first byte contains 7 least significant bits of integer and continuation flag. Second byte, if present, // contains next 7 bits and so on. - public ulong ReadRarVInt(int maxBytes = 10) { + public ulong ReadRarVInt(int maxBytes = 10) + { // hopefully this gets inlined return DoReadRarVInt((maxBytes - 1) * 7); } - private ulong DoReadRarVInt(int maxShift) { + private ulong DoReadRarVInt(int maxShift) + { int shift = 0; ulong result = 0; - do { + do + { byte b0 = ReadByte(); uint b1 = ((uint)b0) & 0x7f; ulong n = b1; ulong shifted = n << shift; - if (n != shifted >> shift) { + if (n != shifted >> shift) + { // overflow break; } result |= shifted; - if (b0 == b1) { + if (b0 == b1) + { return result; } shift += 7; @@ -159,35 +164,42 @@ namespace SharpCompress.IO throw new FormatException("malformed vint"); } - public uint ReadRarVIntUInt32(int maxBytes = 5) { + public uint ReadRarVIntUInt32(int maxBytes = 5) + { // hopefully this gets inlined return DoReadRarVIntUInt32((maxBytes - 1) * 7); } - public ushort ReadRarVIntUInt16(int maxBytes = 3) { + public ushort ReadRarVIntUInt16(int maxBytes = 3) + { // hopefully this gets inlined return checked((ushort)DoReadRarVIntUInt32((maxBytes - 1) * 7)); } - public byte ReadRarVIntByte(int maxBytes = 2) { + public byte ReadRarVIntByte(int maxBytes = 2) + { // hopefully this gets inlined return checked((byte)DoReadRarVIntUInt32((maxBytes - 1) * 7)); } - private uint DoReadRarVIntUInt32(int maxShift) { + private uint DoReadRarVIntUInt32(int maxShift) + { int shift = 0; uint result = 0; - do { + do + { byte b0 = ReadByte(); uint b1 = ((uint)b0) & 0x7f; uint n = b1; uint shifted = n << shift; - if (n != shifted >> shift) { + if (n != shifted >> shift) + { // overflow break; } result |= shifted; - if (b0 == b1) { + if (b0 == b1) + { return result; } shift += 7; diff --git a/src/SharpCompress/IO/RewindableStream.cs b/src/SharpCompress/IO/RewindableStream.cs index 97bd0f4d..998e1834 100644 --- a/src/SharpCompress/IO/RewindableStream.cs +++ b/src/SharpCompress/IO/RewindableStream.cs @@ -46,7 +46,7 @@ namespace SharpCompress.IO } else { - + bufferStream.TransferTo(buffer); //create new memorystream to allow proper resizing as memorystream could be a user provided buffer //https://github.com/adamhathcock/sharpcompress/issues/306 diff --git a/src/SharpCompress/Lazy.cs b/src/SharpCompress/Lazy.cs index 6d8e84c5..eab72849 100644 --- a/src/SharpCompress/Lazy.cs +++ b/src/SharpCompress/Lazy.cs @@ -9,7 +9,7 @@ namespace SharpCompress private readonly Func _lazyFunc; private bool _evaluated; private T _value; - + public Lazy(Func lazyFunc) { _lazyFunc = lazyFunc; diff --git a/src/SharpCompress/Readers/AbstractReader.cs b/src/SharpCompress/Readers/AbstractReader.cs index a4af4827..dfd012a3 100644 --- a/src/SharpCompress/Readers/AbstractReader.cs +++ b/src/SharpCompress/Readers/AbstractReader.cs @@ -16,7 +16,7 @@ namespace SharpCompress.Readers private bool completed; private IEnumerator? entriesForCurrentReadStream; private bool wroteCurrentEntry; - + public event EventHandler>? EntryExtractionProgress; public event EventHandler? CompressedBytesRead; @@ -131,8 +131,8 @@ namespace SharpCompress.Readers private void Skip() { - if (ArchiveType != ArchiveType.Rar - && !Entry.IsSolid + if (ArchiveType != ArchiveType.Rar + && !Entry.IsSolid && Entry.CompressedSize > 0) { //not solid and has a known compressed size then we can skip raw bytes. diff --git a/src/SharpCompress/Readers/IReaderExtensions.cs b/src/SharpCompress/Readers/IReaderExtensions.cs index d58bcf7d..502fc8ad 100644 --- a/src/SharpCompress/Readers/IReaderExtensions.cs +++ b/src/SharpCompress/Readers/IReaderExtensions.cs @@ -46,7 +46,7 @@ namespace SharpCompress.Readers /// /// Extract to specific file /// - public static void WriteEntryToFile(this IReader reader, + public static void WriteEntryToFile(this IReader reader, string destinationFileName, ExtractionOptions? options = null) { diff --git a/src/SharpCompress/Readers/Rar/MultiVolumeRarReader.cs b/src/SharpCompress/Readers/Rar/MultiVolumeRarReader.cs index 0bcfe9a1..6de11a24 100644 --- a/src/SharpCompress/Readers/Rar/MultiVolumeRarReader.cs +++ b/src/SharpCompress/Readers/Rar/MultiVolumeRarReader.cs @@ -35,7 +35,8 @@ namespace SharpCompress.Readers.Rar internal override bool NextEntryForCurrentStream() { - if (!base.NextEntryForCurrentStream()) { + if (!base.NextEntryForCurrentStream()) + { // if we're got another stream to try to process then do so return streams.MoveNext() && LoadStreamForReading(streams.Current); } diff --git a/src/SharpCompress/Readers/Rar/SingleVolumeRarReader.cs b/src/SharpCompress/Readers/Rar/SingleVolumeRarReader.cs index b8d64f8d..4d3cf411 100644 --- a/src/SharpCompress/Readers/Rar/SingleVolumeRarReader.cs +++ b/src/SharpCompress/Readers/Rar/SingleVolumeRarReader.cs @@ -16,7 +16,8 @@ namespace SharpCompress.Readers.Rar internal override void ValidateArchive(RarVolume archive) { - if (archive.IsMultiVolume) { + if (archive.IsMultiVolume) + { var msg = "Streamed archive is a Multi-volume archive. Use different RarReader method to extract."; throw new MultiVolumeExtractionException(msg); } diff --git a/src/SharpCompress/Readers/ReaderFactory.cs b/src/SharpCompress/Readers/ReaderFactory.cs index 85f99310..1384264f 100644 --- a/src/SharpCompress/Readers/ReaderFactory.cs +++ b/src/SharpCompress/Readers/ReaderFactory.cs @@ -30,9 +30,9 @@ namespace SharpCompress.Readers { stream.CheckNotNull(nameof(stream)); options = options ?? new ReaderOptions() - { - LeaveStreamOpen = false - }; + { + LeaveStreamOpen = false + }; RewindableStream rewindableStream = new RewindableStream(stream); rewindableStream.StartRecording(); if (ZipArchive.IsZipFile(rewindableStream, options.Password)) diff --git a/src/SharpCompress/Readers/Tar/TarReader.cs b/src/SharpCompress/Readers/Tar/TarReader.cs index acb9fc9b..a2b7ecc7 100644 --- a/src/SharpCompress/Readers/Tar/TarReader.cs +++ b/src/SharpCompress/Readers/Tar/TarReader.cs @@ -33,29 +33,29 @@ namespace SharpCompress.Readers.Tar switch (compressionType) { case CompressionType.BZip2: - { - return new BZip2Stream(stream, CompressionMode.Decompress, false); - } + { + return new BZip2Stream(stream, CompressionMode.Decompress, false); + } case CompressionType.GZip: - { - return new GZipStream(stream, CompressionMode.Decompress); - } + { + return new GZipStream(stream, CompressionMode.Decompress); + } case CompressionType.LZip: - { - return new LZipStream(stream, CompressionMode.Decompress); - } + { + return new LZipStream(stream, CompressionMode.Decompress); + } case CompressionType.Xz: - { - return new XZStream(stream); - } + { + return new XZStream(stream); + } case CompressionType.None: - { - return stream; - } + { + return stream; + } default: - { - throw new NotSupportedException("Invalid compression type: " + compressionType); - } + { + throw new NotSupportedException("Invalid compression type: " + compressionType); + } } } diff --git a/src/SharpCompress/Writers/GZip/GZipWriter.cs b/src/SharpCompress/Writers/GZip/GZipWriter.cs index bcbb087a..1147b686 100644 --- a/src/SharpCompress/Writers/GZip/GZipWriter.cs +++ b/src/SharpCompress/Writers/GZip/GZipWriter.cs @@ -18,7 +18,7 @@ namespace SharpCompress.Writers.GZip { destination = new NonDisposingStream(destination); } - InitalizeStream(new GZipStream(destination, CompressionMode.Compress, + InitalizeStream(new GZipStream(destination, CompressionMode.Compress, options?.CompressionLevel ?? CompressionLevel.Default, WriterOptions.ArchiveEncoding.GetEncoding())); } diff --git a/src/SharpCompress/Writers/GZip/GZipWriterOptions.cs b/src/SharpCompress/Writers/GZip/GZipWriterOptions.cs index 38c3a723..b6966e16 100644 --- a/src/SharpCompress/Writers/GZip/GZipWriterOptions.cs +++ b/src/SharpCompress/Writers/GZip/GZipWriterOptions.cs @@ -9,7 +9,7 @@ namespace SharpCompress.Writers.GZip : base(CompressionType.GZip) { } - + internal GZipWriterOptions(WriterOptions options) : base(options.CompressionType) { @@ -22,7 +22,7 @@ namespace SharpCompress.Writers.GZip CompressionLevel = writerOptions.CompressionLevel; } } - + public CompressionLevel CompressionLevel { get; set; } = CompressionLevel.Default; } } \ No newline at end of file diff --git a/src/SharpCompress/Writers/Tar/TarWriter.cs b/src/SharpCompress/Writers/Tar/TarWriter.cs index 89e9ba75..ae7105a6 100644 --- a/src/SharpCompress/Writers/Tar/TarWriter.cs +++ b/src/SharpCompress/Writers/Tar/TarWriter.cs @@ -32,24 +32,24 @@ namespace SharpCompress.Writers.Tar case CompressionType.None: break; case CompressionType.BZip2: - { - destination = new BZip2Stream(destination, CompressionMode.Compress, false); - } + { + destination = new BZip2Stream(destination, CompressionMode.Compress, false); + } break; case CompressionType.GZip: - { - destination = new GZipStream(destination, CompressionMode.Compress); - } + { + destination = new GZipStream(destination, CompressionMode.Compress); + } break; case CompressionType.LZip: - { - destination = new LZipStream(destination, CompressionMode.Compress); - } + { + destination = new LZipStream(destination, CompressionMode.Compress); + } break; default: - { - throw new InvalidFormatException("Tar does not support compression: " + options.CompressionType); - } + { + throw new InvalidFormatException("Tar does not support compression: " + options.CompressionType); + } } InitalizeStream(destination); } @@ -106,22 +106,23 @@ namespace SharpCompress.Writers.Tar { if (isDisposing) { - if (finalizeArchiveOnClose) { + if (finalizeArchiveOnClose) + { PadTo512(0, true); PadTo512(0, true); } switch (OutputStream) { case BZip2Stream b: - { - b.Finish(); - break; - } + { + b.Finish(); + break; + } case LZipStream l: - { - l.Finish(); - break; - } + { + l.Finish(); + break; + } } } base.Dispose(isDisposing); diff --git a/src/SharpCompress/Writers/WriterFactory.cs b/src/SharpCompress/Writers/WriterFactory.cs index 1f1c01a5..fcb0fd41 100644 --- a/src/SharpCompress/Writers/WriterFactory.cs +++ b/src/SharpCompress/Writers/WriterFactory.cs @@ -14,25 +14,25 @@ namespace SharpCompress.Writers switch (archiveType) { case ArchiveType.GZip: - { - if (writerOptions.CompressionType != CompressionType.GZip) { - throw new InvalidFormatException("GZip archives only support GZip compression type."); + if (writerOptions.CompressionType != CompressionType.GZip) + { + throw new InvalidFormatException("GZip archives only support GZip compression type."); + } + return new GZipWriter(stream, new GZipWriterOptions(writerOptions)); } - return new GZipWriter(stream, new GZipWriterOptions(writerOptions)); - } case ArchiveType.Zip: - { - return new ZipWriter(stream, new ZipWriterOptions(writerOptions)); - } + { + return new ZipWriter(stream, new ZipWriterOptions(writerOptions)); + } case ArchiveType.Tar: - { - return new TarWriter(stream, new TarWriterOptions(writerOptions)); - } + { + return new TarWriter(stream, new TarWriterOptions(writerOptions)); + } default: - { - throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); - } + { + throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); + } } } } diff --git a/tests/SharpCompress.Test/ADCTest.cs b/tests/SharpCompress.Test/ADCTest.cs index e5151bec..26ea2699 100644 --- a/tests/SharpCompress.Test/ADCTest.cs +++ b/tests/SharpCompress.Test/ADCTest.cs @@ -144,7 +144,7 @@ namespace SharpCompress.Test var crc32a = crcStream.Crc; var crc32b = Crc32Stream.Compute(memory.ToArray()); - + Assert.Equal(crc32, crc32a); Assert.Equal(crc32, crc32b); } diff --git a/tests/SharpCompress.Test/Mocks/FlushOnDisposeStream.cs b/tests/SharpCompress.Test/Mocks/FlushOnDisposeStream.cs index 6e0b4131..22e84ef9 100644 --- a/tests/SharpCompress.Test/Mocks/FlushOnDisposeStream.cs +++ b/tests/SharpCompress.Test/Mocks/FlushOnDisposeStream.cs @@ -11,7 +11,8 @@ namespace SharpCompress.Test.Mocks { private Stream inner; - public FlushOnDisposeStream(Stream innerStream) { + public FlushOnDisposeStream(Stream innerStream) + { this.inner = innerStream; } @@ -25,28 +26,35 @@ namespace SharpCompress.Test.Mocks public override long Position { get => this.inner.Position; set => this.inner.Position = value; } - public override void Flush() { + public override void Flush() + { throw new NotImplementedException(); } - public override int Read(byte[] buffer, int offset, int count) { + public override int Read(byte[] buffer, int offset, int count) + { return this.inner.Read(buffer, offset, count); } - public override long Seek(long offset, SeekOrigin origin) { + public override long Seek(long offset, SeekOrigin origin) + { throw new NotImplementedException(); } - public override void SetLength(long value) { + public override void SetLength(long value) + { throw new NotImplementedException(); } - public override void Write(byte[] buffer, int offset, int count) { + public override void Write(byte[] buffer, int offset, int count) + { throw new NotImplementedException(); } - protected override void Dispose(bool disposing) { - if(disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { this.inner.Flush(); this.inner.Close(); } diff --git a/tests/SharpCompress.Test/Rar/RarArchiveTests.cs b/tests/SharpCompress.Test/Rar/RarArchiveTests.cs index 71917bd9..7133e8e8 100644 --- a/tests/SharpCompress.Test/Rar/RarArchiveTests.cs +++ b/tests/SharpCompress.Test/Rar/RarArchiveTests.cs @@ -123,7 +123,8 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_test_invalid_exttime_ArchiveStreamRead() { + public void Rar_test_invalid_exttime_ArchiveStreamRead() + { DoRar_test_invalid_exttime_ArchiveStreamRead("Rar.test_invalid_exttime.rar"); } @@ -170,12 +171,14 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_IsSolidArchiveCheck() { + public void Rar_IsSolidArchiveCheck() + { DoRar_IsSolidArchiveCheck("Rar.rar"); } [Fact] - public void Rar5_IsSolidArchiveCheck() { + public void Rar5_IsSolidArchiveCheck() + { DoRar_IsSolidArchiveCheck("Rar5.rar"); } @@ -225,8 +228,9 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_Multi_ArchiveStreamRead() { - DoRar_Multi_ArchiveStreamRead(new string[] { + public void Rar_Multi_ArchiveStreamRead() + { + DoRar_Multi_ArchiveStreamRead(new string[] { "Rar.multi.part01.rar", "Rar.multi.part02.rar", "Rar.multi.part03.rar", @@ -236,8 +240,9 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar5_Multi_ArchiveStreamRead() { - DoRar_Multi_ArchiveStreamRead(new string[] { + public void Rar5_Multi_ArchiveStreamRead() + { + DoRar_Multi_ArchiveStreamRead(new string[] { "Rar5.multi.part01.rar", "Rar5.multi.part02.rar", "Rar5.multi.part03.rar", @@ -300,12 +305,14 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_ArchiveFileRead_HasDirectories() { + public void Rar_ArchiveFileRead_HasDirectories() + { DoRar_ArchiveFileRead_HasDirectories("Rar.rar"); } [Fact] - public void Rar5_ArchiveFileRead_HasDirectories() { + public void Rar5_ArchiveFileRead_HasDirectories() + { DoRar_ArchiveFileRead_HasDirectories("Rar5.rar"); } @@ -366,12 +373,14 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_IsFirstVolume_True() { + public void Rar_IsFirstVolume_True() + { DoRar_IsFirstVolume_True("Rar.multi.part01.rar"); } [Fact] - public void Rar5_IsFirstVolume_True() { + public void Rar5_IsFirstVolume_True() + { DoRar_IsFirstVolume_True("Rar5.multi.part01.rar"); } @@ -385,12 +394,14 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_IsFirstVolume_False() { + public void Rar_IsFirstVolume_False() + { DoRar_IsFirstVolume_False("Rar.multi.part03.rar"); } [Fact] - public void Rar5_IsFirstVolume_False() { + public void Rar5_IsFirstVolume_False() + { DoRar_IsFirstVolume_False("Rar5.multi.part03.rar"); } diff --git a/tests/SharpCompress.Test/Rar/RarHeaderFactoryTest.cs b/tests/SharpCompress.Test/Rar/RarHeaderFactoryTest.cs index 0c6e66a6..a9c4c798 100644 --- a/tests/SharpCompress.Test/Rar/RarHeaderFactoryTest.cs +++ b/tests/SharpCompress.Test/Rar/RarHeaderFactoryTest.cs @@ -16,7 +16,7 @@ namespace SharpCompress.Test.Rar public RarHeaderFactoryTest() { rarHeaderFactory = new RarHeaderFactory( - StreamingMode.Seekable, + StreamingMode.Seekable, new ReaderOptions { LeaveStreamOpen = true }); } diff --git a/tests/SharpCompress.Test/Rar/RarReaderTests.cs b/tests/SharpCompress.Test/Rar/RarReaderTests.cs index caf2caf6..6affbc7b 100644 --- a/tests/SharpCompress.Test/Rar/RarReaderTests.cs +++ b/tests/SharpCompress.Test/Rar/RarReaderTests.cs @@ -10,8 +10,9 @@ namespace SharpCompress.Test.Rar public class RarReaderTests : ReaderTests { [Fact] - public void Rar_Multi_Reader() { - DoRar_Multi_Reader(new string[] { + public void Rar_Multi_Reader() + { + DoRar_Multi_Reader(new string[] { "Rar.multi.part01.rar", "Rar.multi.part02.rar", "Rar.multi.part03.rar", @@ -21,8 +22,9 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar5_Multi_Reader() { - DoRar_Multi_Reader(new string[] { + public void Rar5_Multi_Reader() + { + DoRar_Multi_Reader(new string[] { "Rar5.multi.part01.rar", "Rar5.multi.part02.rar", "Rar5.multi.part03.rar", @@ -49,8 +51,9 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_Multi_Reader_Encrypted() { - DoRar_Multi_Reader_Encrypted(new string[] { + public void Rar_Multi_Reader_Encrypted() + { + DoRar_Multi_Reader_Encrypted(new string[] { "Rar.EncryptedParts.part01.rar", "Rar.EncryptedParts.part02.rar", "Rar.EncryptedParts.part03.rar", @@ -85,8 +88,9 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_Multi_Reader_Delete_Files() { - DoRar_Multi_Reader_Delete_Files(new string[] { + public void Rar_Multi_Reader_Delete_Files() + { + DoRar_Multi_Reader_Delete_Files(new string[] { "Rar.multi.part01.rar", "Rar.multi.part02.rar", "Rar.multi.part03.rar", @@ -96,8 +100,9 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar5_Multi_Reader_Delete_Files() { - DoRar_Multi_Reader_Delete_Files(new string[] { + public void Rar5_Multi_Reader_Delete_Files() + { + DoRar_Multi_Reader_Delete_Files(new string[] { "Rar5.multi.part01.rar", "Rar5.multi.part02.rar", "Rar5.multi.part03.rar", @@ -203,12 +208,14 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_Entry_Stream() { + public void Rar_Entry_Stream() + { DoRar_Entry_Stream("Rar.rar"); } [Fact] - public void Rar5_Entry_Stream() { + public void Rar5_Entry_Stream() + { DoRar_Entry_Stream("Rar5.rar"); } @@ -302,12 +309,14 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_Solid_Skip_Reader() { + public void Rar_Solid_Skip_Reader() + { DoRar_Solid_Skip_Reader("Rar.solid.rar"); } [Fact] - public void Rar5_Solid_Skip_Reader() { + public void Rar5_Solid_Skip_Reader() + { DoRar_Solid_Skip_Reader("Rar5.solid.rar"); } @@ -335,12 +344,14 @@ namespace SharpCompress.Test.Rar } [Fact] - public void Rar_Reader_Skip() { + public void Rar_Reader_Skip() + { DoRar_Reader_Skip("Rar.rar"); } [Fact] - public void Rar5_Reader_Skip() { + public void Rar5_Reader_Skip() + { DoRar_Reader_Skip("Rar5.rar"); } diff --git a/tests/SharpCompress.Test/SevenZip/SevenZipArchiveTests.cs b/tests/SharpCompress.Test/SevenZip/SevenZipArchiveTests.cs index db6c07f0..f144ab84 100644 --- a/tests/SharpCompress.Test/SevenZip/SevenZipArchiveTests.cs +++ b/tests/SharpCompress.Test/SevenZip/SevenZipArchiveTests.cs @@ -22,13 +22,13 @@ namespace SharpCompress.Test.SevenZip [Fact] public void SevenZipArchive_LZMAAES_StreamRead() { - ArchiveStreamRead("7Zip.LZMA.Aes.7z", new ReaderOptions() {Password = "testpassword"}); + ArchiveStreamRead("7Zip.LZMA.Aes.7z", new ReaderOptions() { Password = "testpassword" }); } [Fact] public void SevenZipArchive_LZMAAES_PathRead() { - ArchiveFileRead("7Zip.LZMA.Aes.7z", new ReaderOptions() {Password = "testpassword"}); + ArchiveFileRead("7Zip.LZMA.Aes.7z", new ReaderOptions() { Password = "testpassword" }); } [Fact] public void SevenZipArchive_PPMd_StreamRead() @@ -63,13 +63,13 @@ namespace SharpCompress.Test.SevenZip [Fact] public void SevenZipArchive_LZMA2AES_StreamRead() { - ArchiveStreamRead("7Zip.LZMA2.Aes.7z", new ReaderOptions {Password = "testpassword"}); + ArchiveStreamRead("7Zip.LZMA2.Aes.7z", new ReaderOptions { Password = "testpassword" }); } [Fact] public void SevenZipArchive_LZMA2AES_PathRead() { - ArchiveFileRead("7Zip.LZMA2.Aes.7z", new ReaderOptions {Password = "testpassword"}); + ArchiveFileRead("7Zip.LZMA2.Aes.7z", new ReaderOptions { Password = "testpassword" }); } [Fact] diff --git a/tests/SharpCompress.Test/Tar/TarReaderTests.cs b/tests/SharpCompress.Test/Tar/TarReaderTests.cs index 1a4fd803..17213c21 100644 --- a/tests/SharpCompress.Test/Tar/TarReaderTests.cs +++ b/tests/SharpCompress.Test/Tar/TarReaderTests.cs @@ -118,7 +118,7 @@ namespace SharpCompress.Test.Tar { filePaths.Add(reader.Entry.Key); } - } + } } Assert.Equal(3, filePaths.Count); @@ -165,18 +165,21 @@ namespace SharpCompress.Test.Tar public void Tar_With_TarGz_With_Flushed_EntryStream() { string archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.ContainsTarGz.tar"); - using(Stream stream = File.OpenRead(archiveFullPath)) - using(IReader reader = ReaderFactory.Open(stream)) + using (Stream stream = File.OpenRead(archiveFullPath)) + using (IReader reader = ReaderFactory.Open(stream)) { Assert.True(reader.MoveToNextEntry()); Assert.Equal("inner.tar.gz", reader.Entry.Key); - using(var entryStream = reader.OpenEntryStream()) { + using (var entryStream = reader.OpenEntryStream()) + { - using(FlushOnDisposeStream flushingStream = new FlushOnDisposeStream(entryStream)) { + using (FlushOnDisposeStream flushingStream = new FlushOnDisposeStream(entryStream)) + { // Extract inner.tar.gz - using(var innerReader = ReaderFactory.Open(flushingStream)) { + using (var innerReader = ReaderFactory.Open(flushingStream)) + { Assert.True(innerReader.MoveToNextEntry()); Assert.Equal("test", innerReader.Entry.Key); diff --git a/tests/SharpCompress.Test/Tar/TarWriterTests.cs b/tests/SharpCompress.Test/Tar/TarWriterTests.cs index d2fb9646..e38e61f9 100644 --- a/tests/SharpCompress.Test/Tar/TarWriterTests.cs +++ b/tests/SharpCompress.Test/Tar/TarWriterTests.cs @@ -44,8 +44,10 @@ namespace SharpCompress.Test.Tar public void Tar_Finalize_Archive(bool finalizeArchive) { using (MemoryStream stream = new MemoryStream()) - using (Stream content = File.OpenRead(Path.Combine(ORIGINAL_FILES_PATH, "jpg", "test.jpg"))) { - using (TarWriter writer = new TarWriter(stream, new TarWriterOptions(CompressionType.None, finalizeArchive))) { + using (Stream content = File.OpenRead(Path.Combine(ORIGINAL_FILES_PATH, "jpg", "test.jpg"))) + { + using (TarWriter writer = new TarWriter(stream, new TarWriterOptions(CompressionType.None, finalizeArchive))) + { writer.Write("doesn't matter", content, null); } diff --git a/tests/SharpCompress.Test/TestBase.cs b/tests/SharpCompress.Test/TestBase.cs index 3f310956..0c1db9d0 100644 --- a/tests/SharpCompress.Test/TestBase.cs +++ b/tests/SharpCompress.Test/TestBase.cs @@ -188,10 +188,11 @@ namespace SharpCompress.Test Assert.Equal(fi1.Attributes, fi2.Attributes); } - protected void CompareArchivesByPath(string file1, string file2, Encoding encoding = null) { + protected void CompareArchivesByPath(string file1, string file2, Encoding encoding = null) + { ReaderOptions readerOptions = new ReaderOptions { LeaveStreamOpen = false }; readerOptions.ArchiveEncoding.Default = encoding ?? Encoding.Default; - + //don't compare the order. OS X reads files from the file system in a different order therefore makes the archive ordering different var archive1Entries = new List(); var archive2Entries = new List(); @@ -213,6 +214,6 @@ namespace SharpCompress.Test Assert.Equal(archive1Entries[i], archive2Entries[i]); } } - + } } diff --git a/tests/SharpCompress.Test/WriterTests.cs b/tests/SharpCompress.Test/WriterTests.cs index b4e2d738..2d99325d 100644 --- a/tests/SharpCompress.Test/WriterTests.cs +++ b/tests/SharpCompress.Test/WriterTests.cs @@ -18,14 +18,15 @@ namespace SharpCompress.Test protected void Write(CompressionType compressionType, string archive, string archiveToVerifyAgainst, Encoding encoding = null) { - using (Stream stream = File.OpenWrite(Path.Combine(SCRATCH2_FILES_PATH, archive))) { - WriterOptions writerOptions = new WriterOptions(compressionType) + using (Stream stream = File.OpenWrite(Path.Combine(SCRATCH2_FILES_PATH, archive))) + { + WriterOptions writerOptions = new WriterOptions(compressionType) { LeaveStreamOpen = true, }; writerOptions.ArchiveEncoding.Default = encoding ?? Encoding.Default; - + using (var writer = WriterFactory.Open(stream, type, writerOptions)) { writer.WriteAll(ORIGINAL_FILES_PATH, "*", SearchOption.AllDirectories); @@ -34,12 +35,12 @@ namespace SharpCompress.Test CompareArchivesByPath(Path.Combine(SCRATCH2_FILES_PATH, archive), Path.Combine(TEST_ARCHIVES_PATH, archiveToVerifyAgainst)); - using (Stream stream = File.OpenRead(Path.Combine(SCRATCH2_FILES_PATH, archive))) + using (Stream stream = File.OpenRead(Path.Combine(SCRATCH2_FILES_PATH, archive))) { ReaderOptions readerOptions = new ReaderOptions(); readerOptions.ArchiveEncoding.Default = encoding ?? Encoding.Default; - + using (var reader = ReaderFactory.Open(new NonDisposingStream(stream), readerOptions)) { reader.WriteAllToDirectory(SCRATCH_FILES_PATH, new ExtractionOptions() diff --git a/tests/SharpCompress.Test/Xz/Filters/Lzma2Tests.cs b/tests/SharpCompress.Test/Xz/Filters/Lzma2Tests.cs index c9594c1b..1f527452 100644 --- a/tests/SharpCompress.Test/Xz/Filters/Lzma2Tests.cs +++ b/tests/SharpCompress.Test/Xz/Filters/Lzma2Tests.cs @@ -8,7 +8,7 @@ namespace SharpCompress.Test.Xz.Filters public class Lzma2Tests : XZTestsBase { private readonly Lzma2Filter filter; - + public Lzma2Tests() { filter = new Lzma2Filter(); diff --git a/tests/SharpCompress.Test/Xz/XZHeaderTests.cs b/tests/SharpCompress.Test/Xz/XZHeaderTests.cs index 78fd2ed6..1fa2a8b5 100644 --- a/tests/SharpCompress.Test/Xz/XZHeaderTests.cs +++ b/tests/SharpCompress.Test/Xz/XZHeaderTests.cs @@ -35,7 +35,8 @@ namespace SharpCompress.Test.Xz } [Fact] - public void BadVersionIfCrcOkButStreamFlagUnknown() { + public void BadVersionIfCrcOkButStreamFlagUnknown() + { var bytes = Compressed.Clone() as byte[]; byte[] streamFlags = { 0x00, 0xF4 }; byte[] crc = Crc32.Compute(streamFlags).ToLittleEndianBytes(); @@ -48,7 +49,7 @@ namespace SharpCompress.Test.Xz var ex = Assert.Throws(() => { header.Process(); }); Assert.Equal("Unknown XZ Stream Version", ex.Message); } -} + } [Fact] public void ProcessesBlockCheckType() diff --git a/tests/SharpCompress.Test/Xz/XZIndexTests.cs b/tests/SharpCompress.Test/Xz/XZIndexTests.cs index 6f41945f..543f984e 100644 --- a/tests/SharpCompress.Test/Xz/XZIndexTests.cs +++ b/tests/SharpCompress.Test/Xz/XZIndexTests.cs @@ -39,7 +39,7 @@ namespace SharpCompress.Test.Xz { BinaryReader br = new BinaryReader(badStream); var index = new XZIndex(br, false); - Assert.Throws( () => index.Process()); + Assert.Throws(() => index.Process()); } } diff --git a/tests/SharpCompress.Test/Xz/XZTestsBase.cs b/tests/SharpCompress.Test/Xz/XZTestsBase.cs index a01657c5..46a13a8f 100644 --- a/tests/SharpCompress.Test/Xz/XZTestsBase.cs +++ b/tests/SharpCompress.Test/Xz/XZTestsBase.cs @@ -38,7 +38,7 @@ namespace SharpCompress.Test.Xz protected static string OriginalEmpty { get; } = string.Empty; - protected Stream CompressedStream { get; } = new MemoryStream(Compressed); + protected Stream CompressedStream { get; } = new MemoryStream(Compressed); protected static byte[] Compressed { get; } = new byte[] { 0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00, 0x00, 0x04, 0xe6, 0xd6, 0xb4, 0x46, 0x02, 0x00, 0x21, 0x01, diff --git a/tests/SharpCompress.Test/Zip/Zip64Tests.cs b/tests/SharpCompress.Test/Zip/Zip64Tests.cs index a24fedc2..c0395684 100644 --- a/tests/SharpCompress.Test/Zip/Zip64Tests.cs +++ b/tests/SharpCompress.Test/Zip/Zip64Tests.cs @@ -14,12 +14,12 @@ namespace SharpCompress.Test.Zip { public class Zip64Tests : WriterTests { - public Zip64Tests() + public Zip64Tests() : base(ArchiveType.Zip) { - } + } - // 4GiB + 1 + // 4GiB + 1 private const long FOUR_GB_LIMIT = ((long)uint.MaxValue) + 1; [Trait("format", "zip64")] @@ -31,9 +31,9 @@ namespace SharpCompress.Test.Zip [Trait("format", "zip64")] public void Zip64_Two_Large_Files() - { - // One single file, requires zip64 - RunSingleTest(2, FOUR_GB_LIMIT, set_zip64: true, forward_only: false); + { + // One single file, requires zip64 + RunSingleTest(2, FOUR_GB_LIMIT, set_zip64: true, forward_only: false); } [Trait("format", "zip64")] @@ -96,13 +96,13 @@ namespace SharpCompress.Test.Zip } catch (NotSupportedException) { - } + } } public void RunSingleTest(long files, long filesize, bool set_zip64, bool forward_only, long write_chunk_size = 1024 * 1024, string filename = "zip64-test.zip") { filename = Path.Combine(SCRATCH2_FILES_PATH, filename); - + if (File.Exists(filename)) { File.Delete(filename); @@ -147,7 +147,7 @@ namespace SharpCompress.Test.Zip var eo = new ZipWriterEntryOptions() { DeflateCompressionLevel = Compressors.Deflate.CompressionLevel.None }; using (var zip = File.OpenWrite(filename)) - using(var st = forward_only ? (Stream)new ForwardOnlyStream(zip) : zip) + using (var st = forward_only ? (Stream)new ForwardOnlyStream(zip) : zip) using (var zipWriter = (ZipWriter)WriterFactory.Open(st, ArchiveType.Zip, opts)) { @@ -171,7 +171,7 @@ namespace SharpCompress.Test.Zip { long count = 0; long size = 0; - Common.Zip.ZipEntry prev = null; + Common.Zip.ZipEntry prev = null; using (var fs = File.OpenRead(filename)) using (var rd = ZipReader.Open(fs, new ReaderOptions() { LookForHeader = false })) { diff --git a/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs b/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs index f38c8c8e..4ecfb07b 100644 --- a/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs +++ b/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs @@ -165,7 +165,7 @@ namespace SharpCompress.Test.Zip WriterOptions writerOptions = new ZipWriterOptions(CompressionType.Deflate); writerOptions.ArchiveEncoding.Default = Encoding.GetEncoding(866); - + archive.SaveTo(scratchPath, writerOptions); } CompareArchivesByPath(modified, scratchPath, Encoding.GetEncoding(866)); @@ -185,7 +185,7 @@ namespace SharpCompress.Test.Zip WriterOptions writerOptions = new ZipWriterOptions(CompressionType.Deflate); writerOptions.ArchiveEncoding.Default = Encoding.GetEncoding(866); - + archive.SaveTo(scratchPath, writerOptions); } CompareArchivesByPath(modified, scratchPath, Encoding.GetEncoding(866)); @@ -280,10 +280,10 @@ namespace SharpCompress.Test.Zip using (var archive = ZipArchive.Create()) { archive.AddAllFromDirectory(SCRATCH_FILES_PATH); - + WriterOptions writerOptions = new ZipWriterOptions(CompressionType.Deflate); writerOptions.ArchiveEncoding.Default = Encoding.GetEncoding(866); - + archive.SaveTo(scratchPath, writerOptions); } CompareArchivesByPath(unmodified, scratchPath, Encoding.GetEncoding(866)); @@ -465,10 +465,11 @@ namespace SharpCompress.Test.Zip { //windows only because of the paths Skip.IfNot(Environment.OSVersion.Platform == PlatformID.Win32NT); - + string zipFile = Path.Combine(TEST_ARCHIVES_PATH, "Zip.Evil.zip"); - Assert.ThrowsAny(() => { + Assert.ThrowsAny(() => + { using (var archive = ZipArchive.Open(zipFile)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) @@ -563,5 +564,5 @@ namespace SharpCompress.Test.Zip } } } - } + } } diff --git a/tests/SharpCompress.Test/Zip/ZipReaderTests.cs b/tests/SharpCompress.Test/Zip/ZipReaderTests.cs index d0fe0044..ba8b070e 100644 --- a/tests/SharpCompress.Test/Zip/ZipReaderTests.cs +++ b/tests/SharpCompress.Test/Zip/ZipReaderTests.cs @@ -324,11 +324,11 @@ namespace SharpCompress.Test.Zip using (Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Zip.none.issue86.zip"))) using (var reader = ZipReader.Open(stream)) { - foreach( var key in keys ) + foreach (var key in keys) { reader.MoveToNextEntry(); - Assert.Equal( reader.Entry.Key, key ); + Assert.Equal(reader.Entry.Key, key); if (!reader.Entry.IsDirectory) {