From fcf86b738e81d738af12339c30fcb5aa41f4f6cd Mon Sep 17 00:00:00 2001 From: Adam Hathcock Date: Sun, 28 Apr 2013 12:32:55 +0100 Subject: [PATCH] Resharper code cleanup --- SharpCompress/Archive/AbstractArchive.cs | 28 +- .../AbstractWritableArchive.Extensions.cs | 87 +-- .../Archive/AbstractWritableArchive.cs | 28 +- SharpCompress/Archive/ArchiveFactory.cs | 4 +- SharpCompress/Archive/GZip/GZipArchive.cs | 10 +- .../Archive/GZip/GZipArchiveEntry.cs | 7 +- .../Archive/GZip/GZipWritableArchiveEntry.cs | 22 +- SharpCompress/Archive/IArchive.Extensions.cs | 4 +- SharpCompress/Archive/IArchive.cs | 22 +- .../Archive/IArchiveEntry.Extensions.cs | 11 +- SharpCompress/Archive/IArchiveEntry.cs | 2 +- .../Archive/Rar/FileInfoRarArchiveVolume.cs | 21 +- .../Archive/Rar/FileInfoRarFilePart.cs | 10 +- .../Archive/Rar/RarArchive.Extensions.cs | 2 +- SharpCompress/Archive/Rar/RarArchive.cs | 12 +- SharpCompress/Archive/Rar/RarArchiveEntry.cs | 30 +- .../Archive/Rar/RarArchiveEntryFactory.cs | 4 +- .../Archive/Rar/RarArchiveVolumeFactory.cs | 11 +- .../Archive/Rar/SeekableStreamFilePart.cs | 13 +- .../Archive/Rar/StreamRarArchiveVolume.cs | 2 +- .../Archive/SevenZip/SevenZipArchive.cs | 46 +- .../Archive/SevenZip/SevenZipArchiveEntry.cs | 7 +- SharpCompress/Archive/Tar/TarArchive.cs | 16 +- SharpCompress/Archive/Tar/TarArchiveEntry.cs | 6 +- .../Archive/Tar/TarWritableArchiveEntry.cs | 22 +- SharpCompress/Archive/Zip/ZipArchive.cs | 17 +- SharpCompress/Archive/Zip/ZipArchiveEntry.cs | 10 +- .../Archive/Zip/ZipWritableArchiveEntry.cs | 25 +- SharpCompress/AssemblyInfo.cs | 8 +- SharpCompress/Common/ArchiveEncoding.cs | 2 +- SharpCompress/Common/ArchiveException.cs | 2 +- .../Common/ArchiveExtractionEventArgs.cs | 2 +- SharpCompress/Common/ArchiveType.cs | 5 +- .../Common/CompressedBytesReadEventArgs.cs | 2 +- SharpCompress/Common/CompressionInfo.cs | 43 +- SharpCompress/Common/CompressionType.cs | 5 +- .../Common/CryptographicException.cs | 2 +- SharpCompress/Common/Entry.cs | 65 +-- SharpCompress/Common/EntryStream.cs | 15 +- SharpCompress/Common/ExtractOptions.cs | 4 +- SharpCompress/Common/ExtractionException.cs | 6 +- SharpCompress/Common/FilePart.cs | 7 +- .../FilePartExtractionBeginEventArgs.cs | 5 +- SharpCompress/Common/FlagUtility.cs | 26 +- SharpCompress/Common/GZip/GZipFilePart.cs | 4 +- SharpCompress/Common/GZip/GZipVolume.cs | 17 +- SharpCompress/Common/GenericVolume.cs | 17 +- SharpCompress/Common/IEntry.cs | 62 +-- SharpCompress/Common/IStreamListener.cs | 5 +- SharpCompress/Common/IVolume.cs | 8 +- .../Common/IncompleteArchiveException.cs | 5 +- .../Common/InvalidFormatException.cs | 2 +- .../Common/MultiVolumeExtractionException.cs | 3 +- .../MultipartStreamRequiredException.cs | 5 +- SharpCompress/Common/Options.cs | 4 +- .../Common/PasswordProtectedException.cs | 3 +- SharpCompress/Common/Rar/Headers/AVHeader.cs | 20 +- .../Common/Rar/Headers/ArchiveHeader.cs | 25 +- .../Common/Rar/Headers/CommentHeader.cs | 26 +- .../Common/Rar/Headers/EndArchiveHeader.cs | 19 +- .../Common/Rar/Headers/FileHeader.cs | 130 +---- .../Common/Rar/Headers/FileNameDecoder.cs | 11 +- SharpCompress/Common/Rar/Headers/Flags.cs | 2 +- .../Common/Rar/Headers/MarkHeader.cs | 9 +- .../Common/Rar/Headers/NewSubHeader.cs | 4 +- SharpCompress/Common/Rar/Headers/RarHeader.cs | 42 +- .../Common/Rar/Headers/RarHeaderFactory.cs | 14 +- .../Common/Rar/Headers/SignHeader.cs | 26 +- SharpCompress/Common/Rar/RarFilePart.cs | 14 +- SharpCompress/Common/Rar/RarVolume.cs | 13 +- .../Common/SevenZip/ArchiveDatabase.cs | 10 +- .../Common/SevenZip/ArchiveReader.cs | 144 +++-- SharpCompress/Common/SevenZip/CBindPair.cs | 10 +- SharpCompress/Common/SevenZip/CCoderInfo.cs | 14 +- SharpCompress/Common/SevenZip/CFileItem.cs | 12 +- SharpCompress/Common/SevenZip/CFolder.cs | 208 +++---- SharpCompress/Common/SevenZip/CMethodId.cs | 6 +- .../Common/SevenZip/CStreamSwitch.cs | 96 ++-- SharpCompress/Common/SevenZip/DataReader.cs | 252 ++++----- .../Common/SevenZip/SevenZipEntry.cs | 9 +- .../Common/SevenZip/SevenZipFilePart.cs | 20 +- .../Common/SevenZip/SevenZipVolume.cs | 2 +- SharpCompress/Common/Tar/Headers/TarHeader.cs | 38 +- SharpCompress/Common/Tar/TarEntry.cs | 3 +- SharpCompress/Common/Tar/TarFilePart.cs | 3 +- SharpCompress/Common/Tar/TarHeaderFactory.cs | 4 +- .../Common/Tar/TarReadOnlySubStream.cs | 48 +- SharpCompress/Common/Tar/TarVolume.cs | 2 +- SharpCompress/Common/Volume.cs | 23 +- .../Common/Zip/Headers/DirectoryEndHeader.cs | 2 +- .../Zip/Headers/DirectoryEntryHeader.cs | 16 +- .../Common/Zip/Headers/HeaderFlags.cs | 2 +- .../Common/Zip/Headers/LocalEntryHeader.cs | 17 +- .../Common/Zip/Headers/SplitHeader.cs | 2 +- .../Common/Zip/Headers/ZipFileEntry..cs | 19 +- SharpCompress/Common/Zip/Headers/ZipHeader.cs | 8 +- .../Common/Zip/Headers/ZipHeaderType.cs | 5 +- .../Zip/PkwareTraditionalEncryptionData.cs | 27 +- .../Common/Zip/SeekableZipFilePart.cs | 7 +- .../Common/Zip/SeekableZipHeaderFactory.cs | 7 +- .../Common/Zip/StreamingZipFilePart.cs | 3 +- .../Common/Zip/StreamingZipHeaderFactory.cs | 7 +- .../Common/Zip/WinzipAesCryptoStream.cs | 8 +- .../Common/Zip/WinzipAesEncryptionData.cs | 10 +- SharpCompress/Common/Zip/WinzipAesKeySize.cs | 5 +- .../Common/Zip/ZipCompressionMethod.cs | 5 +- SharpCompress/Common/Zip/ZipFilePart.cs | 12 +- SharpCompress/Common/Zip/ZipHeaderFactory.cs | 19 +- SharpCompress/Common/Zip/ZipVolume.cs | 2 +- .../Compressor/BZip2/BZip2Constants.cs | 115 ++-- SharpCompress/Compressor/BZip2/BZip2Stream.cs | 5 +- .../Compressor/BZip2/CBZip2InputStream.cs | 108 ++-- .../Compressor/BZip2/CBZip2OutputStream.cs | 257 +++++---- SharpCompress/Compressor/BZip2/CRC.cs | 205 ++++--- SharpCompress/Compressor/CompressionMode.cs | 5 +- SharpCompress/Compressor/Deflate/CRC32.cs | 14 +- .../Compressor/Deflate/DeflateManager.cs | 444 +++++++-------- .../Compressor/Deflate/DeflateStream.cs | 4 +- SharpCompress/Compressor/Deflate/FlushType.cs | 5 +- .../Compressor/Deflate/GZipStream.cs | 2 +- SharpCompress/Compressor/Deflate/InfTree.cs | 41 +- SharpCompress/Compressor/Deflate/Inflate.cs | 62 +-- .../Deflate/ParallelDeflateOutputStream.cs | 68 +-- SharpCompress/Compressor/Deflate/Tree.cs | 49 +- SharpCompress/Compressor/Deflate/Zlib.cs | 228 +++++--- .../Compressor/Deflate/ZlibBaseStream.cs | 84 +-- SharpCompress/Compressor/Deflate/ZlibCodec.cs | 18 +- .../Compressor/Deflate/ZlibConstants.cs | 6 +- .../Compressor/Filters/BCJ2Filter.cs | 22 +- SharpCompress/Compressor/Filters/BCJFilter.cs | 8 +- SharpCompress/Compressor/Filters/Filter.cs | 12 +- .../Compressor/LZMA/AesDecoderStream.cs | 59 +- .../Compressor/LZMA/Bcj2DecoderStream.cs | 85 +-- SharpCompress/Compressor/LZMA/BitVector.cs | 2 +- SharpCompress/Compressor/LZMA/CRC.cs | 36 +- .../Compressor/LZMA/DecoderStream.cs | 60 +- SharpCompress/Compressor/LZMA/ICoder.cs | 26 +- SharpCompress/Compressor/LZMA/LZ/CRC.cs | 22 +- SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs | 109 ++-- .../Compressor/LZMA/LZ/LzInWindow.cs | 66 ++- .../Compressor/LZMA/LZ/LzOutWindow.cs | 35 +- SharpCompress/Compressor/LZMA/Log.cs | 6 +- SharpCompress/Compressor/LZMA/LzmaBase.cs | 41 +- SharpCompress/Compressor/LZMA/LzmaDecoder.cs | 149 ++--- SharpCompress/Compressor/LZMA/LzmaEncoder.cs | 515 ++++++++++-------- .../Compressor/LZMA/LzmaEncoderProperties.cs | 42 +- SharpCompress/Compressor/LZMA/LzmaStream.cs | 21 +- .../Compressor/LZMA/RangeCoder/RangeCoder.cs | 42 +- .../LZMA/RangeCoder/RangeCoderBit.cs | 52 +- .../LZMA/RangeCoder/RangeCoderBitTree.cs | 22 +- SharpCompress/Compressor/LZMA/Registry.cs | 23 +- .../LZMA/Utilites/CrcBuilderStream.cs | 18 +- .../LZMA/Utilites/CrcCheckStream.cs | 22 +- .../LZMA/Utilites/IPasswordProvider.cs | 2 +- .../LZMA/Utilites/SyncStreamView.cs | 32 +- .../Compressor/LZMA/Utilites/Utils.cs | 20 +- SharpCompress/Compressor/PPMd/H/FreqData.cs | 14 +- SharpCompress/Compressor/PPMd/H/ModelPPM.cs | 258 ++++----- SharpCompress/Compressor/PPMd/H/PPMContext.cs | 62 +-- SharpCompress/Compressor/PPMd/H/Pointer.cs | 13 +- SharpCompress/Compressor/PPMd/H/RangeCoder.cs | 51 +- .../Compressor/PPMd/H/RarMemBlock.cs | 6 +- .../Compressor/PPMd/H/SEE2Context.cs | 47 +- SharpCompress/Compressor/PPMd/H/State.cs | 25 +- SharpCompress/Compressor/PPMd/H/StateRef.cs | 23 +- .../Compressor/PPMd/H/SubAllocator.cs | 86 ++- SharpCompress/Compressor/PPMd/I1/Allocator.cs | 59 +- SharpCompress/Compressor/PPMd/I1/Coder.cs | 18 +- .../Compressor/PPMd/I1/MemoryNode.cs | 30 +- SharpCompress/Compressor/PPMd/I1/Model.cs | 143 ++--- .../PPMd/I1/ModelRestorationMethod.cs | 2 +- SharpCompress/Compressor/PPMd/I1/Pointer.cs | 84 +-- .../Compressor/PPMd/I1/PpmContext.cs | 177 +++--- SharpCompress/Compressor/PPMd/I1/PpmState.cs | 16 +- .../Compressor/PPMd/I1/See2Context.cs | 2 +- .../Compressor/PPMd/PpmdProperties.cs | 14 +- SharpCompress/Compressor/PPMd/PpmdStream.cs | 16 +- .../Compressor/Rar/Decode/AudioVariables.cs | 79 +-- .../Compressor/Rar/Decode/Compress.cs | 1 - SharpCompress/Compressor/Rar/Decode/Decode.cs | 26 +- .../Compressor/Rar/Decode/LitDecode.cs | 1 - .../Compressor/Rar/Decode/RepDecode.cs | 1 - .../Rar/MultiVolumeReadOnlyStream.cs | 41 +- .../Compressor/Rar/PPM/BlockTypes.cs | 1 - SharpCompress/Compressor/Rar/RarCRC.cs | 2 +- SharpCompress/Compressor/Rar/RarStream.cs | 22 +- SharpCompress/Compressor/Rar/Unpack.cs | 132 ++--- SharpCompress/Compressor/Rar/Unpack15.cs | 75 ++- SharpCompress/Compressor/Rar/Unpack20.cs | 68 ++- SharpCompress/Compressor/Rar/UnpackFilter.cs | 36 +- SharpCompress/Compressor/Rar/UnpackUtility.cs | 10 +- SharpCompress/Compressor/Rar/VM/BitInput.cs | 11 +- SharpCompress/Compressor/Rar/VM/RarVM.cs | 356 +++++++----- SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs | 31 +- SharpCompress/Compressor/Rar/VM/VMCommands.cs | 7 + .../Compressor/Rar/VM/VMPreparedCommand.cs | 25 +- .../Compressor/Rar/VM/VMPreparedOperand.cs | 25 +- .../Compressor/Rar/VM/VMPreparedProgram.cs | 18 +- .../Rar/VM/VMStandardFilterSignature.cs | 18 +- SharpCompress/IO/CountingWritableSubStream.cs | 14 +- SharpCompress/IO/ListeningStream.cs | 38 +- SharpCompress/IO/MarkingBinaryReader.cs | 9 +- SharpCompress/IO/NonDisposingStream.cs | 38 +- SharpCompress/IO/ReadOnlySubStream.cs | 46 +- SharpCompress/IO/RewindableStream.cs | 9 +- SharpCompress/IO/StreamingMode.cs | 5 +- SharpCompress/LazyReadOnlyCollection.cs | 5 +- SharpCompress/ReadOnlyCollection.cs | 2 +- SharpCompress/Reader/AbstractReader.cs | 45 +- SharpCompress/Reader/GZip/GZipReader.cs | 4 +- SharpCompress/Reader/IReader.Extensions.cs | 10 +- SharpCompress/Reader/IReader.cs | 12 +- .../Reader/Rar/MultiVolumeRarReader.cs | 16 +- .../Reader/Rar/NonSeekableStreamFilePart.cs | 7 +- SharpCompress/Reader/Rar/RarReader.cs | 12 +- SharpCompress/Reader/Rar/RarReaderVolume.cs | 8 +- .../Reader/Rar/SingleVolumeRarReader.cs | 5 +- SharpCompress/Reader/ReaderFactory.cs | 2 +- SharpCompress/Reader/Tar/TarReader.cs | 5 +- SharpCompress/Reader/Zip/ZipReader.cs | 2 +- SharpCompress/Utility.cs | 71 +-- SharpCompress/VersionInfo.cs | 3 +- SharpCompress/Writer/AbstractWriter.cs | 2 +- SharpCompress/Writer/GZip/GZipWriter.cs | 14 +- SharpCompress/Writer/IWriter.Extensions.cs | 14 +- SharpCompress/Writer/IWriter.cs | 7 +- SharpCompress/Writer/Tar/TarWriter.cs | 7 +- SharpCompress/Writer/WriterFactory.cs | 20 +- .../Writer/Zip/ZipCentralDirectoryEntry.cs | 33 +- SharpCompress/Writer/Zip/ZipWriter.cs | 36 +- 230 files changed, 3909 insertions(+), 4248 deletions(-) diff --git a/SharpCompress/Archive/AbstractArchive.cs b/SharpCompress/Archive/AbstractArchive.cs index e0b6bf85..2ac559f9 100644 --- a/SharpCompress/Archive/AbstractArchive.cs +++ b/SharpCompress/Archive/AbstractArchive.cs @@ -28,7 +28,7 @@ namespace SharpCompress.Archive { throw new ArgumentException("File does not exist: " + fileInfo.FullName); } - options = (Options)FlagUtility.SetFlag(options, Options.KeepStreamsOpen, false); + options = (Options) FlagUtility.SetFlag(options, Options.KeepStreamsOpen, false); lazyVolumes = new LazyReadOnlyCollection(LoadVolumes(fileInfo, options)); lazyEntries = new LazyReadOnlyCollection(LoadEntries(Volumes)); } @@ -40,7 +40,8 @@ namespace SharpCompress.Archive internal AbstractArchive(ArchiveType type, IEnumerable streams, Options options) { this.Type = type; - lazyVolumes = new LazyReadOnlyCollection(LoadVolumes(streams.Select(CheckStreams), options)); + lazyVolumes = + new LazyReadOnlyCollection(LoadVolumes(streams.Select(CheckStreams), options)); lazyEntries = new LazyReadOnlyCollection(LoadEntries(Volumes)); } @@ -141,10 +142,10 @@ namespace SharpCompress.Archive if (CompressedBytesRead != null) { CompressedBytesRead(this, new CompressedBytesReadEventArgs() - { - CurrentFilePartCompressedBytesRead = currentPartCompressedBytes, - CompressedBytesRead = compressedReadBytes - }); + { + CurrentFilePartCompressedBytesRead = currentPartCompressedBytes, + CompressedBytesRead = compressedReadBytes + }); } } @@ -153,11 +154,11 @@ namespace SharpCompress.Archive if (FilePartExtractionBegin != null) { FilePartExtractionBegin(this, new FilePartExtractionBeginEventArgs() - { - CompressedSize = compressedSize, - Size = size, - Name = name, - }); + { + CompressedSize = compressedSize, + Size = size, + Name = name, + }); } } @@ -185,10 +186,7 @@ namespace SharpCompress.Archive /// public virtual bool IsSolid { - get - { - return false; - } + get { return false; } } diff --git a/SharpCompress/Archive/AbstractWritableArchive.Extensions.cs b/SharpCompress/Archive/AbstractWritableArchive.Extensions.cs index df6320dd..05e3fe38 100644 --- a/SharpCompress/Archive/AbstractWritableArchive.Extensions.cs +++ b/SharpCompress/Archive/AbstractWritableArchive.Extensions.cs @@ -5,68 +5,70 @@ namespace SharpCompress.Archive { public static class AbstractWritableArchiveExtensions { - - public static void SaveTo(this AbstractWritableArchive writableArchive, - Stream stream, CompressionType compressionType) - where TEntry : IArchiveEntry - where TVolume : IVolume - { - writableArchive.SaveTo(stream, new CompressionInfo { Type = compressionType }); - } -#if !PORTABLE - - public static void AddEntry(this AbstractWritableArchive writableArchive, - string entryPath, string filePath) - where TEntry : IArchiveEntry - where TVolume : IVolume - { - var fileInfo = new FileInfo(filePath); - if (!fileInfo.Exists) - { - throw new FileNotFoundException("Could not AddEntry: " + filePath); - } - writableArchive.AddEntry(entryPath, new FileInfo(filePath).OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime); - } - public static void SaveTo(this AbstractWritableArchive writableArchive, - string filePath, CompressionType compressionType) + Stream stream, CompressionType compressionType) where TEntry : IArchiveEntry where TVolume : IVolume { - writableArchive.SaveTo(new FileInfo(filePath), new CompressionInfo { Type = compressionType }); + writableArchive.SaveTo(stream, new CompressionInfo {Type = compressionType}); + } + +#if !PORTABLE + + public static void AddEntry(this AbstractWritableArchive writableArchive, + string entryPath, string filePath) + where TEntry : IArchiveEntry + where TVolume : IVolume + { + var fileInfo = new FileInfo(filePath); + if (!fileInfo.Exists) + { + throw new FileNotFoundException("Could not AddEntry: " + filePath); + } + writableArchive.AddEntry(entryPath, new FileInfo(filePath).OpenRead(), true, fileInfo.Length, + fileInfo.LastWriteTime); } public static void SaveTo(this AbstractWritableArchive writableArchive, - FileInfo fileInfo, CompressionType compressionType) + string filePath, CompressionType compressionType) + where TEntry : IArchiveEntry + where TVolume : IVolume + { + writableArchive.SaveTo(new FileInfo(filePath), new CompressionInfo {Type = compressionType}); + } + + public static void SaveTo(this AbstractWritableArchive writableArchive, + FileInfo fileInfo, CompressionType compressionType) where TEntry : IArchiveEntry where TVolume : IVolume { using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write)) { - writableArchive.SaveTo(stream, new CompressionInfo { Type = compressionType }); + writableArchive.SaveTo(stream, new CompressionInfo {Type = compressionType}); } } public static void SaveTo(this AbstractWritableArchive writableArchive, - string filePath, CompressionInfo compressionInfo) - where TEntry : IArchiveEntry - where TVolume : IVolume + string filePath, CompressionInfo compressionInfo) + where TEntry : IArchiveEntry + where TVolume : IVolume { - writableArchive.SaveTo(new FileInfo(filePath), compressionInfo); + writableArchive.SaveTo(new FileInfo(filePath), compressionInfo); } public static void SaveTo(this AbstractWritableArchive writableArchive, - FileInfo fileInfo, CompressionInfo compressionInfo) - where TEntry : IArchiveEntry - where TVolume : IVolume + FileInfo fileInfo, CompressionInfo compressionInfo) + where TEntry : IArchiveEntry + where TVolume : IVolume { - using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write)) - { - writableArchive.SaveTo(stream, compressionInfo); - } + using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write)) + { + writableArchive.SaveTo(stream, compressionInfo); + } } - public static void AddAllFromDirectory(this AbstractWritableArchive writableArchive, + public static void AddAllFromDirectory( + this AbstractWritableArchive writableArchive, string filePath, string searchPattern = "*.*", SearchOption searchOption = SearchOption.AllDirectories) where TEntry : IArchiveEntry where TVolume : IVolume @@ -78,10 +80,11 @@ namespace SharpCompress.Archive #endif { - var fileInfo = new FileInfo(path); - writableArchive.AddEntry(path.Substring(filePath.Length), fileInfo.OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime); + var fileInfo = new FileInfo(path); + writableArchive.AddEntry(path.Substring(filePath.Length), fileInfo.OpenRead(), true, fileInfo.Length, + fileInfo.LastWriteTime); } } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/AbstractWritableArchive.cs b/SharpCompress/Archive/AbstractWritableArchive.cs index 2f00e529..1e82b403 100644 --- a/SharpCompress/Archive/AbstractWritableArchive.cs +++ b/SharpCompress/Archive/AbstractWritableArchive.cs @@ -30,6 +30,7 @@ namespace SharpCompress.Archive anyNotWritable = true; } } + #if !PORTABLE internal AbstractWritableArchive(ArchiveType type, FileInfo fileInfo, Options options) : base(type, fileInfo, options) @@ -66,10 +67,7 @@ namespace SharpCompress.Archive private IEnumerable OldEntries { - get - { - return base.Entries.Where(x => !removedEntries.Contains(x)); - } + get { return base.Entries.Where(x => !removedEntries.Contains(x)); } } public void RemoveEntry(TEntry entry) @@ -83,7 +81,7 @@ namespace SharpCompress.Archive } public void AddEntry(string filePath, Stream source, - long size = 0, DateTime? modified = null) + long size = 0, DateTime? modified = null) { CheckWritable(); newEntries.Add(CreateEntry(filePath, source, size, modified, false)); @@ -91,14 +89,14 @@ namespace SharpCompress.Archive } public void AddEntry(string filePath, Stream source, bool closeStream, - long size = 0, DateTime? modified = null) + long size = 0, DateTime? modified = null) { - CheckWritable(); - newEntries.Add(CreateEntry(filePath, source, size, modified, closeStream)); - RebuildModifiedCollection(); + CheckWritable(); + newEntries.Add(CreateEntry(filePath, source, size, modified, closeStream)); + RebuildModifiedCollection(); } - #if !PORTABLE +#if !PORTABLE public void AddEntry(string filePath, FileInfo fileInfo) { if (!fileInfo.Exists) @@ -107,15 +105,17 @@ namespace SharpCompress.Archive } AddEntry(filePath, fileInfo.OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime); } - #endif +#endif public void SaveTo(Stream stream, CompressionInfo compressionType) { SaveTo(stream, compressionType, OldEntries, newEntries); } - protected abstract TEntry CreateEntry(string filePath, Stream source, long size, DateTime? modified, bool closeStream); + protected abstract TEntry CreateEntry(string filePath, Stream source, long size, DateTime? modified, + bool closeStream); + protected abstract void SaveTo(Stream stream, CompressionInfo compressionType, - IEnumerable oldEntries, IEnumerable newEntries); + IEnumerable oldEntries, IEnumerable newEntries); } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/ArchiveFactory.cs b/SharpCompress/Archive/ArchiveFactory.cs index 9351a153..2677edf6 100644 --- a/SharpCompress/Archive/ArchiveFactory.cs +++ b/SharpCompress/Archive/ArchiveFactory.cs @@ -153,7 +153,7 @@ namespace SharpCompress.Archive /// Extract to specific directory, retaining filename /// public static void WriteToDirectory(string sourceArchive, string destinationDirectory, - ExtractOptions options = ExtractOptions.Overwrite) + ExtractOptions options = ExtractOptions.Overwrite) { using (IArchive archive = Open(sourceArchive)) { @@ -165,4 +165,4 @@ namespace SharpCompress.Archive } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/GZip/GZipArchive.cs b/SharpCompress/Archive/GZip/GZipArchive.cs index f3b5e48c..adb13e06 100644 --- a/SharpCompress/Archive/GZip/GZipArchive.cs +++ b/SharpCompress/Archive/GZip/GZipArchive.cs @@ -161,7 +161,8 @@ namespace SharpCompress.Archive.GZip this.SaveTo(stream, CompressionType.GZip); } - protected override GZipArchiveEntry CreateEntry(string filePath, Stream source, long size, DateTime? modified, bool closeStream) + protected override GZipArchiveEntry CreateEntry(string filePath, Stream source, long size, DateTime? modified, + bool closeStream) { if (Entries.Any()) { @@ -171,7 +172,8 @@ namespace SharpCompress.Archive.GZip } protected override void SaveTo(Stream stream, CompressionInfo compressionInfo, - IEnumerable oldEntries, IEnumerable newEntries) + IEnumerable oldEntries, + IEnumerable newEntries) { if (Entries.Count > 1) { @@ -180,7 +182,7 @@ namespace SharpCompress.Archive.GZip using (var writer = new GZipWriter(stream)) { foreach (var entry in oldEntries.Concat(newEntries) - .Where(x => !x.IsDirectory)) + .Where(x => !x.IsDirectory)) { using (var entryStream = entry.OpenEntryStream()) { @@ -208,4 +210,4 @@ namespace SharpCompress.Archive.GZip return GZipReader.Open(stream); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/GZip/GZipArchiveEntry.cs b/SharpCompress/Archive/GZip/GZipArchiveEntry.cs index f6a7ce22..45b2532c 100644 --- a/SharpCompress/Archive/GZip/GZipArchiveEntry.cs +++ b/SharpCompress/Archive/GZip/GZipArchiveEntry.cs @@ -33,12 +33,9 @@ namespace SharpCompress.Archive.GZip public bool IsComplete { - get - { - return true; - } + get { return true; } } #endregion } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/GZip/GZipWritableArchiveEntry.cs b/SharpCompress/Archive/GZip/GZipWritableArchiveEntry.cs index 3bbd7480..679ccd08 100644 --- a/SharpCompress/Archive/GZip/GZipWritableArchiveEntry.cs +++ b/SharpCompress/Archive/GZip/GZipWritableArchiveEntry.cs @@ -14,7 +14,7 @@ namespace SharpCompress.Archive.GZip private bool closeStream; internal GZipWritableArchiveEntry(GZipArchive archive, Stream stream, - string path, long size, DateTime? lastModified, bool closeStream) + string path, long size, DateTime? lastModified, bool closeStream) : base(archive, null) { this.Stream = stream; @@ -29,14 +29,20 @@ namespace SharpCompress.Archive.GZip get { return 0; } } - public override string FilePath { get { return path; } } + public override string FilePath + { + get { return path; } + } public override long CompressedSize { get { return 0; } } - public override long Size { get { return size; } } + public override long Size + { + get { return size; } + } public override DateTime? LastModifiedTime { @@ -87,10 +93,10 @@ namespace SharpCompress.Archive.GZip internal override void Close() { - if (closeStream) - { - Stream.Dispose(); - } + if (closeStream) + { + Stream.Dispose(); + } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/IArchive.Extensions.cs b/SharpCompress/Archive/IArchive.Extensions.cs index ff4619b7..b2a4adb8 100644 --- a/SharpCompress/Archive/IArchive.Extensions.cs +++ b/SharpCompress/Archive/IArchive.Extensions.cs @@ -10,7 +10,7 @@ namespace SharpCompress.Archive /// Extract to specific directory, retaining filename /// public static void WriteToDirectory(this IArchive archive, string destinationDirectory, - ExtractOptions options = ExtractOptions.Overwrite) + ExtractOptions options = ExtractOptions.Overwrite) { foreach (IArchiveEntry entry in archive.Entries.Where(x => !x.IsDirectory)) { @@ -19,4 +19,4 @@ namespace SharpCompress.Archive } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/IArchive.cs b/SharpCompress/Archive/IArchive.cs index c8063036..f38e4164 100644 --- a/SharpCompress/Archive/IArchive.cs +++ b/SharpCompress/Archive/IArchive.cs @@ -13,18 +13,9 @@ namespace SharpCompress.Archive event EventHandler CompressedBytesRead; event EventHandler FilePartExtractionBegin; - IEnumerable Entries - { - get; - } - long TotalSize - { - get; - } - IEnumerable Volumes - { - get; - } + IEnumerable Entries { get; } + long TotalSize { get; } + IEnumerable Volumes { get; } ArchiveType Type { get; } @@ -40,14 +31,11 @@ namespace SharpCompress.Archive /// Archive is SOLID (this means the Archive saved bytes by reusing information which helps for archives containing many small files). /// Rar Archives can be SOLID while all 7Zip archives are considered SOLID. /// - bool IsSolid - { - get; - } + bool IsSolid { get; } /// /// This checks to see if all the known entries have IsComplete = true /// bool IsComplete { get; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/IArchiveEntry.Extensions.cs b/SharpCompress/Archive/IArchiveEntry.Extensions.cs index e369d55f..6576318f 100644 --- a/SharpCompress/Archive/IArchiveEntry.Extensions.cs +++ b/SharpCompress/Archive/IArchiveEntry.Extensions.cs @@ -1,12 +1,12 @@ using System.IO; using SharpCompress.Common; + #if THREEFIVE using SharpCompress.Common.Rar.Headers; #endif namespace SharpCompress.Archive { - public static class IArchiveEntryExtensions { #if !PORTABLE @@ -14,7 +14,7 @@ namespace SharpCompress.Archive /// Extract to specific directory, retaining filename /// public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory, - ExtractOptions options = ExtractOptions.Overwrite) + ExtractOptions options = ExtractOptions.Overwrite) { string destinationFileName = string.Empty; string file = Path.GetFileName(entry.FilePath); @@ -22,7 +22,6 @@ namespace SharpCompress.Archive if (options.HasFlag(ExtractOptions.ExtractFullPath)) { - string folder = Path.GetDirectoryName(entry.FilePath); string destdir = Path.Combine(destinationDirectory, folder); if (!Directory.Exists(destdir)) @@ -42,7 +41,7 @@ namespace SharpCompress.Archive /// Extract to specific file /// public static void WriteToFile(this IArchiveEntry entry, string destinationFileName, - ExtractOptions options = ExtractOptions.Overwrite) + ExtractOptions options = ExtractOptions.Overwrite) { if (entry.IsDirectory) { @@ -58,9 +57,9 @@ namespace SharpCompress.Archive // using (Stream entryStream = entry.OpenEntryStream()) { //entryStream.TransferTo(fs); - entry.WriteTo(fs); + entry.WriteTo(fs); } } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/IArchiveEntry.cs b/SharpCompress/Archive/IArchiveEntry.cs index 8658be78..e9727003 100644 --- a/SharpCompress/Archive/IArchiveEntry.cs +++ b/SharpCompress/Archive/IArchiveEntry.cs @@ -18,4 +18,4 @@ namespace SharpCompress.Archive /// bool IsComplete { get; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Rar/FileInfoRarArchiveVolume.cs b/SharpCompress/Archive/Rar/FileInfoRarArchiveVolume.cs index b35c0fcc..621f3591 100644 --- a/SharpCompress/Archive/Rar/FileInfoRarArchiveVolume.cs +++ b/SharpCompress/Archive/Rar/FileInfoRarArchiveVolume.cs @@ -24,22 +24,14 @@ namespace SharpCompress.Archive.Rar //make sure we're closing streams with fileinfo if (options.HasFlag(Options.KeepStreamsOpen)) { - options = (Options)FlagUtility.SetFlag(options, Options.KeepStreamsOpen, false); + options = (Options) FlagUtility.SetFlag(options, Options.KeepStreamsOpen, false); } return options; } - internal ReadOnlyCollection FileParts - { - get; - private set; - } + internal ReadOnlyCollection FileParts { get; private set; } - internal FileInfo FileInfo - { - get; - private set; - } + internal FileInfo FileInfo { get; private set; } internal override RarFilePart CreateFilePart(FileHeader fileHeader, MarkHeader markHeader) { @@ -53,10 +45,7 @@ namespace SharpCompress.Archive.Rar public override FileInfo VolumeFile { - get - { - return FileInfo; - } + get { return FileInfo; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Rar/FileInfoRarFilePart.cs b/SharpCompress/Archive/Rar/FileInfoRarFilePart.cs index 22d75a9b..cea7d6a1 100644 --- a/SharpCompress/Archive/Rar/FileInfoRarFilePart.cs +++ b/SharpCompress/Archive/Rar/FileInfoRarFilePart.cs @@ -15,11 +15,7 @@ namespace SharpCompress.Archive.Rar FileInfo = fi; } - internal FileInfo FileInfo - { - get; - private set; - } + internal FileInfo FileInfo { get; private set; } internal override Stream GetCompressedStream() { @@ -33,8 +29,8 @@ namespace SharpCompress.Archive.Rar get { return "Rar File: " + FileInfo.FullName - + " File Entry: " + FileHeader.FileName; + + " File Entry: " + FileHeader.FileName; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Rar/RarArchive.Extensions.cs b/SharpCompress/Archive/Rar/RarArchive.Extensions.cs index cac2fb15..b295aa39 100644 --- a/SharpCompress/Archive/Rar/RarArchive.Extensions.cs +++ b/SharpCompress/Archive/Rar/RarArchive.Extensions.cs @@ -28,4 +28,4 @@ namespace SharpCompress.Archive.Rar return archive.IsSolid; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Rar/RarArchive.cs b/SharpCompress/Archive/Rar/RarArchive.cs index 73df984f..5c8ccbdf 100644 --- a/SharpCompress/Archive/Rar/RarArchive.cs +++ b/SharpCompress/Archive/Rar/RarArchive.cs @@ -18,10 +18,7 @@ namespace SharpCompress.Archive.Rar internal Unpack Unpack { - get - { - return unpack; - } + get { return unpack; } } #if !PORTABLE @@ -70,10 +67,7 @@ namespace SharpCompress.Archive.Rar public override bool IsSolid { - get - { - return Volumes.First().IsSolidArchive; - } + get { return Volumes.First().IsSolidArchive; } } #region Creation @@ -196,7 +190,7 @@ namespace SharpCompress.Archive.Rar { return false; } - return Enum.IsDefined(typeof(HeaderType), header.HeaderType); + return Enum.IsDefined(typeof (HeaderType), header.HeaderType); } catch { diff --git a/SharpCompress/Archive/Rar/RarArchiveEntry.cs b/SharpCompress/Archive/Rar/RarArchiveEntry.cs index cb8d6000..3dc86a54 100644 --- a/SharpCompress/Archive/Rar/RarArchiveEntry.cs +++ b/SharpCompress/Archive/Rar/RarArchiveEntry.cs @@ -23,26 +23,16 @@ namespace SharpCompress.Archive.Rar get { return CompressionType.Rar; } } - private RarArchive Archive - { - get; - set; - } + private RarArchive Archive { get; set; } internal override IEnumerable Parts { - get - { - return parts.Cast(); - } + get { return parts.Cast(); } } internal override FileHeader FileHeader { - get - { - return parts.First().FileHeader; - } + get { return parts.First().FileHeader; } } public override uint Crc @@ -51,8 +41,8 @@ namespace SharpCompress.Archive.Rar { CheckIncomplete(); return parts.Select(fp => fp.FileHeader) - .Where(fh => !fh.FileFlags.HasFlag(FileFlags.SPLIT_AFTER)) - .Single().FileCRC; + .Where(fh => !fh.FileFlags.HasFlag(FileFlags.SPLIT_AFTER)) + .Single().FileCRC; } } @@ -71,10 +61,7 @@ namespace SharpCompress.Archive.Rar get { CheckIncomplete(); - return parts.Aggregate(0L, (total, fp) => - { - return total + fp.FileHeader.CompressedSize; - }); + return parts.Aggregate(0L, (total, fp) => { return total + fp.FileHeader.CompressedSize; }); } } @@ -100,10 +87,7 @@ namespace SharpCompress.Archive.Rar public bool IsComplete { - get - { - return parts.Select(fp => fp.FileHeader).Any(fh => !fh.FileFlags.HasFlag(FileFlags.SPLIT_AFTER)); - } + get { return parts.Select(fp => fp.FileHeader).Any(fh => !fh.FileFlags.HasFlag(FileFlags.SPLIT_AFTER)); } } private void CheckIncomplete() diff --git a/SharpCompress/Archive/Rar/RarArchiveEntryFactory.cs b/SharpCompress/Archive/Rar/RarArchiveEntryFactory.cs index fec0242a..9f6ca64a 100644 --- a/SharpCompress/Archive/Rar/RarArchiveEntryFactory.cs +++ b/SharpCompress/Archive/Rar/RarArchiveEntryFactory.cs @@ -25,7 +25,7 @@ namespace SharpCompress.Archive.Rar { groupedParts.Add(fp); - if (!FlagUtility.HasFlag((long)fp.FileHeader.FileFlags, (long)FileFlags.SPLIT_AFTER)) + if (!FlagUtility.HasFlag((long) fp.FileHeader.FileFlags, (long) FileFlags.SPLIT_AFTER)) { yield return groupedParts; groupedParts = new List(); @@ -46,4 +46,4 @@ namespace SharpCompress.Archive.Rar } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Rar/RarArchiveVolumeFactory.cs b/SharpCompress/Archive/Rar/RarArchiveVolumeFactory.cs index 30b05a49..4d07685c 100644 --- a/SharpCompress/Archive/Rar/RarArchiveVolumeFactory.cs +++ b/SharpCompress/Archive/Rar/RarArchiveVolumeFactory.cs @@ -55,7 +55,7 @@ namespace SharpCompress.Archive.Rar return null; } bool oldNumbering = !ah.ArchiveHeaderFlags.HasFlag(ArchiveFlags.NEWNUMBERING) - || currentFilePart.MarkHeader.OldFormat; + || currentFilePart.MarkHeader.OldFormat; if (oldNumbering) { return FindNextFileWithOldNumbering(currentFilePart.FileInfo); @@ -73,7 +73,7 @@ namespace SharpCompress.Archive.Rar StringBuilder buffer = new StringBuilder(currentFileInfo.FullName.Length); buffer.Append(currentFileInfo.FullName.Substring(0, - currentFileInfo.FullName.Length - extension.Length)); + currentFileInfo.FullName.Length - extension.Length)); if (string.Compare(extension, ".rar", StringComparison.InvariantCultureIgnoreCase) == 0) { buffer.Append(".r00"); @@ -116,7 +116,8 @@ namespace SharpCompress.Archive.Rar buffer.Append(currentFileInfo.FullName, 0, startIndex); int num = 0; string numString = currentFileInfo.FullName.Substring(startIndex + 5, - currentFileInfo.FullName.IndexOf('.', startIndex + 5) - startIndex - 5); + currentFileInfo.FullName.IndexOf('.', startIndex + 5) - + startIndex - 5); buffer.Append(".part"); if (int.TryParse(numString, out num)) { @@ -138,9 +139,9 @@ namespace SharpCompress.Archive.Rar private static void ThrowInvalidFileName(FileInfo fileInfo) { throw new ArgumentException("Filename invalid or next archive could not be found:" - + fileInfo.FullName); + + fileInfo.FullName); } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Rar/SeekableStreamFilePart.cs b/SharpCompress/Archive/Rar/SeekableStreamFilePart.cs index eaff37c2..5b880644 100644 --- a/SharpCompress/Archive/Rar/SeekableStreamFilePart.cs +++ b/SharpCompress/Archive/Rar/SeekableStreamFilePart.cs @@ -12,11 +12,7 @@ namespace SharpCompress.Archive.Rar Stream = stream; } - internal Stream Stream - { - get; - private set; - } + internal Stream Stream { get; private set; } internal override Stream GetCompressedStream() { @@ -26,10 +22,7 @@ namespace SharpCompress.Archive.Rar internal override string FilePartName { - get - { - return "Unknown Stream - File Entry: " + base.FileHeader.FileName; - } + get { return "Unknown Stream - File Entry: " + base.FileHeader.FileName; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Rar/StreamRarArchiveVolume.cs b/SharpCompress/Archive/Rar/StreamRarArchiveVolume.cs index 9505edb1..c6a06b0e 100644 --- a/SharpCompress/Archive/Rar/StreamRarArchiveVolume.cs +++ b/SharpCompress/Archive/Rar/StreamRarArchiveVolume.cs @@ -31,4 +31,4 @@ namespace SharpCompress.Archive.Rar return new SeekableStreamFilePart(markHeader, fileHeader, Stream); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/SevenZip/SevenZipArchive.cs b/SharpCompress/Archive/SevenZip/SevenZipArchive.cs index b2c9ede3..218412a1 100644 --- a/SharpCompress/Archive/SevenZip/SevenZipArchive.cs +++ b/SharpCompress/Archive/SevenZip/SevenZipArchive.cs @@ -74,6 +74,7 @@ namespace SharpCompress.Archive.SevenZip stream.CheckNotNull("stream"); return new SevenZipArchive(stream, options); } + #if !PORTABLE internal SevenZipArchive(FileInfo fileInfo, Options options) : base(ArchiveType.SevenZip, fileInfo, options) @@ -133,10 +134,10 @@ namespace SharpCompress.Archive.SevenZip for (int i = 0; i < database.Files.Count; i++) { var file = database.Files[i]; - if (!file.IsDir) - { - yield return new SevenZipArchiveEntry(this, new SevenZipFilePart(stream, database, i, file)); - } + if (!file.IsDir) + { + yield return new SevenZipArchiveEntry(this, new SevenZipFilePart(stream, database, i, file)); + } } } @@ -163,12 +164,14 @@ namespace SharpCompress.Archive.SevenZip return false; } } - private static readonly byte[] SIGNATURE = new byte[] { (byte)'7', (byte)'z', 0xBC, 0xAF, 0x27, 0x1C }; + + private static readonly byte[] SIGNATURE = new byte[] {(byte) '7', (byte) 'z', 0xBC, 0xAF, 0x27, 0x1C}; + private static bool SignatureMatch(Stream stream) { - BinaryReader reader = new BinaryReader(stream); - byte[] signatureBytes = reader.ReadBytes(6); - return signatureBytes.BinaryEquals(SIGNATURE); + BinaryReader reader = new BinaryReader(stream); + byte[] signatureBytes = reader.ReadBytes(6); + return signatureBytes.BinaryEquals(SIGNATURE); } protected override IReader CreateReaderForSolidExtraction() @@ -178,10 +181,7 @@ namespace SharpCompress.Archive.SevenZip public override bool IsSolid { - get - { - return Entries.Where(x => !x.IsDirectory).GroupBy(x => x.FilePart.Folder).Count() > 1; - } + get { return Entries.Where(x => !x.IsDirectory).GroupBy(x => x.FilePart.Folder).Count() > 1; } } private class SevenZipReader : AbstractReader @@ -213,26 +213,26 @@ namespace SharpCompress.Archive.SevenZip } foreach (var group in entries.Where(x => !x.IsDirectory).GroupBy(x => x.FilePart.Folder)) { - currentFolder = group.Key; - if (group.Key == null) - { + currentFolder = group.Key; + if (group.Key == null) + { currentStream = Stream.Null; - } - else - { + } + else + { currentStream = archive.database.GetFolderStream(stream, currentFolder, null); - } - foreach (var entry in group) - { + } + foreach (var entry in group) + { currentItem = entry.FilePart.Header; yield return entry; - } + } } } protected override EntryStream GetEntryStream() { - return new EntryStream(new ReadOnlySubStream(currentStream, currentItem.Size)); + return new EntryStream(new ReadOnlySubStream(currentStream, currentItem.Size)); } } } diff --git a/SharpCompress/Archive/SevenZip/SevenZipArchiveEntry.cs b/SharpCompress/Archive/SevenZip/SevenZipArchiveEntry.cs index 4e5b47ef..57964990 100644 --- a/SharpCompress/Archive/SevenZip/SevenZipArchiveEntry.cs +++ b/SharpCompress/Archive/SevenZip/SevenZipArchiveEntry.cs @@ -30,10 +30,7 @@ namespace SharpCompress.Archive.SevenZip public bool IsComplete { - get - { - return true; - } + get { return true; } } /// @@ -44,4 +41,4 @@ namespace SharpCompress.Archive.SevenZip get { return FilePart.Header.IsAnti; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Tar/TarArchive.cs b/SharpCompress/Archive/Tar/TarArchive.cs index a0253dcc..6578b9b4 100644 --- a/SharpCompress/Archive/Tar/TarArchive.cs +++ b/SharpCompress/Archive/Tar/TarArchive.cs @@ -102,7 +102,7 @@ namespace SharpCompress.Archive.Tar { TarHeader tar = new TarHeader(); tar.Read(new BinaryReader(stream)); - return tar.Name.Length > 0 && Enum.IsDefined(typeof(EntryType), tar.EntryType); + return tar.Name.Length > 0 && Enum.IsDefined(typeof (EntryType), tar.EntryType); } catch { @@ -163,7 +163,8 @@ namespace SharpCompress.Archive.Tar { if (previousHeader != null) { - var entry = new TarArchiveEntry(this, new TarFilePart(previousHeader, stream), CompressionType.None); + var entry = new TarArchiveEntry(this, new TarFilePart(previousHeader, stream), + CompressionType.None); var memoryStream = new MemoryStream(); entry.WriteTo(memoryStream); memoryStream.Position = 0; @@ -183,19 +184,20 @@ namespace SharpCompress.Archive.Tar } protected override TarArchiveEntry CreateEntry(string filePath, Stream source, - long size, DateTime? modified, bool closeStream) + long size, DateTime? modified, bool closeStream) { - return new TarWritableArchiveEntry(this, source, CompressionType.Unknown, filePath, size, modified, closeStream); + return new TarWritableArchiveEntry(this, source, CompressionType.Unknown, filePath, size, modified, + closeStream); } protected override void SaveTo(Stream stream, CompressionInfo compressionInfo, - IEnumerable oldEntries, - IEnumerable newEntries) + IEnumerable oldEntries, + IEnumerable newEntries) { using (var writer = new TarWriter(stream, compressionInfo)) { foreach (var entry in oldEntries.Concat(newEntries) - .Where(x => !x.IsDirectory)) + .Where(x => !x.IsDirectory)) { using (var entryStream = entry.OpenEntryStream()) { diff --git a/SharpCompress/Archive/Tar/TarArchiveEntry.cs b/SharpCompress/Archive/Tar/TarArchiveEntry.cs index d3f0ac72..5c3d8e95 100644 --- a/SharpCompress/Archive/Tar/TarArchiveEntry.cs +++ b/SharpCompress/Archive/Tar/TarArchiveEntry.cs @@ -8,6 +8,7 @@ namespace SharpCompress.Archive.Tar public class TarArchiveEntry : TarEntry, IArchiveEntry { private TarArchive archive; + internal TarArchiveEntry(TarArchive archive, TarFilePart part, CompressionType compressionType) : base(part, compressionType) { @@ -32,10 +33,7 @@ namespace SharpCompress.Archive.Tar public bool IsComplete { - get - { - return true; - } + get { return true; } } #endregion diff --git a/SharpCompress/Archive/Tar/TarWritableArchiveEntry.cs b/SharpCompress/Archive/Tar/TarWritableArchiveEntry.cs index ab080195..15644ace 100644 --- a/SharpCompress/Archive/Tar/TarWritableArchiveEntry.cs +++ b/SharpCompress/Archive/Tar/TarWritableArchiveEntry.cs @@ -14,7 +14,7 @@ namespace SharpCompress.Archive.Tar private bool closeStream; internal TarWritableArchiveEntry(TarArchive archive, Stream stream, CompressionType compressionType, - string path, long size, DateTime? lastModified, bool closeStream) + string path, long size, DateTime? lastModified, bool closeStream) : base(archive, null, compressionType) { this.Stream = stream; @@ -29,14 +29,20 @@ namespace SharpCompress.Archive.Tar get { return 0; } } - public override string FilePath { get { return path; } } + public override string FilePath + { + get { return path; } + } public override long CompressedSize { get { return 0; } } - public override long Size { get { return size; } } + public override long Size + { + get { return size; } + } public override DateTime? LastModifiedTime { @@ -87,10 +93,10 @@ namespace SharpCompress.Archive.Tar internal override void Close() { - if (closeStream) - { - Stream.Dispose(); - } + if (closeStream) + { + Stream.Dispose(); + } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Archive/Zip/ZipArchive.cs b/SharpCompress/Archive/Zip/ZipArchive.cs index 7aec5a13..f9fc799f 100644 --- a/SharpCompress/Archive/Zip/ZipArchive.cs +++ b/SharpCompress/Archive/Zip/ZipArchive.cs @@ -121,7 +121,7 @@ namespace SharpCompress.Archive.Zip { return false; } - return Enum.IsDefined(typeof(ZipHeaderType), header.ZipHeaderType); + return Enum.IsDefined(typeof (ZipHeaderType), header.ZipHeaderType); } catch (CryptographicException) { @@ -187,7 +187,9 @@ namespace SharpCompress.Archive.Zip case ZipHeaderType.DirectoryEntry: { yield return new ZipArchiveEntry(this, - new SeekableZipFilePart(headerFactory, h as DirectoryEntryHeader, stream)); + new SeekableZipFilePart(headerFactory, + h as DirectoryEntryHeader, + stream)); } break; case ZipHeaderType.DirectoryEnd: @@ -202,15 +204,15 @@ namespace SharpCompress.Archive.Zip } protected override void SaveTo(Stream stream, CompressionInfo compressionInfo, - IEnumerable oldEntries, - IEnumerable newEntries) + IEnumerable oldEntries, + IEnumerable newEntries) { using (var writer = new ZipWriter(stream, compressionInfo, string.Empty)) { foreach (var entry in oldEntries.Concat(newEntries) - .Where(x => !x.IsDirectory)) + .Where(x => !x.IsDirectory)) { - using(var entryStream = entry.OpenEntryStream()) + using (var entryStream = entry.OpenEntryStream()) { writer.Write(entry.FilePath, entryStream, entry.LastModifiedTime, string.Empty); } @@ -218,7 +220,8 @@ namespace SharpCompress.Archive.Zip } } - protected override ZipArchiveEntry CreateEntry(string filePath, Stream source, long size, DateTime? modified, bool closeStream) + protected override ZipArchiveEntry CreateEntry(string filePath, Stream source, long size, DateTime? modified, + bool closeStream) { return new ZipWritableArchiveEntry(this, source, filePath, size, modified, closeStream); } diff --git a/SharpCompress/Archive/Zip/ZipArchiveEntry.cs b/SharpCompress/Archive/Zip/ZipArchiveEntry.cs index 1acd6a1a..17ec0cf9 100644 --- a/SharpCompress/Archive/Zip/ZipArchiveEntry.cs +++ b/SharpCompress/Archive/Zip/ZipArchiveEntry.cs @@ -28,20 +28,14 @@ namespace SharpCompress.Archive.Zip public bool IsComplete { - get - { - return true; - } + get { return true; } } #endregion public string Comment { - get - { - return (Parts.Single() as SeekableZipFilePart).Comment; - } + get { return (Parts.Single() as SeekableZipFilePart).Comment; } } } } \ No newline at end of file diff --git a/SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs b/SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs index 7b1973c7..4da5d382 100644 --- a/SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs +++ b/SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs @@ -13,7 +13,8 @@ namespace SharpCompress.Archive.Zip private DateTime? lastModified; private bool closeStream; - internal ZipWritableArchiveEntry(ZipArchive archive, Stream stream, string path, long size, DateTime? lastModified, bool closeStream) + internal ZipWritableArchiveEntry(ZipArchive archive, Stream stream, string path, long size, + DateTime? lastModified, bool closeStream) : base(archive, null) { this.Stream = stream; @@ -28,14 +29,20 @@ namespace SharpCompress.Archive.Zip get { return 0; } } - public override string FilePath { get { return path; } } + public override string FilePath + { + get { return path; } + } public override long CompressedSize { get { return 0; } } - public override long Size { get { return size; } } + public override long Size + { + get { return size; } + } public override DateTime? LastModifiedTime { @@ -81,15 +88,15 @@ namespace SharpCompress.Archive.Zip public override Stream OpenEntryStream() { - return new NonDisposingStream(Stream); + return new NonDisposingStream(Stream); } internal override void Close() { - if (closeStream) - { - Stream.Dispose(); - } + if (closeStream) + { + Stream.Dispose(); + } } } -} +} \ No newline at end of file diff --git a/SharpCompress/AssemblyInfo.cs b/SharpCompress/AssemblyInfo.cs index 6c11b5cc..375915be 100644 --- a/SharpCompress/AssemblyInfo.cs +++ b/SharpCompress/AssemblyInfo.cs @@ -13,9 +13,13 @@ using System.Runtime.CompilerServices; [assembly: AssemblyTitle("SharpCompress.3.5")] [assembly: AssemblyProduct("SharpCompress.3.5")] #else + [assembly: AssemblyTitle("SharpCompress")] [assembly: AssemblyProduct("SharpCompress")] -[assembly: InternalsVisibleTo("SharpCompress.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010005d6ae1b0f6875393da83c920a5b9408f5191aaf4e8b3c2c476ad2a11f5041ecae84ce9298bc4c203637e2fd3a80ad5378a9fa8da1363e98cea45c73969198a4b64510927c910001491cebbadf597b22448ad103b0a4007e339faf8fe8665dcdb70d65b27ac05b1977c0655fad06b372b820ecbdccf10a0f214fee0986dfeded")] -#endif +[assembly: + InternalsVisibleTo( + "SharpCompress.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010005d6ae1b0f6875393da83c920a5b9408f5191aaf4e8b3c2c476ad2a11f5041ecae84ce9298bc4c203637e2fd3a80ad5378a9fa8da1363e98cea45c73969198a4b64510927c910001491cebbadf597b22448ad103b0a4007e339faf8fe8665dcdb70d65b27ac05b1977c0655fad06b372b820ecbdccf10a0f214fee0986dfeded" + )] #endif #endif +#endif \ No newline at end of file diff --git a/SharpCompress/Common/ArchiveEncoding.cs b/SharpCompress/Common/ArchiveEncoding.cs index 9f28b70e..f56f9c47 100644 --- a/SharpCompress/Common/ArchiveEncoding.cs +++ b/SharpCompress/Common/ArchiveEncoding.cs @@ -26,4 +26,4 @@ namespace SharpCompress.Common #endif } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/ArchiveException.cs b/SharpCompress/Common/ArchiveException.cs index b822ac47..3a969784 100644 --- a/SharpCompress/Common/ArchiveException.cs +++ b/SharpCompress/Common/ArchiveException.cs @@ -9,4 +9,4 @@ namespace SharpCompress.Common { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/ArchiveExtractionEventArgs.cs b/SharpCompress/Common/ArchiveExtractionEventArgs.cs index 44c7a45f..1a4cba25 100644 --- a/SharpCompress/Common/ArchiveExtractionEventArgs.cs +++ b/SharpCompress/Common/ArchiveExtractionEventArgs.cs @@ -11,4 +11,4 @@ namespace SharpCompress.Common public T Item { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/ArchiveType.cs b/SharpCompress/Common/ArchiveType.cs index f65d3e41..2b405356 100644 --- a/SharpCompress/Common/ArchiveType.cs +++ b/SharpCompress/Common/ArchiveType.cs @@ -1,5 +1,4 @@ - -namespace SharpCompress.Common +namespace SharpCompress.Common { public enum ArchiveType { @@ -9,4 +8,4 @@ namespace SharpCompress.Common SevenZip, GZip, } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/CompressedBytesReadEventArgs.cs b/SharpCompress/Common/CompressedBytesReadEventArgs.cs index ade2119d..7c8ed598 100644 --- a/SharpCompress/Common/CompressedBytesReadEventArgs.cs +++ b/SharpCompress/Common/CompressedBytesReadEventArgs.cs @@ -14,4 +14,4 @@ namespace SharpCompress.Common /// public long CurrentFilePartCompressedBytesRead { get; internal set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/CompressionInfo.cs b/SharpCompress/Common/CompressionInfo.cs index 41ebe71f..f62ea405 100644 --- a/SharpCompress/Common/CompressionInfo.cs +++ b/SharpCompress/Common/CompressionInfo.cs @@ -2,26 +2,29 @@ namespace SharpCompress.Common { - /// - /// Detailed compression properties when saving. - /// - public class CompressionInfo - { - public CompressionInfo() - { - DeflateCompressionLevel = CompressionLevel.Default; - } + /// + /// Detailed compression properties when saving. + /// + public class CompressionInfo + { + public CompressionInfo() + { + DeflateCompressionLevel = CompressionLevel.Default; + } - /// - /// The algorthm to use. Must be valid for the format type. - /// - public CompressionType Type { get; set; } + /// + /// The algorthm to use. Must be valid for the format type. + /// + public CompressionType Type { get; set; } - /// - /// When CompressionType.Deflate is used, this property is referenced. Defaults to CompressionLevel.Default. - /// - public CompressionLevel DeflateCompressionLevel { get; set; } + /// + /// When CompressionType.Deflate is used, this property is referenced. Defaults to CompressionLevel.Default. + /// + public CompressionLevel DeflateCompressionLevel { get; set; } - public static implicit operator CompressionInfo(CompressionType compressionType) { return new CompressionInfo() { Type = compressionType }; } - } -} + public static implicit operator CompressionInfo(CompressionType compressionType) + { + return new CompressionInfo() {Type = compressionType}; + } + } +} \ No newline at end of file diff --git a/SharpCompress/Common/CompressionType.cs b/SharpCompress/Common/CompressionType.cs index 1bd39d66..d51e6545 100644 --- a/SharpCompress/Common/CompressionType.cs +++ b/SharpCompress/Common/CompressionType.cs @@ -1,5 +1,4 @@ - -namespace SharpCompress.Common +namespace SharpCompress.Common { public enum CompressionType { @@ -14,4 +13,4 @@ namespace SharpCompress.Common BCJ2, Unknown, } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/CryptographicException.cs b/SharpCompress/Common/CryptographicException.cs index cab9c467..4e17f303 100644 --- a/SharpCompress/Common/CryptographicException.cs +++ b/SharpCompress/Common/CryptographicException.cs @@ -9,4 +9,4 @@ namespace SharpCompress.Common { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Entry.cs b/SharpCompress/Common/Entry.cs index 7637a36a..e8a2c673 100644 --- a/SharpCompress/Common/Entry.cs +++ b/SharpCompress/Common/Entry.cs @@ -10,100 +10,61 @@ namespace SharpCompress.Common /// /// The File's 32 bit CRC Hash /// - public abstract uint Crc - { - get; - } + public abstract uint Crc { get; } /// /// The path of the file internal to the Rar Archive. /// - public abstract string FilePath - { - get; - } + public abstract string FilePath { get; } /// /// The compressed file size /// - public abstract long CompressedSize - { - get; - } + public abstract long CompressedSize { get; } /// /// The compression type /// - public abstract CompressionType CompressionType - { - get; - } + public abstract CompressionType CompressionType { get; } /// /// The uncompressed file size /// - public abstract long Size - { - get; - } + public abstract long Size { get; } /// /// The entry last modified time in the archive, if recorded /// - public abstract DateTime? LastModifiedTime - { - get; - } + public abstract DateTime? LastModifiedTime { get; } /// /// The entry create time in the archive, if recorded /// - public abstract DateTime? CreatedTime - { - get; - } + public abstract DateTime? CreatedTime { get; } /// /// The entry last accessed time in the archive, if recorded /// - public abstract DateTime? LastAccessedTime - { - get; - } + public abstract DateTime? LastAccessedTime { get; } /// /// The entry time whend archived, if recorded /// - public abstract DateTime? ArchivedTime - { - get; - } + public abstract DateTime? ArchivedTime { get; } /// /// Entry is password protected and encrypted and cannot be extracted. /// - public abstract bool IsEncrypted - { - get; - } + public abstract bool IsEncrypted { get; } /// /// Entry is password protected and encrypted and cannot be extracted. /// - public abstract bool IsDirectory - { - get; - } + public abstract bool IsDirectory { get; } - public abstract bool IsSplit - { - get; - } + public abstract bool IsSplit { get; } - internal abstract IEnumerable Parts - { - get; - } + internal abstract IEnumerable Parts { get; } internal abstract void Close(); } diff --git a/SharpCompress/Common/EntryStream.cs b/SharpCompress/Common/EntryStream.cs index b3ececcd..6ba87a41 100644 --- a/SharpCompress/Common/EntryStream.cs +++ b/SharpCompress/Common/EntryStream.cs @@ -29,7 +29,8 @@ namespace SharpCompress.Common { if (!completed) { - throw new InvalidOperationException("EntryStream has not been fully consumed. Read the entire stream or use SkipEntry."); + throw new InvalidOperationException( + "EntryStream has not been fully consumed. Read the entire stream or use SkipEntry."); } base.Dispose(disposing); stream.Dispose(); @@ -62,14 +63,8 @@ namespace SharpCompress.Common public override long Position { - get - { - throw new System.NotImplementedException(); - } - set - { - throw new System.NotImplementedException(); - } + get { throw new System.NotImplementedException(); } + set { throw new System.NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) @@ -97,4 +92,4 @@ namespace SharpCompress.Common throw new System.NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/ExtractOptions.cs b/SharpCompress/Common/ExtractOptions.cs index 29e50b84..93cefd6a 100644 --- a/SharpCompress/Common/ExtractOptions.cs +++ b/SharpCompress/Common/ExtractOptions.cs @@ -6,13 +6,15 @@ namespace SharpCompress.Common public enum ExtractOptions { None, + /// /// overwrite target if it exists /// Overwrite, + /// /// extract with internal directory structure /// ExtractFullPath, } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/ExtractionException.cs b/SharpCompress/Common/ExtractionException.cs index ca620ffb..15224d4d 100644 --- a/SharpCompress/Common/ExtractionException.cs +++ b/SharpCompress/Common/ExtractionException.cs @@ -1,5 +1,4 @@ - -using System; +using System; namespace SharpCompress.Common { @@ -9,9 +8,10 @@ namespace SharpCompress.Common : base(message) { } + public ExtractionException(string message, Exception inner) : base(message, inner) { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/FilePart.cs b/SharpCompress/Common/FilePart.cs index 29d7b9fe..c9bbd636 100644 --- a/SharpCompress/Common/FilePart.cs +++ b/SharpCompress/Common/FilePart.cs @@ -4,12 +4,9 @@ namespace SharpCompress.Common { public abstract class FilePart { - internal abstract string FilePartName - { - get; - } + internal abstract string FilePartName { get; } internal abstract Stream GetCompressedStream(); internal abstract Stream GetRawStream(); } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/FilePartExtractionBeginEventArgs.cs b/SharpCompress/Common/FilePartExtractionBeginEventArgs.cs index d295f066..b5742b6c 100644 --- a/SharpCompress/Common/FilePartExtractionBeginEventArgs.cs +++ b/SharpCompress/Common/FilePartExtractionBeginEventArgs.cs @@ -8,14 +8,15 @@ namespace SharpCompress.Common /// File name for the part for the current entry /// public string Name { get; internal set; } + /// /// Uncompressed size of the current entry in the part /// public long Size { get; internal set; } + /// /// Compressed size of the current entry in the part /// public long CompressedSize { get; internal set; } } - -} +} \ No newline at end of file diff --git a/SharpCompress/Common/FlagUtility.cs b/SharpCompress/Common/FlagUtility.cs index 92d9091a..bb8e406d 100644 --- a/SharpCompress/Common/FlagUtility.cs +++ b/SharpCompress/Common/FlagUtility.cs @@ -50,12 +50,12 @@ namespace SharpCompress.Common } #if PORTABLE - /// - /// Generically checks enums in a Windows Phone 7 enivronment - /// - /// - /// - /// + /// + /// Generically checks enums in a Windows Phone 7 enivronment + /// + /// + /// + /// public static bool HasFlag(this Enum enumVal, Enum flag) { if (enumVal.GetHashCode() > 0) //GetHashCode returns the enum value. But it's something very crazy if not set beforehand @@ -71,12 +71,12 @@ namespace SharpCompress.Common #endif #if THREEFIVE - /// - /// Generically checks enums in a .NET 3.5 - /// - /// - /// - /// + /// + /// Generically checks enums in a .NET 3.5 + /// + /// + /// + /// public static bool HasFlag(this Enum enumVal, Enum flag) { return (Convert.ToInt32(enumVal) & Convert.ToInt32(flag)) == Convert.ToInt32(flag); @@ -145,4 +145,4 @@ namespace SharpCompress.Common return SetFlag(bitField.ToInt64(null), flag, @on); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/GZip/GZipFilePart.cs b/SharpCompress/Common/GZip/GZipFilePart.cs index b1025c0a..5aab3dba 100644 --- a/SharpCompress/Common/GZip/GZipFilePart.cs +++ b/SharpCompress/Common/GZip/GZipFilePart.cs @@ -57,7 +57,7 @@ namespace SharpCompress.Common.GZip // read and discard extra field n = stream.Read(header, 0, 2); // 2-byte length field - Int16 extraLength = (Int16)(header[0] + header[1] * 256); + Int16 extraLength = (Int16) (header[0] + header[1]*256); byte[] extra = new byte[extraLength]; n = stream.Read(extra, 0, extra.Length); if (n != extraLength) @@ -100,4 +100,4 @@ namespace SharpCompress.Common.GZip return ArchiveEncoding.Default.GetString(a, 0, a.Length); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/GZip/GZipVolume.cs b/SharpCompress/Common/GZip/GZipVolume.cs index 5a948bcd..f5f40ad1 100644 --- a/SharpCompress/Common/GZip/GZipVolume.cs +++ b/SharpCompress/Common/GZip/GZipVolume.cs @@ -27,27 +27,18 @@ namespace SharpCompress.Common.GZip /// public override FileInfo VolumeFile { - get - { - return fileInfo; - } + get { return fileInfo; } } #endif public override bool IsFirstVolume { - get - { - return true; - } + get { return true; } } public override bool IsMultiVolume { - get - { - return true; - } + get { return true; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/GenericVolume.cs b/SharpCompress/Common/GenericVolume.cs index b1ed6a04..30547c19 100644 --- a/SharpCompress/Common/GenericVolume.cs +++ b/SharpCompress/Common/GenericVolume.cs @@ -27,27 +27,18 @@ namespace SharpCompress.Common /// public override FileInfo VolumeFile { - get - { - return fileInfo; - } + get { return fileInfo; } } #endif public override bool IsFirstVolume { - get - { - return true; - } + get { return true; } } public override bool IsMultiVolume { - get - { - return true; - } + get { return true; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/IEntry.cs b/SharpCompress/Common/IEntry.cs index 04318110..78080e0c 100644 --- a/SharpCompress/Common/IEntry.cs +++ b/SharpCompress/Common/IEntry.cs @@ -4,53 +4,17 @@ namespace SharpCompress.Common { public interface IEntry { - CompressionType CompressionType - { - get; - } - DateTime? ArchivedTime - { - get; - } - long CompressedSize - { - get; - } - uint Crc - { - get; - } - DateTime? CreatedTime - { - get; - } - string FilePath - { - get; - } - bool IsDirectory - { - get; - } - bool IsEncrypted - { - get; - } - bool IsSplit - { - get; - } - DateTime? LastAccessedTime - { - get; - } - DateTime? LastModifiedTime - { - get; - } - long Size - { - get; - } + CompressionType CompressionType { get; } + DateTime? ArchivedTime { get; } + long CompressedSize { get; } + uint Crc { get; } + DateTime? CreatedTime { get; } + string FilePath { get; } + bool IsDirectory { get; } + bool IsEncrypted { get; } + bool IsSplit { get; } + DateTime? LastAccessedTime { get; } + DateTime? LastModifiedTime { get; } + long Size { get; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/IStreamListener.cs b/SharpCompress/Common/IStreamListener.cs index 979d12ba..ce83e26d 100644 --- a/SharpCompress/Common/IStreamListener.cs +++ b/SharpCompress/Common/IStreamListener.cs @@ -1,9 +1,8 @@ - -namespace SharpCompress.Common +namespace SharpCompress.Common { internal interface IStreamListener { void FireFilePartExtractionBegin(string name, long size, long compressedSize); void FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes); } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/IVolume.cs b/SharpCompress/Common/IVolume.cs index 1f98446b..eb9bf5ff 100644 --- a/SharpCompress/Common/IVolume.cs +++ b/SharpCompress/Common/IVolume.cs @@ -1,6 +1,7 @@ using System; #if !PORTABLE using System.IO; + #endif namespace SharpCompress.Common @@ -11,10 +12,7 @@ namespace SharpCompress.Common /// /// File that backs this volume, if it not stream based /// - FileInfo VolumeFile - { - get; - } + FileInfo VolumeFile { get; } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/IncompleteArchiveException.cs b/SharpCompress/Common/IncompleteArchiveException.cs index a90b60af..21b24cfd 100644 --- a/SharpCompress/Common/IncompleteArchiveException.cs +++ b/SharpCompress/Common/IncompleteArchiveException.cs @@ -1,5 +1,4 @@ - -namespace SharpCompress.Common +namespace SharpCompress.Common { public class IncompleteArchiveException : ArchiveException { @@ -8,4 +7,4 @@ namespace SharpCompress.Common { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/InvalidFormatException.cs b/SharpCompress/Common/InvalidFormatException.cs index c29ea2ca..d0b16865 100644 --- a/SharpCompress/Common/InvalidFormatException.cs +++ b/SharpCompress/Common/InvalidFormatException.cs @@ -14,4 +14,4 @@ namespace SharpCompress.Common { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/MultiVolumeExtractionException.cs b/SharpCompress/Common/MultiVolumeExtractionException.cs index 9b3afa79..a0ea22ac 100644 --- a/SharpCompress/Common/MultiVolumeExtractionException.cs +++ b/SharpCompress/Common/MultiVolumeExtractionException.cs @@ -8,9 +8,10 @@ namespace SharpCompress.Common : base(message) { } + public MultiVolumeExtractionException(string message, Exception inner) : base(message, inner) { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/MultipartStreamRequiredException.cs b/SharpCompress/Common/MultipartStreamRequiredException.cs index 62f39a36..2c441407 100644 --- a/SharpCompress/Common/MultipartStreamRequiredException.cs +++ b/SharpCompress/Common/MultipartStreamRequiredException.cs @@ -1,5 +1,4 @@ - -namespace SharpCompress.Common +namespace SharpCompress.Common { public class MultipartStreamRequiredException : ExtractionException { @@ -8,4 +7,4 @@ namespace SharpCompress.Common { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Options.cs b/SharpCompress/Common/Options.cs index e9c1bab1..d7d4b372 100644 --- a/SharpCompress/Common/Options.cs +++ b/SharpCompress/Common/Options.cs @@ -9,13 +9,15 @@ namespace SharpCompress.Common /// No options specified /// None = 0, + /// /// SharpCompress will keep the supplied streams open /// KeepStreamsOpen = 1, + /// /// Look for RarArchive (Check for self-extracting archives or cases where RarArchive isn't at the start of the file) /// LookForHeader = 2, } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/PasswordProtectedException.cs b/SharpCompress/Common/PasswordProtectedException.cs index e8d1fc09..cfd3a809 100644 --- a/SharpCompress/Common/PasswordProtectedException.cs +++ b/SharpCompress/Common/PasswordProtectedException.cs @@ -8,9 +8,10 @@ namespace SharpCompress.Common : base(message) { } + public PasswordProtectedException(string message, Exception inner) : base(message, inner) { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/AVHeader.cs b/SharpCompress/Common/Rar/Headers/AVHeader.cs index 9df2b199..d3ff7580 100644 --- a/SharpCompress/Common/Rar/Headers/AVHeader.cs +++ b/SharpCompress/Common/Rar/Headers/AVHeader.cs @@ -11,22 +11,10 @@ namespace SharpCompress.Common.Rar.Headers UserNameSize = reader.ReadInt16(); } - internal int CreationTime - { - get; - private set; - } + internal int CreationTime { get; private set; } - internal short ArcNameSize - { - get; - private set; - } + internal short ArcNameSize { get; private set; } - internal short UserNameSize - { - get; - private set; - } + internal short UserNameSize { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs b/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs index 59fafd6c..57ee6a8b 100644 --- a/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs +++ b/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs @@ -19,28 +19,13 @@ namespace SharpCompress.Common.Rar.Headers internal ArchiveFlags ArchiveHeaderFlags { - get - { - return (ArchiveFlags)base.Flags; - } + get { return (ArchiveFlags) base.Flags; } } - internal short HighPosAv - { - get; - private set; - } + internal short HighPosAv { get; private set; } - internal int PosAv - { - get; - private set; - } + internal int PosAv { get; private set; } - internal byte EncryptionVersion - { - get; - private set; - } + internal byte EncryptionVersion { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/CommentHeader.cs b/SharpCompress/Common/Rar/Headers/CommentHeader.cs index 5cec48cb..b170e6e4 100644 --- a/SharpCompress/Common/Rar/Headers/CommentHeader.cs +++ b/SharpCompress/Common/Rar/Headers/CommentHeader.cs @@ -12,27 +12,11 @@ namespace SharpCompress.Common.Rar.Headers CommCRC = reader.ReadInt16(); } - internal short UnpSize - { - get; - private set; - } + internal short UnpSize { get; private set; } - internal byte UnpVersion - { - get; - private set; - } + internal byte UnpVersion { get; private set; } - internal byte UnpMethod - { - get; - private set; - } - internal short CommCRC - { - get; - private set; - } + internal byte UnpMethod { get; private set; } + internal short CommCRC { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs b/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs index 5a5ac245..7ae9c06e 100644 --- a/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs +++ b/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs @@ -18,22 +18,11 @@ namespace SharpCompress.Common.Rar.Headers internal EndArchiveFlags EndArchiveFlags { - get - { - return (EndArchiveFlags)base.Flags; - } + get { return (EndArchiveFlags) base.Flags; } } - internal int? ArchiveCRC - { - get; - private set; - } + internal int? ArchiveCRC { get; private set; } - internal short? VolumeNumber - { - get; - private set; - } + internal short? VolumeNumber { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/FileHeader.cs b/SharpCompress/Common/Rar/Headers/FileHeader.cs index fa44ef25..8b078335 100644 --- a/SharpCompress/Common/Rar/Headers/FileHeader.cs +++ b/SharpCompress/Common/Rar/Headers/FileHeader.cs @@ -15,7 +15,7 @@ namespace SharpCompress.Common.Rar.Headers { uint lowUncompressedSize = reader.ReadUInt32(); - HostOS = (HostOS)(int)reader.ReadByte(); + HostOS = (HostOS) (int) reader.ReadByte(); FileCRC = reader.ReadUInt32(); @@ -39,16 +39,14 @@ namespace SharpCompress.Common.Rar.Headers { if (lowUncompressedSize == 0xffffffff) { - lowUncompressedSize = 0xffffffff; highUncompressedkSize = int.MaxValue; } - } CompressedSize = UInt32To64(highCompressedSize, AdditionalSize); UncompressedSize = UInt32To64(highUncompressedkSize, lowUncompressedSize); - nameSize = nameSize > 4 * 1024 ? (short)(4 * 1024) : nameSize; + nameSize = nameSize > 4*1024 ? (short) (4*1024) : nameSize; byte[] fileNameBytes = reader.ReadBytes(nameSize); @@ -60,7 +58,7 @@ namespace SharpCompress.Common.Rar.Headers { int length = 0; while (length < fileNameBytes.Length - && fileNameBytes[length] != 0) + && fileNameBytes[length] != 0) { length++; } @@ -96,7 +94,7 @@ namespace SharpCompress.Common.Rar.Headers if (NewSubHeaderType.SUBHEAD_TYPE_RR.Equals(fileNameBytes)) { RecoverySectors = SubData[8] + (SubData[9] << 8) - + (SubData[10] << 16) + (SubData[11] << 24); + + (SubData[10] << 16) + (SubData[11] << 24); } } break; @@ -129,9 +127,10 @@ namespace SharpCompress.Common.Rar.Headers return l + y; } - private static DateTime? ProcessExtendedTime(ushort extendedFlags, DateTime? time, MarkingBinaryReader reader, int i) + private static DateTime? ProcessExtendedTime(ushort extendedFlags, DateTime? time, MarkingBinaryReader reader, + int i) { - uint rmode = (uint)extendedFlags >> (3 - i) * 4; + uint rmode = (uint) extendedFlags >> (3 - i)*4; if ((rmode & 8) == 0) { return null; @@ -146,14 +145,14 @@ namespace SharpCompress.Common.Rar.Headers time = time.Value.AddSeconds(1); } uint nanosecondHundreds = 0; - int count = (int)rmode & 3; + int count = (int) rmode & 3; for (int j = 0; j < count; j++) { byte b = reader.ReadByte(); - nanosecondHundreds |= (((uint)b) << ((j + 3 - count) * 8)); + nanosecondHundreds |= (((uint) b) << ((j + 3 - count)*8)); } //10^-7 to 10^-3 - return time.Value.AddMilliseconds(nanosecondHundreds * Math.Pow(10, -4)); + return time.Value.AddMilliseconds(nanosecondHundreds*Math.Pow(10, -4)); } private static string ConvertPath(string path, HostOS os) @@ -185,117 +184,46 @@ namespace SharpCompress.Common.Rar.Headers #endif } - internal long DataStartPosition - { - get; - set; - } - internal HostOS HostOS - { - get; - private set; - } + internal long DataStartPosition { get; set; } + internal HostOS HostOS { get; private set; } - internal uint FileCRC - { - get; - private set; - } + internal uint FileCRC { get; private set; } - internal DateTime? FileLastModifiedTime - { - get; - private set; - } + internal DateTime? FileLastModifiedTime { get; private set; } - internal DateTime? FileCreatedTime - { - get; - private set; - } + internal DateTime? FileCreatedTime { get; private set; } - internal DateTime? FileLastAccessedTime - { - get; - private set; - } + internal DateTime? FileLastAccessedTime { get; private set; } - internal DateTime? FileArchivedTime - { - get; - private set; - } + internal DateTime? FileArchivedTime { get; private set; } - internal byte RarVersion - { - get; - private set; - } + internal byte RarVersion { get; private set; } - internal byte PackingMethod - { - get; - private set; - } + internal byte PackingMethod { get; private set; } - internal int FileAttributes - { - get; - private set; - } + internal int FileAttributes { get; private set; } internal FileFlags FileFlags { - get - { - return (FileFlags)base.Flags; - } + get { return (FileFlags) base.Flags; } } - internal long CompressedSize - { - get; - private set; - } - internal long UncompressedSize - { - get; - private set; - } + internal long CompressedSize { get; private set; } + internal long UncompressedSize { get; private set; } - internal string FileName - { - get; - private set; - } + internal string FileName { get; private set; } - internal byte[] SubData - { - get; - private set; - } + internal byte[] SubData { get; private set; } - internal int RecoverySectors - { - get; - private set; - } + internal int RecoverySectors { get; private set; } - internal byte[] Salt - { - get; - private set; - } + internal byte[] Salt { get; private set; } public override string ToString() { return FileName; } - public Stream PackedStream - { - get; - set; - } + public Stream PackedStream { get; set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/FileNameDecoder.cs b/SharpCompress/Common/Rar/Headers/FileNameDecoder.cs index 5561497b..97d6644a 100644 --- a/SharpCompress/Common/Rar/Headers/FileNameDecoder.cs +++ b/SharpCompress/Common/Rar/Headers/FileNameDecoder.cs @@ -31,21 +31,20 @@ namespace SharpCompress.Common.Rar.Headers } switch (flags >> 6) { - case 0: - buf.Append((char)(GetChar(name, encPos++))); + buf.Append((char) (GetChar(name, encPos++))); ++decPos; break; case 1: - buf.Append((char)(GetChar(name, encPos++) + (highByte << 8))); + buf.Append((char) (GetChar(name, encPos++) + (highByte << 8))); ++decPos; break; case 2: low = GetChar(name, encPos); high = GetChar(name, encPos + 1); - buf.Append((char)((high << 8) + low)); + buf.Append((char) ((high << 8) + low)); ++decPos; encPos += 2; break; @@ -58,14 +57,14 @@ namespace SharpCompress.Common.Rar.Headers for (length = (length & 0x7f) + 2; length > 0 && decPos < name.Length; length--, decPos++) { low = (GetChar(name, decPos) + correction) & 0xff; - buf.Append((char)((highByte << 8) + low)); + buf.Append((char) ((highByte << 8) + low)); } } else { for (length += 2; length > 0 && decPos < name.Length; length--, decPos++) { - buf.Append((char)(GetChar(name, decPos))); + buf.Append((char) (GetChar(name, decPos))); } } break; diff --git a/SharpCompress/Common/Rar/Headers/Flags.cs b/SharpCompress/Common/Rar/Headers/Flags.cs index 6d8f2256..477a096d 100644 --- a/SharpCompress/Common/Rar/Headers/Flags.cs +++ b/SharpCompress/Common/Rar/Headers/Flags.cs @@ -82,4 +82,4 @@ namespace SharpCompress.Common.Rar.Headers EARC_REVSPACE = 0x0004, EARC_VOLNUMBER = 0x0008, } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/MarkHeader.cs b/SharpCompress/Common/Rar/Headers/MarkHeader.cs index b354beeb..41214b46 100644 --- a/SharpCompress/Common/Rar/Headers/MarkHeader.cs +++ b/SharpCompress/Common/Rar/Headers/MarkHeader.cs @@ -4,7 +4,6 @@ namespace SharpCompress.Common.Rar.Headers { internal class MarkHeader : RarHeader { - protected override void ReadFromReader(MarkingBinaryReader reader) { } @@ -55,10 +54,6 @@ namespace SharpCompress.Common.Rar.Headers return valid; } - internal bool OldFormat - { - get; - private set; - } + internal bool OldFormat { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/NewSubHeader.cs b/SharpCompress/Common/Rar/Headers/NewSubHeader.cs index 6866da12..23bf6247 100644 --- a/SharpCompress/Common/Rar/Headers/NewSubHeader.cs +++ b/SharpCompress/Common/Rar/Headers/NewSubHeader.cs @@ -27,7 +27,7 @@ namespace SharpCompress.Common.Rar.Headers bytes = new byte[chars.Length]; for (int i = 0; i < chars.Length; ++i) { - bytes[i] = (byte)chars[i]; + bytes[i] = (byte) chars[i]; } } @@ -56,4 +56,4 @@ namespace SharpCompress.Common.Rar.Headers #endregion } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/RarHeader.cs b/SharpCompress/Common/Rar/Headers/RarHeader.cs index 1d9e76fc..260aef3f 100644 --- a/SharpCompress/Common/Rar/Headers/RarHeader.cs +++ b/SharpCompress/Common/Rar/Headers/RarHeader.cs @@ -39,7 +39,7 @@ namespace SharpCompress.Common.Rar.Headers protected virtual void ReadFromReader(MarkingBinaryReader reader) { HeadCRC = reader.ReadInt16(); - HeaderType = (HeaderType)(int)(reader.ReadByte() & 0xff); + HeaderType = (HeaderType) (int) (reader.ReadByte() & 0xff); Flags = reader.ReadInt16(); HeaderSize = reader.ReadInt16(); if (FlagUtility.HasFlag(Flags, LONG_BLOCK)) @@ -58,7 +58,7 @@ namespace SharpCompress.Common.Rar.Headers header.ReadFromReader(reader); header.ReadBytes += reader.CurrentReadByteCount; - int headerSizeDiff = header.HeaderSize - (int)header.ReadBytes; + int headerSizeDiff = header.HeaderSize - (int) header.ReadBytes; if (headerSizeDiff > 0) { @@ -75,46 +75,22 @@ namespace SharpCompress.Common.Rar.Headers /// /// This is the number of bytes read when reading the header /// - protected long ReadBytes - { - get; - private set; - } + protected long ReadBytes { get; private set; } - protected short HeadCRC - { - get; - private set; - } + protected short HeadCRC { get; private set; } - internal HeaderType HeaderType - { - get; - private set; - } + internal HeaderType HeaderType { get; private set; } /// /// Untyped flags. These should be typed when Promoting to another header /// - protected short Flags - { - get; - private set; - } + protected short Flags { get; private set; } - protected short HeaderSize - { - get; - private set; - } + protected short HeaderSize { get; private set; } /// /// This additional size of the header could be file data /// - protected uint AdditionalSize - { - get; - private set; - } + protected uint AdditionalSize { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs b/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs index ada1daa8..777d7d27 100644 --- a/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs +++ b/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs @@ -15,17 +15,9 @@ namespace SharpCompress.Common.Rar.Headers Options = options; } - private Options Options - { - get; - set; - } + private Options Options { get; set; } - internal StreamingMode StreamingMode - { - get; - private set; - } + internal StreamingMode StreamingMode { get; private set; } internal IEnumerable ReadHeaders(Stream stream) { @@ -197,4 +189,4 @@ namespace SharpCompress.Common.Rar.Headers } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/Headers/SignHeader.cs b/SharpCompress/Common/Rar/Headers/SignHeader.cs index 4e43eb72..8c0482c1 100644 --- a/SharpCompress/Common/Rar/Headers/SignHeader.cs +++ b/SharpCompress/Common/Rar/Headers/SignHeader.cs @@ -12,28 +12,12 @@ namespace SharpCompress.Common.Rar.Headers AVInfoCRC = reader.ReadInt32(); } - internal int AVInfoCRC - { - get; - private set; - } + internal int AVInfoCRC { get; private set; } - internal byte UnpackVersion - { - get; - private set; - } + internal byte UnpackVersion { get; private set; } - internal byte Method - { - get; - private set; - } + internal byte Method { get; private set; } - internal byte AVVersion - { - get; - private set; - } + internal byte AVVersion { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/RarFilePart.cs b/SharpCompress/Common/Rar/RarFilePart.cs index 2b7aa27d..a6ba8ec7 100644 --- a/SharpCompress/Common/Rar/RarFilePart.cs +++ b/SharpCompress/Common/Rar/RarFilePart.cs @@ -14,21 +14,13 @@ namespace SharpCompress.Common.Rar FileHeader = fh; } - internal MarkHeader MarkHeader - { - get; - private set; - } + internal MarkHeader MarkHeader { get; private set; } - internal FileHeader FileHeader - { - get; - private set; - } + internal FileHeader FileHeader { get; private set; } internal override Stream GetRawStream() { return null; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Rar/RarVolume.cs b/SharpCompress/Common/Rar/RarVolume.cs index 3d6a050a..1d5d0556 100644 --- a/SharpCompress/Common/Rar/RarVolume.cs +++ b/SharpCompress/Common/Rar/RarVolume.cs @@ -22,10 +22,7 @@ namespace SharpCompress.Common.Rar internal StreamingMode Mode { - get - { - return headerFactory.StreamingMode; - } + get { return headerFactory.StreamingMode; } } internal abstract IEnumerable ReadFileParts(); @@ -60,11 +57,7 @@ namespace SharpCompress.Common.Rar } } - internal ArchiveHeader ArchiveHeader - { - get; - private set; - } + internal ArchiveHeader ArchiveHeader { get; private set; } private void EnsureArchiveHeaderLoaded() { @@ -118,4 +111,4 @@ namespace SharpCompress.Common.Rar } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/ArchiveDatabase.cs b/SharpCompress/Common/SevenZip/ArchiveDatabase.cs index 0fe624f2..bee1e177 100644 --- a/SharpCompress/Common/SevenZip/ArchiveDatabase.cs +++ b/SharpCompress/Common/SevenZip/ArchiveDatabase.cs @@ -39,10 +39,10 @@ namespace SharpCompress.Common.SevenZip internal bool IsEmpty() { return PackSizes.Count == 0 - && PackCRCs.Count == 0 - && Folders.Count == 0 - && NumUnpackStreamsVector.Count == 0 - && Files.Count == 0; + && PackCRCs.Count == 0 + && Folders.Count == 0 + && NumUnpackStreamsVector.Count == 0 + && Files.Count == 0; } private void FillStartPos() @@ -158,4 +158,4 @@ namespace SharpCompress.Common.SevenZip return 0; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/ArchiveReader.cs b/SharpCompress/Common/SevenZip/ArchiveReader.cs index 3b45cef7..46e9e358 100644 --- a/SharpCompress/Common/SevenZip/ArchiveReader.cs +++ b/SharpCompress/Common/SevenZip/ArchiveReader.cs @@ -220,7 +220,11 @@ namespace SharpCompress.Common.SevenZip int idSize = (mainByte & 0xF); byte[] longID = new byte[idSize]; ReadBytes(longID, 0, idSize); - Log.WriteLine("MethodId: " + String.Join("", Enumerable.Range(0, idSize).Select(x => longID[x].ToString("x2")).ToArray())); + Log.WriteLine("MethodId: " + + String.Join("", + Enumerable.Range(0, idSize) + .Select(x => longID[x].ToString("x2")) + .ToArray())); if (idSize > 8) throw new NotSupportedException(); ulong id = 0; @@ -232,7 +236,8 @@ namespace SharpCompress.Common.SevenZip { coder.NumInStreams = ReadNum(); coder.NumOutStreams = ReadNum(); - Log.WriteLine("Complex Stream (In: " + coder.NumInStreams + " - Out: " + coder.NumOutStreams + ")"); + Log.WriteLine("Complex Stream (In: " + coder.NumInStreams + " - Out: " + coder.NumOutStreams + + ")"); } else { @@ -246,7 +251,8 @@ namespace SharpCompress.Common.SevenZip int propsSize = ReadNum(); coder.Props = new byte[propsSize]; ReadBytes(coder.Props, 0, propsSize); - Log.WriteLine("Settings: " + String.Join("", coder.Props.Select(bt => bt.ToString("x2")).ToArray())); + Log.WriteLine("Settings: " + + String.Join("", coder.Props.Select(bt => bt.ToString("x2")).ToArray())); } if ((mainByte & 0x80) != 0) @@ -255,7 +261,10 @@ namespace SharpCompress.Common.SevenZip numInStreams += coder.NumInStreams; numOutStreams += coder.NumOutStreams; } - finally { Log.PopIndent(); } + finally + { + Log.PopIndent(); + } } int numBindPairs = numOutStreams - 1; @@ -382,7 +391,10 @@ namespace SharpCompress.Common.SevenZip packCRCs.Add(null); } } - finally { Log.PopIndent(); } + finally + { + Log.PopIndent(); + } } private void ReadUnpackInfo(List dataVector, out List folders) @@ -445,10 +457,14 @@ namespace SharpCompress.Common.SevenZip SkipData(); } } - finally { Log.PopIndent(); } + finally + { + Log.PopIndent(); + } } - private void ReadSubStreamsInfo(List folders, out List numUnpackStreamsInFolders, out List unpackSizes, out List digests) + private void ReadSubStreamsInfo(List folders, out List numUnpackStreamsInFolders, + out List unpackSizes, out List digests) { Log.WriteLine("-- ReadSubStreamsInfo --"); Log.PushIndent(); @@ -571,18 +587,21 @@ namespace SharpCompress.Common.SevenZip type = ReadId(); } } - finally { Log.PopIndent(); } + finally + { + Log.PopIndent(); + } } private void ReadStreamsInfo( - List dataVector, - out long dataOffset, - out List packSizes, - out List packCRCs, - out List folders, - out List numUnpackStreamsInFolders, - out List unpackSizes, - out List digests) + List dataVector, + out long dataOffset, + out List packSizes, + out List packCRCs, + out List folders, + out List numUnpackStreamsInFolders, + out List unpackSizes, + out List digests) { Log.WriteLine("-- ReadStreamsInfo --"); Log.PushIndent(); @@ -616,7 +635,10 @@ namespace SharpCompress.Common.SevenZip } } } - finally { Log.PopIndent(); } + finally + { + Log.PopIndent(); + } } private List ReadAndDecodePackedStreams(long baseOffset, IPasswordProvider pass) @@ -657,7 +679,8 @@ namespace SharpCompress.Common.SevenZip dataStartPos += packSize; } - var outStream = DecoderStreamHelper.CreateDecoderStream(_stream, oldDataStartPos, myPackSizes, folder, pass); + var outStream = DecoderStreamHelper.CreateDecoderStream(_stream, oldDataStartPos, myPackSizes, + folder, pass); int unpackSize = checked((int)folder.GetUnpackSize()); byte[] data = new byte[unpackSize]; @@ -672,7 +695,10 @@ namespace SharpCompress.Common.SevenZip } return dataVector; } - finally { Log.PopIndent(); } + finally + { + Log.PopIndent(); + } } private void ReadHeader(ArchiveDatabase db, IPasswordProvider getTextPassword) @@ -772,10 +798,13 @@ namespace SharpCompress.Common.SevenZip case BlockType.WinAttributes: Log.Write("WinAttributes:"); ReadAttributeVector(dataVector, numFiles, delegate(int i, uint? attr) - { - db.Files[i].Attrib = attr; - Log.Write(" " + (attr.HasValue ? attr.Value.ToString("x8") : "n/a")); - }); + { + db.Files[i].Attrib = attr; + Log.Write(" " + + (attr.HasValue + ? attr.Value.ToString("x8") + : "n/a")); + }); Log.WriteLine(); break; case BlockType.EmptyStream: @@ -816,37 +845,49 @@ namespace SharpCompress.Common.SevenZip case BlockType.StartPos: Log.Write("StartPos:"); ReadNumberVector(dataVector, numFiles, delegate(int i, long? startPos) - { - db.Files[i].StartPos = startPos; - Log.Write(" " + (startPos.HasValue ? startPos.Value.ToString() : "n/a")); - }); + { + db.Files[i].StartPos = startPos; + Log.Write(" " + + (startPos.HasValue + ? startPos.Value.ToString() + : "n/a")); + }); Log.WriteLine(); break; case BlockType.CTime: Log.Write("CTime:"); ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) - { - db.Files[i].CTime = time; - Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); - }); + { + db.Files[i].CTime = time; + Log.Write(" " + + (time.HasValue + ? time.Value.ToString() + : "n/a")); + }); Log.WriteLine(); break; case BlockType.ATime: Log.Write("ATime:"); ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) - { - db.Files[i].ATime = time; - Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); - }); + { + db.Files[i].ATime = time; + Log.Write(" " + + (time.HasValue + ? time.Value.ToString() + : "n/a")); + }); Log.WriteLine(); break; case BlockType.MTime: Log.Write("MTime:"); ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) - { - db.Files[i].MTime = time; - Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); - }); + { + db.Files[i].MTime = time; + Log.Write(" " + + (time.HasValue + ? time.Value.ToString() + : "n/a")); + }); Log.WriteLine(); break; case BlockType.Dummy: @@ -890,7 +931,10 @@ namespace SharpCompress.Common.SevenZip } } } - finally { Log.PopIndent(); } + finally + { + Log.PopIndent(); + } } #endregion @@ -1016,6 +1060,7 @@ namespace SharpCompress.Common.SevenZip internal int FileIndex; internal int FolderIndex; internal List ExtractStatuses = new List(); + internal CExtractFolderInfo(int fileIndex, int folderIndex) { FileIndex = fileIndex; @@ -1069,14 +1114,8 @@ namespace SharpCompress.Common.SevenZip public override long Position { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) @@ -1097,6 +1136,7 @@ namespace SharpCompress.Common.SevenZip private Stream _stream; private long _rem; private int _currentIndex; + private void ProcessEmptyFiles() { while (_currentIndex < _extractStatuses.Count && _db.Files[_startIndex + _currentIndex].Size == 0) @@ -1107,6 +1147,7 @@ namespace SharpCompress.Common.SevenZip _currentIndex++; } } + private void OpenFile() { bool skip = !_extractStatuses[_currentIndex]; @@ -1122,6 +1163,7 @@ namespace SharpCompress.Common.SevenZip _stream = new MemoryStream(); _rem = _db.Files[index].Size; } + public override void Write(byte[] buffer, int offset, int count) { while (count != 0) @@ -1172,7 +1214,8 @@ namespace SharpCompress.Common.SevenZip for (int j = 0; j < folderInfo.PackStreams.Count; j++) packSizes.Add(_db.PackSizes[packStreamIndex + j]); - s = DecoderStreamHelper.CreateDecoderStream(_stream, folderStartPackPos, packSizes.ToArray(), folderInfo, pw); + s = DecoderStreamHelper.CreateDecoderStream(_stream, folderStartPackPos, packSizes.ToArray(), folderInfo, + pw); _cachedStreams.Add(folderIndex, s); } return s; @@ -1255,7 +1298,8 @@ namespace SharpCompress.Common.SevenZip // TODO: If the decoding fails the last file may be extracted incompletely. Delete it? - Stream s = DecoderStreamHelper.CreateDecoderStream(_stream, folderStartPackPos, packSizes.ToArray(), folderInfo, pw); + Stream s = DecoderStreamHelper.CreateDecoderStream(_stream, folderStartPackPos, packSizes.ToArray(), + folderInfo, pw); byte[] buffer = new byte[4 << 10]; for (; ; ) { diff --git a/SharpCompress/Common/SevenZip/CBindPair.cs b/SharpCompress/Common/SevenZip/CBindPair.cs index 20831537..6956ef6f 100644 --- a/SharpCompress/Common/SevenZip/CBindPair.cs +++ b/SharpCompress/Common/SevenZip/CBindPair.cs @@ -1,8 +1,8 @@ namespace SharpCompress.Common.SevenZip { - internal class CBindPair - { - internal int InIndex; - internal int OutIndex; - } + internal class CBindPair + { + internal int InIndex; + internal int OutIndex; + } } \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/CCoderInfo.cs b/SharpCompress/Common/SevenZip/CCoderInfo.cs index d3a38ff2..abe11ae4 100644 --- a/SharpCompress/Common/SevenZip/CCoderInfo.cs +++ b/SharpCompress/Common/SevenZip/CCoderInfo.cs @@ -1,10 +1,10 @@ namespace SharpCompress.Common.SevenZip { - internal class CCoderInfo - { - internal CMethodId MethodId; - internal byte[] Props; - internal int NumInStreams; - internal int NumOutStreams; - } + internal class CCoderInfo + { + internal CMethodId MethodId; + internal byte[] Props; + internal int NumInStreams; + internal int NumOutStreams; + } } \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/CFileItem.cs b/SharpCompress/Common/SevenZip/CFileItem.cs index fca9d3db..92d72354 100644 --- a/SharpCompress/Common/SevenZip/CFileItem.cs +++ b/SharpCompress/Common/SevenZip/CFileItem.cs @@ -11,8 +11,16 @@ namespace SharpCompress.Common.SevenZip public bool HasStream { get; internal set; } public bool IsDir { get; internal set; } - public bool CrcDefined { get { return Crc != null; } } - public bool AttribDefined { get { return Attrib != null; } } + + public bool CrcDefined + { + get { return Crc != null; } + } + + public bool AttribDefined + { + get { return Attrib != null; } + } public void SetAttrib(uint attrib) { diff --git a/SharpCompress/Common/SevenZip/CFolder.cs b/SharpCompress/Common/SevenZip/CFolder.cs index 8613a750..c83bc4df 100644 --- a/SharpCompress/Common/SevenZip/CFolder.cs +++ b/SharpCompress/Common/SevenZip/CFolder.cs @@ -4,132 +4,136 @@ using SharpCompress.Compressor.LZMA; namespace SharpCompress.Common.SevenZip { - internal class CFolder - { - internal List Coders = new List(); - internal List BindPairs = new List(); - internal List PackStreams = new List(); - internal int FirstPackStreamId; - internal List UnpackSizes = new List(); - internal uint? UnpackCRC; - internal bool UnpackCRCDefined { get { return UnpackCRC != null; } } + internal class CFolder + { + internal List Coders = new List(); + internal List BindPairs = new List(); + internal List PackStreams = new List(); + internal int FirstPackStreamId; + internal List UnpackSizes = new List(); + internal uint? UnpackCRC; - public long GetUnpackSize() - { - if(UnpackSizes.Count == 0) - return 0; + internal bool UnpackCRCDefined + { + get { return UnpackCRC != null; } + } - for(int i = UnpackSizes.Count - 1; i >= 0; i--) - if(FindBindPairForOutStream(i) < 0) - return UnpackSizes[i]; + public long GetUnpackSize() + { + if (UnpackSizes.Count == 0) + return 0; - throw new Exception(); - } + for (int i = UnpackSizes.Count - 1; i >= 0; i--) + if (FindBindPairForOutStream(i) < 0) + return UnpackSizes[i]; - public int GetNumOutStreams() - { - int count = 0; - for(int i = 0; i < Coders.Count; i++) - count += Coders[i].NumOutStreams; + throw new Exception(); + } - return count; - } + public int GetNumOutStreams() + { + int count = 0; + for (int i = 0; i < Coders.Count; i++) + count += Coders[i].NumOutStreams; - public int FindBindPairForInStream(int inStreamIndex) - { - for(int i = 0; i < BindPairs.Count; i++) - if(BindPairs[i].InIndex == inStreamIndex) - return i; + return count; + } - return -1; - } + public int FindBindPairForInStream(int inStreamIndex) + { + for (int i = 0; i < BindPairs.Count; i++) + if (BindPairs[i].InIndex == inStreamIndex) + return i; - public int FindBindPairForOutStream(int outStreamIndex) - { - for(int i = 0; i < BindPairs.Count; i++) - if(BindPairs[i].OutIndex == outStreamIndex) - return i; + return -1; + } - return -1; - } + public int FindBindPairForOutStream(int outStreamIndex) + { + for (int i = 0; i < BindPairs.Count; i++) + if (BindPairs[i].OutIndex == outStreamIndex) + return i; - public int FindPackStreamArrayIndex(int inStreamIndex) - { - for(int i = 0; i < PackStreams.Count; i++) - if(PackStreams[i] == inStreamIndex) - return i; + return -1; + } - return -1; - } + public int FindPackStreamArrayIndex(int inStreamIndex) + { + for (int i = 0; i < PackStreams.Count; i++) + if (PackStreams[i] == inStreamIndex) + return i; - public bool IsEncrypted() - { - for(int i = Coders.Count - 1; i >= 0; i--) - if(Coders[i].MethodId == CMethodId.kAES) - return true; + return -1; + } - return false; - } + public bool IsEncrypted() + { + for (int i = Coders.Count - 1; i >= 0; i--) + if (Coders[i].MethodId == CMethodId.kAES) + return true; - public bool CheckStructure() - { - const int kNumCodersMax = 32; // don't change it - const int kMaskSize = 32; // it must be >= kNumCodersMax - const int kNumBindsMax = 32; - - if(Coders.Count > kNumCodersMax || BindPairs.Count > kNumBindsMax) return false; + } - { - var v = new BitVector(BindPairs.Count + PackStreams.Count); + public bool CheckStructure() + { + const int kNumCodersMax = 32; // don't change it + const int kMaskSize = 32; // it must be >= kNumCodersMax + const int kNumBindsMax = 32; - for(int i = 0; i < BindPairs.Count; i++) - if(v.GetAndSet(BindPairs[i].InIndex)) - return false; + if (Coders.Count > kNumCodersMax || BindPairs.Count > kNumBindsMax) + return false; - for(int i = 0; i < PackStreams.Count; i++) - if(v.GetAndSet(PackStreams[i])) - return false; - } - - { - var v = new BitVector(UnpackSizes.Count); - for(int i = 0; i < BindPairs.Count; i++) - if(v.GetAndSet(BindPairs[i].OutIndex)) - return false; - } - - uint[] mask = new uint[kMaskSize]; - - { - List inStreamToCoder = new List(); - List outStreamToCoder = new List(); - for(int i = 0; i < Coders.Count; i++) { - CCoderInfo coder = Coders[i]; - for(int j = 0; j < coder.NumInStreams; j++) - inStreamToCoder.Add(i); - for(int j = 0; j < coder.NumOutStreams; j++) - outStreamToCoder.Add(i); + var v = new BitVector(BindPairs.Count + PackStreams.Count); + + for (int i = 0; i < BindPairs.Count; i++) + if (v.GetAndSet(BindPairs[i].InIndex)) + return false; + + for (int i = 0; i < PackStreams.Count; i++) + if (v.GetAndSet(PackStreams[i])) + return false; } - for(int i = 0; i < BindPairs.Count; i++) { - CBindPair bp = BindPairs[i]; - mask[inStreamToCoder[bp.InIndex]] |= (1u << outStreamToCoder[bp.OutIndex]); + var v = new BitVector(UnpackSizes.Count); + for (int i = 0; i < BindPairs.Count; i++) + if (v.GetAndSet(BindPairs[i].OutIndex)) + return false; } - } - for(int i = 0; i < kMaskSize; i++) - for(int j = 0; j < kMaskSize; j++) - if(((1u << j) & mask[i]) != 0) - mask[i] |= mask[j]; + uint[] mask = new uint[kMaskSize]; - for(int i = 0; i < kMaskSize; i++) - if(((1u << i) & mask[i]) != 0) - return false; + { + List inStreamToCoder = new List(); + List outStreamToCoder = new List(); + for (int i = 0; i < Coders.Count; i++) + { + CCoderInfo coder = Coders[i]; + for (int j = 0; j < coder.NumInStreams; j++) + inStreamToCoder.Add(i); + for (int j = 0; j < coder.NumOutStreams; j++) + outStreamToCoder.Add(i); + } - return true; - } - } + for (int i = 0; i < BindPairs.Count; i++) + { + CBindPair bp = BindPairs[i]; + mask[inStreamToCoder[bp.InIndex]] |= (1u << outStreamToCoder[bp.OutIndex]); + } + } + + for (int i = 0; i < kMaskSize; i++) + for (int j = 0; j < kMaskSize; j++) + if (((1u << j) & mask[i]) != 0) + mask[i] |= mask[j]; + + for (int i = 0; i < kMaskSize; i++) + if (((1u << i) & mask[i]) != 0) + return false; + + return true; + } + } } \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/CMethodId.cs b/SharpCompress/Common/SevenZip/CMethodId.cs index e0944d38..ebf1b52a 100644 --- a/SharpCompress/Common/SevenZip/CMethodId.cs +++ b/SharpCompress/Common/SevenZip/CMethodId.cs @@ -26,7 +26,7 @@ public override bool Equals(object obj) { - return obj is CMethodId && (CMethodId)obj == this; + return obj is CMethodId && (CMethodId) obj == this; } public bool Equals(CMethodId other) @@ -47,9 +47,9 @@ public int GetLength() { int bytes = 0; - for(ulong value = Id; value != 0; value >>= 8) + for (ulong value = Id; value != 0; value >>= 8) bytes++; return bytes; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/CStreamSwitch.cs b/SharpCompress/Common/SevenZip/CStreamSwitch.cs index af837932..ed639a21 100644 --- a/SharpCompress/Common/SevenZip/CStreamSwitch.cs +++ b/SharpCompress/Common/SevenZip/CStreamSwitch.cs @@ -5,58 +5,58 @@ using SharpCompress.Compressor.LZMA; namespace SharpCompress.Common.SevenZip { - internal struct CStreamSwitch: IDisposable - { - private ArchiveReader _archive; - private bool _needRemove; - private bool _active; + internal struct CStreamSwitch : IDisposable + { + private ArchiveReader _archive; + private bool _needRemove; + private bool _active; - public void Dispose() - { - if(_active) - { - _active = false; - Log.WriteLine("[end of switch]"); - } + public void Dispose() + { + if (_active) + { + _active = false; + Log.WriteLine("[end of switch]"); + } - if(_needRemove) - { - _needRemove = false; - _archive.DeleteByteStream(); - } - } + if (_needRemove) + { + _needRemove = false; + _archive.DeleteByteStream(); + } + } - public void Set(ArchiveReader archive, byte[] dataVector) - { - Dispose(); - _archive = archive; - _archive.AddByteStream(dataVector, 0, dataVector.Length); - _needRemove = true; - _active = true; - } - - public void Set(ArchiveReader archive, List dataVector) - { - Dispose(); - _active = true; - - byte external = archive.ReadByte(); - if(external != 0) - { - int dataIndex = archive.ReadNum(); - if(dataIndex < 0 || dataIndex >= dataVector.Count) - throw new InvalidOperationException(); - - Log.WriteLine("[switch to stream {0}]", dataIndex); + public void Set(ArchiveReader archive, byte[] dataVector) + { + Dispose(); _archive = archive; - _archive.AddByteStream(dataVector[dataIndex], 0, dataVector[dataIndex].Length); + _archive.AddByteStream(dataVector, 0, dataVector.Length); _needRemove = true; _active = true; - } - else - { - Log.WriteLine("[inline data]"); - } - } - } + } + + public void Set(ArchiveReader archive, List dataVector) + { + Dispose(); + _active = true; + + byte external = archive.ReadByte(); + if (external != 0) + { + int dataIndex = archive.ReadNum(); + if (dataIndex < 0 || dataIndex >= dataVector.Count) + throw new InvalidOperationException(); + + Log.WriteLine("[switch to stream {0}]", dataIndex); + _archive = archive; + _archive.AddByteStream(dataVector[dataIndex], 0, dataVector[dataIndex].Length); + _needRemove = true; + _active = true; + } + else + { + Log.WriteLine("[inline data]"); + } + } + } } \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/DataReader.cs b/SharpCompress/Common/SevenZip/DataReader.cs index 34e43bc3..ddc43d60 100644 --- a/SharpCompress/Common/SevenZip/DataReader.cs +++ b/SharpCompress/Common/SevenZip/DataReader.cs @@ -5,164 +5,164 @@ using SharpCompress.Compressor.LZMA; namespace SharpCompress.Common.SevenZip { - internal class DataReader - { - #region Static Methods + internal class DataReader + { + #region Static Methods - public static uint Get32(byte[] buffer, int offset) - { - return (uint)buffer[offset] - + ((uint)buffer[offset + 1] << 8) - + ((uint)buffer[offset + 2] << 16) - + ((uint)buffer[offset + 3] << 24); - } + public static uint Get32(byte[] buffer, int offset) + { + return (uint) buffer[offset] + + ((uint) buffer[offset + 1] << 8) + + ((uint) buffer[offset + 2] << 16) + + ((uint) buffer[offset + 3] << 24); + } - public static ulong Get64(byte[] buffer, int offset) - { - return (ulong)buffer[offset] - + ((ulong)buffer[offset + 1] << 8) - + ((ulong)buffer[offset + 2] << 16) - + ((ulong)buffer[offset + 3] << 24) - + ((ulong)buffer[offset + 4] << 32) - + ((ulong)buffer[offset + 5] << 40) - + ((ulong)buffer[offset + 6] << 48) - + ((ulong)buffer[offset + 7] << 56); - } + public static ulong Get64(byte[] buffer, int offset) + { + return (ulong) buffer[offset] + + ((ulong) buffer[offset + 1] << 8) + + ((ulong) buffer[offset + 2] << 16) + + ((ulong) buffer[offset + 3] << 24) + + ((ulong) buffer[offset + 4] << 32) + + ((ulong) buffer[offset + 5] << 40) + + ((ulong) buffer[offset + 6] << 48) + + ((ulong) buffer[offset + 7] << 56); + } - #endregion + #endregion - #region Variables + #region Variables - private byte[] _buffer; - private int _origin; - private int _offset; - private int _ending; + private byte[] _buffer; + private int _origin; + private int _offset; + private int _ending; - #endregion + #endregion - #region Public Methods + #region Public Methods - public DataReader(byte[] buffer, int offset, int length) - { - _buffer = buffer; - _origin = offset; - _offset = offset; - _ending = offset + length; - } + public DataReader(byte[] buffer, int offset, int length) + { + _buffer = buffer; + _origin = offset; + _offset = offset; + _ending = offset + length; + } - public int Offset - { - get { return _offset; } - } + public int Offset + { + get { return _offset; } + } - public Byte ReadByte() - { - if(_offset >= _ending) - throw new EndOfStreamException(); + public Byte ReadByte() + { + if (_offset >= _ending) + throw new EndOfStreamException(); - return _buffer[_offset++]; - } + return _buffer[_offset++]; + } - public void ReadBytes(byte[] buffer, int offset, int length) - { - if(length > _ending - _offset) - throw new EndOfStreamException(); + public void ReadBytes(byte[] buffer, int offset, int length) + { + if (length > _ending - _offset) + throw new EndOfStreamException(); - while(length-- > 0) - buffer[offset++] = _buffer[_offset++]; - } + while (length-- > 0) + buffer[offset++] = _buffer[_offset++]; + } - public void SkipData(long size) - { - if(size > _ending - _offset) - throw new EndOfStreamException(); + public void SkipData(long size) + { + if (size > _ending - _offset) + throw new EndOfStreamException(); - _offset += (int)size; - Log.WriteLine("SkipData {0}", size); - } + _offset += (int) size; + Log.WriteLine("SkipData {0}", size); + } - public void SkipData() - { - SkipData(checked((long)ReadNumber())); - } + public void SkipData() + { + SkipData(checked((long) ReadNumber())); + } - public ulong ReadNumber() - { - if(_offset >= _ending) - throw new EndOfStreamException(); + public ulong ReadNumber() + { + if (_offset >= _ending) + throw new EndOfStreamException(); - byte firstByte = _buffer[_offset++]; - byte mask = 0x80; - ulong value = 0; + byte firstByte = _buffer[_offset++]; + byte mask = 0x80; + ulong value = 0; - for(int i = 0; i < 8; i++) - { - if((firstByte & mask) == 0) + for (int i = 0; i < 8; i++) { - ulong highPart = firstByte & (mask - 1u); - value += highPart << (i * 8); - return value; + if ((firstByte & mask) == 0) + { + ulong highPart = firstByte & (mask - 1u); + value += highPart << (i*8); + return value; + } + + if (_offset >= _ending) + throw new EndOfStreamException(); + + value |= (ulong) _buffer[_offset++] << (8*i); + mask >>= 1; } - if(_offset >= _ending) - throw new EndOfStreamException(); + return value; + } - value |= (ulong)_buffer[_offset++] << (8 * i); - mask >>= 1; - } + public int ReadNum() + { + ulong value = ReadNumber(); + if (value > Int32.MaxValue) + throw new NotSupportedException(); - return value; - } + return (int) value; + } - public int ReadNum() - { - ulong value = ReadNumber(); - if(value > Int32.MaxValue) - throw new NotSupportedException(); + public uint ReadUInt32() + { + if (_offset + 4 > _ending) + throw new EndOfStreamException(); - return (int)value; - } + uint res = Get32(_buffer, _offset); + _offset += 4; + return res; + } - public uint ReadUInt32() - { - if(_offset + 4 > _ending) - throw new EndOfStreamException(); + public ulong ReadUInt64() + { + if (_offset + 8 > _ending) + throw new EndOfStreamException(); - uint res = Get32(_buffer, _offset); - _offset += 4; - return res; - } + ulong res = Get64(_buffer, _offset); + _offset += 8; + return res; + } - public ulong ReadUInt64() - { - if(_offset + 8 > _ending) - throw new EndOfStreamException(); + public string ReadString() + { + int ending = _offset; - ulong res = Get64(_buffer, _offset); - _offset += 8; - return res; - } + for (;;) + { + if (ending + 2 > _ending) + throw new EndOfStreamException(); - public string ReadString() - { - int ending = _offset; + if (_buffer[ending] == 0 && _buffer[ending + 1] == 0) + break; - for(; ; ) - { - if(ending + 2 > _ending) - throw new EndOfStreamException(); + ending += 2; + } - if(_buffer[ending] == 0 && _buffer[ending + 1] == 0) - break; + string str = Encoding.Unicode.GetString(_buffer, _offset, ending - _offset); + _offset = ending + 2; + return str; + } - ending += 2; - } - - string str = Encoding.Unicode.GetString(_buffer, _offset, ending - _offset); - _offset = ending + 2; - return str; - } - - #endregion - } + #endregion + } } \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/SevenZipEntry.cs b/SharpCompress/Common/SevenZip/SevenZipEntry.cs index 00f448b6..242a6a77 100644 --- a/SharpCompress/Common/SevenZip/SevenZipEntry.cs +++ b/SharpCompress/Common/SevenZip/SevenZipEntry.cs @@ -14,10 +14,7 @@ namespace SharpCompress.Common.SevenZip public override CompressionType CompressionType { - get - { - return FilePart.CompressionType; - } + get { return FilePart.CompressionType; } } public override uint Crc @@ -37,7 +34,7 @@ namespace SharpCompress.Common.SevenZip public override long Size { - get { return (long)FilePart.Header.Size; } + get { return (long) FilePart.Header.Size; } } public override DateTime? LastModifiedTime @@ -84,4 +81,4 @@ namespace SharpCompress.Common.SevenZip { } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/SevenZipFilePart.cs b/SharpCompress/Common/SevenZip/SevenZipFilePart.cs index 5b1e5449..215ba10c 100644 --- a/SharpCompress/Common/SevenZip/SevenZipFilePart.cs +++ b/SharpCompress/Common/SevenZip/SevenZipFilePart.cs @@ -73,15 +73,15 @@ namespace SharpCompress.Common.SevenZip } //copied from DecoderRegistry - const uint k_Copy = 0x0; - const uint k_Delta = 3; - const uint k_LZMA2 = 0x21; - const uint k_LZMA = 0x030101; - const uint k_PPMD = 0x030401; - const uint k_BCJ = 0x03030103; - const uint k_BCJ2 = 0x0303011B; - const uint k_Deflate = 0x040108; - const uint k_BZip2 = 0x040202; + private const uint k_Copy = 0x0; + private const uint k_Delta = 3; + private const uint k_LZMA2 = 0x21; + private const uint k_LZMA = 0x030101; + private const uint k_PPMD = 0x030401; + private const uint k_BCJ = 0x03030103; + private const uint k_BCJ2 = 0x0303011B; + private const uint k_Deflate = 0x040108; + private const uint k_BZip2 = 0x040202; internal CompressionType GetCompression() { @@ -106,4 +106,4 @@ namespace SharpCompress.Common.SevenZip } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/SevenZip/SevenZipVolume.cs b/SharpCompress/Common/SevenZip/SevenZipVolume.cs index 4b823dfa..b0035787 100644 --- a/SharpCompress/Common/SevenZip/SevenZipVolume.cs +++ b/SharpCompress/Common/SevenZip/SevenZipVolume.cs @@ -16,4 +16,4 @@ namespace SharpCompress.Common.SevenZip } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Tar/Headers/TarHeader.cs b/SharpCompress/Common/Tar/Headers/TarHeader.cs index 47040e1f..8172c511 100644 --- a/SharpCompress/Common/Tar/Headers/TarHeader.cs +++ b/SharpCompress/Common/Tar/Headers/TarHeader.cs @@ -10,18 +10,19 @@ namespace SharpCompress.Common.Tar.Headers internal enum EntryType : byte { File = 0, - OldFile = (byte)'0', - HardLink = (byte)'1', - SymLink = (byte)'2', - CharDevice = (byte)'3', - BlockDevice = (byte)'4', - Directory = (byte)'5', - Fifo = (byte)'6', - LongLink = (byte)'K', - LongName = (byte)'L', - SparseFile = (byte)'S', - VolumeHeader = (byte)'V', + OldFile = (byte) '0', + HardLink = (byte) '1', + SymLink = (byte) '2', + CharDevice = (byte) '3', + BlockDevice = (byte) '4', + Directory = (byte) '5', + Fifo = (byte) '6', + LongLink = (byte) 'K', + LongName = (byte) 'L', + SparseFile = (byte) 'S', + VolumeHeader = (byte) 'V', } + internal class TarHeader { internal static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0); @@ -55,10 +56,10 @@ namespace SharpCompress.Common.Tar.Headers WriteOctalBytes(0, buffer, 108, 8); WriteOctalBytes(0, buffer, 116, 8); WriteOctalBytes(Size, buffer, 124, 12); - var time = (long)(LastModifiedTime - Epoch).TotalSeconds; + var time = (long) (LastModifiedTime - Epoch).TotalSeconds; WriteOctalBytes(time, buffer, 136, 12); - buffer[156] = (byte)EntryType; + buffer[156] = (byte) EntryType; //Encoding.UTF8.GetBytes("magic").CopyTo(buffer, 257); if (Name.Length > 100) @@ -99,7 +100,7 @@ namespace SharpCompress.Common.Tar.Headers //Mode = ReadASCIIInt32Base8(buffer, 100, 7); //UserId = ReadASCIIInt32Base8(buffer, 108, 7); //GroupId = ReadASCIIInt32Base8(buffer, 116, 7); - EntryType = (EntryType)buffer[156]; + EntryType = (EntryType) buffer[156]; if ((buffer[124] & 0x80) == 0x80) // if size in binary { long sizeBigEndian = BitConverter.ToInt64(buffer, 0x80); @@ -141,7 +142,7 @@ namespace SharpCompress.Common.Tar.Headers for (i = 0; i < length - 1 && i < name.Length; ++i) { - buffer[offset + i] = (byte)name[i]; + buffer[offset + i] = (byte) name[i]; } for (; i < length; ++i) @@ -156,11 +157,11 @@ namespace SharpCompress.Common.Tar.Headers int shift = length - val.Length - 1; for (int i = 0; i < shift; i++) { - buffer[offset + i] = (byte)' '; + buffer[offset + i] = (byte) ' '; } for (int i = 0; i < val.Length; i++) { - buffer[offset + i + shift] = (byte)val[i]; + buffer[offset + i + shift] = (byte) val[i]; } buffer[offset + length] = 0; } @@ -226,8 +227,9 @@ namespace SharpCompress.Common.Tar.Headers } return headerChecksum; } + public long? DataStartPosition { get; set; } public string Magic { get; set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Tar/TarEntry.cs b/SharpCompress/Common/Tar/TarEntry.cs index 09a2bbba..b44c5f88 100644 --- a/SharpCompress/Common/Tar/TarEntry.cs +++ b/SharpCompress/Common/Tar/TarEntry.cs @@ -82,7 +82,8 @@ namespace SharpCompress.Common.Tar get { return filePart.AsEnumerable(); } } - internal static IEnumerable GetEntries(StreamingMode mode, Stream stream, CompressionType compressionType) + internal static IEnumerable GetEntries(StreamingMode mode, Stream stream, + CompressionType compressionType) { foreach (TarHeader h in TarHeaderFactory.ReadHeader(mode, stream)) { diff --git a/SharpCompress/Common/Tar/TarFilePart.cs b/SharpCompress/Common/Tar/TarFilePart.cs index 7fd69c3c..c0d1341f 100644 --- a/SharpCompress/Common/Tar/TarFilePart.cs +++ b/SharpCompress/Common/Tar/TarFilePart.cs @@ -13,6 +13,7 @@ namespace SharpCompress.Common.Tar this.seekableStream = seekableStream; this.Header = header; } + internal TarHeader Header { get; private set; } internal override string FilePartName @@ -35,4 +36,4 @@ namespace SharpCompress.Common.Tar return null; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Tar/TarHeaderFactory.cs b/SharpCompress/Common/Tar/TarHeaderFactory.cs index 2ebc0df5..f084849e 100644 --- a/SharpCompress/Common/Tar/TarHeaderFactory.cs +++ b/SharpCompress/Common/Tar/TarHeaderFactory.cs @@ -50,7 +50,7 @@ namespace SharpCompress.Common.Tar private static long PadTo512(long size) { - int zeros = (int)(size % 512); + int zeros = (int) (size%512); if (zeros == 0) { return size; @@ -58,4 +58,4 @@ namespace SharpCompress.Common.Tar return 512 - zeros + size; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Tar/TarReadOnlySubStream.cs b/SharpCompress/Common/Tar/TarReadOnlySubStream.cs index 3c9c40b4..61f4c04c 100644 --- a/SharpCompress/Common/Tar/TarReadOnlySubStream.cs +++ b/SharpCompress/Common/Tar/TarReadOnlySubStream.cs @@ -16,7 +16,7 @@ namespace SharpCompress.Common.Tar { if (disposing) { - int skipBytes = this.amountRead % 512; + int skipBytes = this.amountRead%512; if (skipBytes == 0) { return; @@ -31,40 +31,23 @@ namespace SharpCompress.Common.Tar } } - private long BytesLeftToRead - { - get; - set; - } + private long BytesLeftToRead { get; set; } - public Stream Stream - { - get; - private set; - } + public Stream Stream { get; private set; } public override bool CanRead { - get - { - return true; - } + get { return true; } } public override bool CanSeek { - get - { - return false; - } + get { return false; } } public override bool CanWrite { - get - { - return false; - } + get { return false; } } public override void Flush() @@ -74,29 +57,20 @@ namespace SharpCompress.Common.Tar public override long Length { - get - { - throw new System.NotImplementedException(); - } + get { throw new System.NotImplementedException(); } } public override long Position { - get - { - throw new System.NotImplementedException(); - } - set - { - throw new System.NotImplementedException(); - } + get { throw new System.NotImplementedException(); } + set { throw new System.NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) { if (this.BytesLeftToRead < count) { - count = (int)this.BytesLeftToRead; + count = (int) this.BytesLeftToRead; } int read = this.Stream.Read(buffer, offset, count); if (read > 0) @@ -122,4 +96,4 @@ namespace SharpCompress.Common.Tar throw new System.NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Tar/TarVolume.cs b/SharpCompress/Common/Tar/TarVolume.cs index 4f75490d..c1b0bc1b 100644 --- a/SharpCompress/Common/Tar/TarVolume.cs +++ b/SharpCompress/Common/Tar/TarVolume.cs @@ -16,4 +16,4 @@ namespace SharpCompress.Common.Tar } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Volume.cs b/SharpCompress/Common/Volume.cs index 2302aba8..dcc43d4d 100644 --- a/SharpCompress/Common/Volume.cs +++ b/SharpCompress/Common/Volume.cs @@ -15,10 +15,7 @@ namespace SharpCompress.Common internal Stream Stream { - get - { - return new NonDisposingStream(actualStream); - } + get { return new NonDisposingStream(actualStream); } } internal Options Options { get; private set; } @@ -27,27 +24,19 @@ namespace SharpCompress.Common /// RarArchive is the first volume of a multi-part archive. /// Only Rar 3.0 format and higher /// - public abstract bool IsFirstVolume - { - get; - } + public abstract bool IsFirstVolume { get; } /// /// RarArchive is part of a multi-part archive. /// - public abstract bool IsMultiVolume - { - get; - } + public abstract bool IsMultiVolume { get; } #if !PORTABLE - public abstract FileInfo VolumeFile - { - get; - } + public abstract FileInfo VolumeFile { get; } #endif private bool disposed; + public void Dispose() { if (!Options.HasFlag(Options.KeepStreamsOpen) && !disposed) @@ -57,4 +46,4 @@ namespace SharpCompress.Common } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/Headers/DirectoryEndHeader.cs b/SharpCompress/Common/Zip/Headers/DirectoryEndHeader.cs index 587947e8..a27778e1 100644 --- a/SharpCompress/Common/Zip/Headers/DirectoryEndHeader.cs +++ b/SharpCompress/Common/Zip/Headers/DirectoryEndHeader.cs @@ -49,4 +49,4 @@ namespace SharpCompress.Common.Zip.Headers public ushort TotalNumberOfEntries { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs b/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs index 7276ff88..16c01d36 100644 --- a/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs +++ b/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs @@ -13,8 +13,8 @@ namespace SharpCompress.Common.Zip.Headers { Version = reader.ReadUInt16(); VersionNeededToExtract = reader.ReadUInt16(); - Flags = (HeaderFlags)reader.ReadUInt16(); - CompressionMethod = (ZipCompressionMethod)reader.ReadUInt16(); + Flags = (HeaderFlags) reader.ReadUInt16(); + CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16(); LastModifiedTime = reader.ReadUInt16(); LastModifiedDate = reader.ReadUInt16(); Crc = reader.ReadUInt32(); @@ -40,8 +40,8 @@ namespace SharpCompress.Common.Zip.Headers { writer.Write(Version); writer.Write(VersionNeededToExtract); - writer.Write((ushort)Flags); - writer.Write((ushort)CompressionMethod); + writer.Write((ushort) Flags); + writer.Write((ushort) CompressionMethod); writer.Write(LastModifiedTime); writer.Write(LastModifiedDate); writer.Write(Crc); @@ -49,10 +49,10 @@ namespace SharpCompress.Common.Zip.Headers writer.Write(UncompressedSize); byte[] nameBytes = EncodeString(Name); - writer.Write((ushort)nameBytes.Length); + writer.Write((ushort) nameBytes.Length); //writer.Write((ushort)Extra.Length); - writer.Write((ushort)0); - writer.Write((ushort)Comment.Length); + writer.Write((ushort) 0); + writer.Write((ushort) Comment.Length); writer.Write(DiskNumberStart); writer.Write(InternalFileAttributes); @@ -78,4 +78,4 @@ namespace SharpCompress.Common.Zip.Headers public string Comment { get; private set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/Headers/HeaderFlags.cs b/SharpCompress/Common/Zip/Headers/HeaderFlags.cs index 159ad599..40562a74 100644 --- a/SharpCompress/Common/Zip/Headers/HeaderFlags.cs +++ b/SharpCompress/Common/Zip/Headers/HeaderFlags.cs @@ -12,4 +12,4 @@ namespace SharpCompress.Common.Zip.Headers EnhancedDeflate = 16, UTF8 = 2048 } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs b/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs index cd557504..3f423df9 100644 --- a/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs +++ b/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs @@ -6,6 +6,7 @@ namespace SharpCompress.Common.Zip.Headers { WinZipAes = 0x9901, } + internal class ExtraData { internal ExtraDataType Type { get; set; } @@ -23,8 +24,8 @@ namespace SharpCompress.Common.Zip.Headers internal override void Read(BinaryReader reader) { Version = reader.ReadUInt16(); - Flags = (HeaderFlags)reader.ReadUInt16(); - CompressionMethod = (ZipCompressionMethod)reader.ReadUInt16(); + Flags = (HeaderFlags) reader.ReadUInt16(); + CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16(); LastModifiedTime = reader.ReadUInt16(); LastModifiedDate = reader.ReadUInt16(); Crc = reader.ReadUInt32(); @@ -41,8 +42,8 @@ namespace SharpCompress.Common.Zip.Headers internal override void Write(BinaryWriter writer) { writer.Write(Version); - writer.Write((ushort)Flags); - writer.Write((ushort)CompressionMethod); + writer.Write((ushort) Flags); + writer.Write((ushort) CompressionMethod); writer.Write(LastModifiedTime); writer.Write(LastModifiedDate); writer.Write(Crc); @@ -51,8 +52,8 @@ namespace SharpCompress.Common.Zip.Headers byte[] nameBytes = EncodeString(Name); - writer.Write((ushort)nameBytes.Length); - writer.Write((ushort)0); + writer.Write((ushort) nameBytes.Length); + writer.Write((ushort) 0); //if (Extra != null) //{ // writer.Write(Extra); @@ -61,7 +62,5 @@ namespace SharpCompress.Common.Zip.Headers } internal ushort Version { get; private set; } - - } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/Headers/SplitHeader.cs b/SharpCompress/Common/Zip/Headers/SplitHeader.cs index 787473b1..82bb8f6c 100644 --- a/SharpCompress/Common/Zip/Headers/SplitHeader.cs +++ b/SharpCompress/Common/Zip/Headers/SplitHeader.cs @@ -19,4 +19,4 @@ namespace SharpCompress.Common.Zip.Headers throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/Headers/ZipFileEntry..cs b/SharpCompress/Common/Zip/Headers/ZipFileEntry..cs index 9b0ac31e..76cd17ff 100644 --- a/SharpCompress/Common/Zip/Headers/ZipFileEntry..cs +++ b/SharpCompress/Common/Zip/Headers/ZipFileEntry..cs @@ -66,10 +66,10 @@ namespace SharpCompress.Common.Zip.Headers protected void LoadExtra(byte[] extra) { - for (int i = 0; i < extra.Length; ) + for (int i = 0; i < extra.Length;) { - ExtraDataType type = (ExtraDataType)BitConverter.ToUInt16(extra, i); - if (!Enum.IsDefined(typeof(ExtraDataType), type)) + ExtraDataType type = (ExtraDataType) BitConverter.ToUInt16(extra, i); + if (!Enum.IsDefined(typeof (ExtraDataType), type)) { return; } @@ -77,14 +77,15 @@ namespace SharpCompress.Common.Zip.Headers byte[] data = new byte[length]; Buffer.BlockCopy(extra, i + 4, data, 0, length); Extra.Add(new ExtraData - { - Type = type, - Length = length, - DataBytes = data - }); + { + Type = type, + Length = length, + DataBytes = data + }); i += length + 4; } } + internal ZipFilePart Part { get; set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/Headers/ZipHeader.cs b/SharpCompress/Common/Zip/Headers/ZipHeader.cs index b5b9ee83..e8114b96 100644 --- a/SharpCompress/Common/Zip/Headers/ZipHeader.cs +++ b/SharpCompress/Common/Zip/Headers/ZipHeader.cs @@ -10,11 +10,7 @@ namespace SharpCompress.Common.Zip.Headers HasData = true; } - internal ZipHeaderType ZipHeaderType - { - get; - private set; - } + internal ZipHeaderType ZipHeaderType { get; private set; } internal abstract void Read(BinaryReader reader); @@ -22,4 +18,4 @@ namespace SharpCompress.Common.Zip.Headers internal bool HasData { get; set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/Headers/ZipHeaderType.cs b/SharpCompress/Common/Zip/Headers/ZipHeaderType.cs index 32b696bd..de823d10 100644 --- a/SharpCompress/Common/Zip/Headers/ZipHeaderType.cs +++ b/SharpCompress/Common/Zip/Headers/ZipHeaderType.cs @@ -1,5 +1,4 @@ - -namespace SharpCompress.Common.Zip.Headers +namespace SharpCompress.Common.Zip.Headers { internal enum ZipHeaderType { @@ -9,4 +8,4 @@ namespace SharpCompress.Common.Zip.Headers DirectoryEnd, Split, } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs b/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs index 74c7eb76..f3b11d02 100644 --- a/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs +++ b/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs @@ -8,7 +8,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 PkwareTraditionalEncryptionData(string password) { @@ -19,22 +19,23 @@ namespace SharpCompress.Common.Zip { get { - ushort t = (ushort)((ushort)(_Keys[2] & 0xFFFF) | 2); - return (byte)((t * (t ^ 1)) >> 8); + ushort t = (ushort) ((ushort) (_Keys[2] & 0xFFFF) | 2); + return (byte) ((t*(t ^ 1)) >> 8); } } - public static PkwareTraditionalEncryptionData ForRead(string password, ZipFileEntry header, byte[] encryptionHeader) + public static PkwareTraditionalEncryptionData ForRead(string password, ZipFileEntry header, + byte[] encryptionHeader) { var encryptor = new PkwareTraditionalEncryptionData(password); byte[] plainTextHeader = encryptor.Decrypt(encryptionHeader, encryptionHeader.Length); - if (plainTextHeader[11] != (byte)((header.Crc >> 24) & 0xff)) + if (plainTextHeader[11] != (byte) ((header.Crc >> 24) & 0xff)) { if (!FlagUtility.HasFlag(header.Flags, HeaderFlags.UsePostDataDescriptor)) { throw new CryptographicException("The password did not match."); } - if (plainTextHeader[11] != (byte)((header.LastModifiedTime >> 8) & 0xff)) + if (plainTextHeader[11] != (byte) ((header.LastModifiedTime >> 8) & 0xff)) { throw new CryptographicException("The password did not match."); } @@ -52,7 +53,7 @@ namespace SharpCompress.Common.Zip var plainText = new byte[length]; for (int i = 0; i < length; i++) { - var C = (byte)(cipherText[i] ^ MagicByte); + var C = (byte) (cipherText[i] ^ MagicByte); UpdateKeys(C); plainText[i] = C; } @@ -72,7 +73,7 @@ namespace SharpCompress.Common.Zip for (int i = 0; i < length; i++) { byte C = plainText[i]; - cipherText[i] = (byte)(plainText[i] ^ MagicByte); + cipherText[i] = (byte) (plainText[i] ^ MagicByte); UpdateKeys(C); } return cipherText; @@ -98,10 +99,10 @@ namespace SharpCompress.Common.Zip private void UpdateKeys(byte byteValue) { - _Keys[0] = (UInt32)crc32.ComputeCrc32((int)_Keys[0], byteValue); - _Keys[1] = _Keys[1] + (byte)_Keys[0]; - _Keys[1] = _Keys[1] * 0x08088405 + 1; - _Keys[2] = (UInt32)crc32.ComputeCrc32((int)_Keys[2], (byte)(_Keys[1] >> 24)); + _Keys[0] = (UInt32) crc32.ComputeCrc32((int) _Keys[0], byteValue); + _Keys[1] = _Keys[1] + (byte) _Keys[0]; + _Keys[1] = _Keys[1]*0x08088405 + 1; + _Keys[2] = (UInt32) crc32.ComputeCrc32((int) _Keys[2], (byte) (_Keys[1] >> 24)); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/SeekableZipFilePart.cs b/SharpCompress/Common/Zip/SeekableZipFilePart.cs index 72035742..f507c113 100644 --- a/SharpCompress/Common/Zip/SeekableZipFilePart.cs +++ b/SharpCompress/Common/Zip/SeekableZipFilePart.cs @@ -26,10 +26,7 @@ namespace SharpCompress.Common.Zip internal string Comment { - get - { - return (Header as DirectoryEntryHeader).Comment; - } + get { return (Header as DirectoryEntryHeader).Comment; } } private void LoadLocalHeader() @@ -45,4 +42,4 @@ namespace SharpCompress.Common.Zip return BaseStream; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs b/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs index f40ccdf5..2ac9a165 100644 --- a/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs +++ b/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs @@ -32,9 +32,10 @@ namespace SharpCompress.Common.Zip signature = reader.ReadUInt32(); offset--; iterationCount++; - if(iterationCount > MAX_ITERATIONS_FOR_DIRECTORY_HEADER) + if (iterationCount > MAX_ITERATIONS_FOR_DIRECTORY_HEADER) { - throw new ArchiveException("Could not find Zip file Directory at the end of the file. File may be corrupted."); + throw new ArchiveException( + "Could not find Zip file Directory at the end of the file. File may be corrupted."); } } while (signature != DIRECTORY_END_HEADER_BYTES); @@ -73,4 +74,4 @@ namespace SharpCompress.Common.Zip return localEntryHeader; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/StreamingZipFilePart.cs b/SharpCompress/Common/Zip/StreamingZipFilePart.cs index 26ae58f4..82a0b43a 100644 --- a/SharpCompress/Common/Zip/StreamingZipFilePart.cs +++ b/SharpCompress/Common/Zip/StreamingZipFilePart.cs @@ -57,6 +57,5 @@ namespace SharpCompress.Common.Zip decompressionStream = null; return reader; } - } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs b/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs index 58ff1e82..6bcffa1d 100644 --- a/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs +++ b/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs @@ -27,7 +27,8 @@ namespace SharpCompress.Common.Zip { ZipHeader header = null; BinaryReader reader = new BinaryReader(rewindableStream); - if (lastEntryHeader != null && FlagUtility.HasFlag(lastEntryHeader.Flags, HeaderFlags.UsePostDataDescriptor)) + if (lastEntryHeader != null && + FlagUtility.HasFlag(lastEntryHeader.Flags, HeaderFlags.UsePostDataDescriptor)) { reader = (lastEntryHeader.Part as StreamingZipFilePart).FixStreamedFileLocation(ref rewindableStream); long pos = rewindableStream.Position; @@ -59,8 +60,6 @@ namespace SharpCompress.Common.Zip } yield return header; } - } - } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/WinzipAesCryptoStream.cs b/SharpCompress/Common/Zip/WinzipAesCryptoStream.cs index b9d72d92..a5091917 100644 --- a/SharpCompress/Common/Zip/WinzipAesCryptoStream.cs +++ b/SharpCompress/Common/Zip/WinzipAesCryptoStream.cs @@ -43,8 +43,8 @@ namespace SharpCompress.Common.Zip { #if !SILVERLIGHT && !PORTABLE RijndaelManaged cipher = new RijndaelManaged(); - cipher.BlockSize = BLOCK_SIZE_IN_BYTES * 8; - cipher.KeySize = winzipAesEncryptionData.KeyBytes.Length * 8; + cipher.BlockSize = BLOCK_SIZE_IN_BYTES*8; + cipher.KeySize = winzipAesEncryptionData.KeyBytes.Length*8; cipher.Mode = CipherMode.ECB; cipher.Padding = PaddingMode.None; return cipher; @@ -104,7 +104,7 @@ namespace SharpCompress.Common.Zip int bytesToRead = count; if (count > totalBytesLeftToRead) { - bytesToRead = (int)totalBytesLeftToRead; + bytesToRead = (int) totalBytesLeftToRead; } int read = stream.Read(buffer, offset, bytesToRead); totalBytesLeftToRead -= read; @@ -157,7 +157,7 @@ namespace SharpCompress.Common.Zip { for (int i = 0; i < count; i++) { - buffer[offset + i] = (byte)(counterOut[i] ^ buffer[offset + i]); + buffer[offset + i] = (byte) (counterOut[i] ^ buffer[offset + i]); } } diff --git a/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs b/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs index d2ec785f..eb37ac98 100644 --- a/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs +++ b/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs @@ -1,6 +1,4 @@ - - -using System; +using System; namespace SharpCompress.Common.Zip { @@ -15,7 +13,8 @@ namespace SharpCompress.Common.Zip private byte[] generatedVerifyValue; - internal WinzipAesEncryptionData(WinzipAesKeySize keySize, byte[] salt, byte[] passwordVerifyValue, string password) + internal WinzipAesEncryptionData(WinzipAesKeySize keySize, byte[] salt, byte[] passwordVerifyValue, + string password) { this.keySize = keySize; this.salt = salt; @@ -48,7 +47,6 @@ namespace SharpCompress.Common.Zip private void Initialize() { - System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, RFC2898_ITERATIONS); @@ -65,4 +63,4 @@ namespace SharpCompress.Common.Zip } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/WinzipAesKeySize.cs b/SharpCompress/Common/Zip/WinzipAesKeySize.cs index d67cd529..c5c55d30 100644 --- a/SharpCompress/Common/Zip/WinzipAesKeySize.cs +++ b/SharpCompress/Common/Zip/WinzipAesKeySize.cs @@ -1,5 +1,4 @@ - -namespace SharpCompress.Common.Zip +namespace SharpCompress.Common.Zip { internal enum WinzipAesKeySize { @@ -7,4 +6,4 @@ namespace SharpCompress.Common.Zip KeySize192 = 2, KeySize256 = 3, } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/ZipCompressionMethod.cs b/SharpCompress/Common/Zip/ZipCompressionMethod.cs index 454aa0c8..887418cf 100644 --- a/SharpCompress/Common/Zip/ZipCompressionMethod.cs +++ b/SharpCompress/Common/Zip/ZipCompressionMethod.cs @@ -1,5 +1,4 @@ - -namespace SharpCompress.Common.Zip +namespace SharpCompress.Common.Zip { internal enum ZipCompressionMethod { @@ -11,4 +10,4 @@ namespace SharpCompress.Common.Zip PPMd = 98, WinzipAes = 0x63 //http://www.winzip.com/aes_info.htm } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/ZipFilePart.cs b/SharpCompress/Common/Zip/ZipFilePart.cs index 99057598..88d27403 100644 --- a/SharpCompress/Common/Zip/ZipFilePart.cs +++ b/SharpCompress/Common/Zip/ZipFilePart.cs @@ -85,10 +85,11 @@ namespace SharpCompress.Common.Zip 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, + return new LzmaStream(props, stream, + Header.CompressedSize > 0 ? Header.CompressedSize - 4 - props.Length : -1, FlagUtility.HasFlag(Header.Flags, HeaderFlags.Bit1) ? -1 - : (long)Header.UncompressedSize); + : (long) Header.UncompressedSize); } case ZipCompressionMethod.PPMd: { @@ -119,7 +120,7 @@ namespace SharpCompress.Common.Zip { throw new InvalidFormatException("Unexpected vendor ID for WinZip AES metadata"); } - Header.CompressionMethod = (ZipCompressionMethod)BitConverter.ToUInt16(data.DataBytes, 5); + Header.CompressionMethod = (ZipCompressionMethod) BitConverter.ToUInt16(data.DataBytes, 5); return CreateDecompressionStream(stream); } default: @@ -133,8 +134,8 @@ namespace SharpCompress.Common.Zip { if ((Header.CompressedSize == 0) #if !PORTABLE - && ((Header.PkwareTraditionalEncryptionData != null) - || (Header.WinzipAesEncryptionData != null))) + && ((Header.PkwareTraditionalEncryptionData != null) + || (Header.WinzipAesEncryptionData != null))) #else && (Header.PkwareTraditionalEncryptionData != null)) #endif @@ -166,5 +167,4 @@ namespace SharpCompress.Common.Zip return plainStream; } } - } \ No newline at end of file diff --git a/SharpCompress/Common/Zip/ZipHeaderFactory.cs b/SharpCompress/Common/Zip/ZipHeaderFactory.cs index d532bc9a..85e4f0b3 100644 --- a/SharpCompress/Common/Zip/ZipHeaderFactory.cs +++ b/SharpCompress/Common/Zip/ZipHeaderFactory.cs @@ -4,6 +4,7 @@ using SharpCompress.Common.Zip.Headers; using SharpCompress.IO; #if !SILVERLIGHT && !PORTABLE using System.Linq; + #endif namespace SharpCompress.Common.Zip @@ -116,7 +117,8 @@ namespace SharpCompress.Common.Zip entryHeader.CompressedSize == 0 && FlagUtility.HasFlag(entryHeader.Flags, HeaderFlags.UsePostDataDescriptor)) { - throw new NotSupportedException("SharpCompress cannot currently read non-seekable Zip Streams with encrypted data that has been written in a non-seekable manner."); + throw new NotSupportedException( + "SharpCompress cannot currently read non-seekable Zip Streams with encrypted data that has been written in a non-seekable manner."); } if (password == null) { @@ -126,7 +128,9 @@ namespace SharpCompress.Common.Zip { byte[] buffer = new byte[12]; stream.Read(buffer, 0, 12); - entryHeader.PkwareTraditionalEncryptionData = PkwareTraditionalEncryptionData.ForRead(password, entryHeader, buffer); + entryHeader.PkwareTraditionalEncryptionData = PkwareTraditionalEncryptionData.ForRead(password, + entryHeader, + buffer); entryHeader.CompressedSize -= 12; } else @@ -136,14 +140,15 @@ namespace SharpCompress.Common.Zip #else var data = entryHeader.Extra.Where(x => x.Type == ExtraDataType.WinZipAes).SingleOrDefault(); - WinzipAesKeySize keySize = (WinzipAesKeySize)data.DataBytes[4]; + WinzipAesKeySize keySize = (WinzipAesKeySize) data.DataBytes[4]; - byte[] salt = new byte[WinzipAesEncryptionData.KeyLengthInBytes(keySize) / 2]; + byte[] salt = new byte[WinzipAesEncryptionData.KeyLengthInBytes(keySize)/2]; byte[] passwordVerifyValue = new byte[2]; stream.Read(salt, 0, salt.Length); stream.Read(passwordVerifyValue, 0, 2); - entryHeader.WinzipAesEncryptionData = new WinzipAesEncryptionData(keySize, salt, passwordVerifyValue, password); - entryHeader.CompressedSize -= (uint)(salt.Length + 2); + entryHeader.WinzipAesEncryptionData = new WinzipAesEncryptionData(keySize, salt, passwordVerifyValue, + password); + entryHeader.CompressedSize -= (uint) (salt.Length + 2); #endif } @@ -179,4 +184,4 @@ namespace SharpCompress.Common.Zip //} } } -} +} \ No newline at end of file diff --git a/SharpCompress/Common/Zip/ZipVolume.cs b/SharpCompress/Common/Zip/ZipVolume.cs index 72c4aec2..f012007f 100644 --- a/SharpCompress/Common/Zip/ZipVolume.cs +++ b/SharpCompress/Common/Zip/ZipVolume.cs @@ -18,4 +18,4 @@ namespace SharpCompress.Common.Zip public string Comment { get; internal set; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/BZip2/BZip2Constants.cs b/SharpCompress/Compressor/BZip2/BZip2Constants.cs index cec013cc..4ba2887a 100644 --- a/SharpCompress/Compressor/BZip2/BZip2Constants.cs +++ b/SharpCompress/Compressor/BZip2/BZip2Constants.cs @@ -28,9 +28,9 @@ namespace SharpCompress.Compressor.BZip2 * * @author Keiron Liddle */ + internal class BZip2Constants { - public const int baseBlockSize = 100000; public const int MAX_ALPHA_SIZE = 258; public const int MAX_CODE_LEN = 23; @@ -39,62 +39,63 @@ namespace SharpCompress.Compressor.BZip2 public const int N_GROUPS = 6; public const int G_SIZE = 50; public const int N_ITERS = 4; - public const int MAX_SELECTORS = (2 + (900000 / G_SIZE)); + public const int MAX_SELECTORS = (2 + (900000/G_SIZE)); public const int NUM_OVERSHOOT_BYTES = 20; - public static int[] rNums = { - 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, - 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, - 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, - 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, - 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, - 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, - 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, - 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, - 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, - 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, - 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, - 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, - 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, - 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, - 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, - 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, - 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, - 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, - 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, - 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, - 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, - 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, - 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, - 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, - 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, - 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, - 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, - 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, - 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, - 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, - 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, - 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, - 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, - 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, - 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, - 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, - 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, - 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, - 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, - 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, - 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, - 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, - 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, - 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, - 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, - 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, - 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, - 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, - 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, - 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, - 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, - 936, 638 - }; + public static int[] rNums = + { + 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, + 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, + 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, + 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, + 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, + 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, + 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, + 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, + 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, + 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, + 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, + 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, + 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, + 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, + 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, + 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, + 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, + 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, + 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, + 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, + 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, + 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, + 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, + 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, + 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, + 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, + 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, + 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, + 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, + 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, + 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, + 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, + 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, + 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, + 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, + 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, + 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, + 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, + 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, + 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, + 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, + 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, + 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, + 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, + 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, + 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, + 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, + 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, + 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, + 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, + 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, + 936, 638 + }; } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/BZip2/BZip2Stream.cs b/SharpCompress/Compressor/BZip2/BZip2Stream.cs index 70af48a0..71de8850 100644 --- a/SharpCompress/Compressor/BZip2/BZip2Stream.cs +++ b/SharpCompress/Compressor/BZip2/BZip2Stream.cs @@ -13,7 +13,8 @@ namespace SharpCompress.Compressor.BZip2 /// Compression Mode /// Leave the underlying stream open when disposed. /// Should the BZip2 stream continue to decompress the stream when the End Marker is found. - public BZip2Stream(Stream stream, CompressionMode compressionMode, bool leaveOpen = false, bool decompressContacted = false) + public BZip2Stream(Stream stream, CompressionMode compressionMode, bool leaveOpen = false, + bool decompressContacted = false) { Mode = compressionMode; if (Mode == CompressionMode.Compress) @@ -103,4 +104,4 @@ namespace SharpCompress.Compressor.BZip2 return true; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/BZip2/CBZip2InputStream.cs b/SharpCompress/Compressor/BZip2/CBZip2InputStream.cs index e4e611dd..a54627a0 100644 --- a/SharpCompress/Compressor/BZip2/CBZip2InputStream.cs +++ b/SharpCompress/Compressor/BZip2/CBZip2InputStream.cs @@ -1,4 +1,5 @@ using System.IO; + /* * Copyright 2001,2004-2005 The Apache Software Foundation * @@ -32,6 +33,7 @@ namespace SharpCompress.Compressor.BZip2 * NB: note this class has been modified to read the leading BZ from the * start of the BZIP2 stream to make it compatible with other PGP programs. */ + internal class CBZip2InputStream : Stream { private static void Cadvise() @@ -63,8 +65,8 @@ namespace SharpCompress.Compressor.BZip2 { if (inUse[i]) { - seqToUnseq[nInUse] = (char)i; - unseqToSeq[i] = (char)nInUse; + seqToUnseq[nInUse] = (char) i; + unseqToSeq[i] = (char) nInUse; nInUse++; } } @@ -137,12 +139,12 @@ namespace SharpCompress.Compressor.BZip2 private int computedBlockCRC, computedCombinedCRC; private bool decompressConcatenated; - int i2, count, chPrev, ch2; - int i, tPos; - int rNToGo = 0; - int rTPos = 0; - int j2; - char z; + private int i2, count, chPrev, ch2; + private int i, tPos; + private int rNToGo = 0; + private int rTPos = 0; + private int j2; + private char z; public CBZip2InputStream(Stream zStream, bool decompressConcatenated, bool leaveOpen) { @@ -252,7 +254,7 @@ namespace SharpCompress.Compressor.BZip2 magic5 = BsGetUChar(); magic6 = BsGetUChar(); if (magic1 != 0x17 || magic2 != 0x72 || magic3 != 0x45 - || magic4 != 0x38 || magic5 != 0x50 || magic6 != 0x90) + || magic4 != 0x38 || magic5 != 0x50 || magic6 != 0x90) { break; } @@ -297,7 +299,7 @@ namespace SharpCompress.Compressor.BZip2 } computedCombinedCRC = (computedCombinedCRC << 1) - | (int)(((uint)computedCombinedCRC) >> 31); + | (int) (((uint) computedCombinedCRC) >> 31); computedCombinedCRC ^= computedBlockCRC; } @@ -370,7 +372,7 @@ namespace SharpCompress.Compressor.BZip2 int thech = '\0'; try { - thech = (char)bsStream.ReadByte(); + thech = (char) bsStream.ReadByte(); } catch (IOException) { @@ -392,7 +394,7 @@ namespace SharpCompress.Compressor.BZip2 private char BsGetUChar() { - return (char)BsR(8); + return (char) BsR(8); } private int BsGetint() @@ -407,17 +409,17 @@ namespace SharpCompress.Compressor.BZip2 private int BsGetIntVS(int numBits) { - return (int)BsR(numBits); + return (int) BsR(numBits); } private int BsGetInt32() { - return (int)BsGetint(); + return (int) BsGetint(); } private void HbCreateDecodeTables(int[] limit, int[] basev, - int[] perm, char[] length, - int minLen, int maxLen, int alphaSize) + int[] perm, char[] length, + int minLen, int maxLen, int alphaSize) { int pp, i, j, vec; @@ -499,7 +501,7 @@ namespace SharpCompress.Compressor.BZip2 { if (BsR(1) == 1) { - inUse[i * 16 + j] = true; + inUse[i*16 + j] = true; } } } @@ -518,7 +520,7 @@ namespace SharpCompress.Compressor.BZip2 { j++; } - selectorMtf[i] = (char)j; + selectorMtf[i] = (char) j; } /* Undo the MTF values for the selectors. */ @@ -561,7 +563,7 @@ namespace SharpCompress.Compressor.BZip2 curr--; } } - len[t][i] = (char)curr; + len[t][i] = (char) curr; } } @@ -582,7 +584,7 @@ namespace SharpCompress.Compressor.BZip2 } } HbCreateDecodeTables(limit[t], basev[t], perm[t], len[t], minLen, - maxLen, alphaSize); + maxLen, alphaSize); minLens[t] = minLen; } } @@ -593,7 +595,7 @@ namespace SharpCompress.Compressor.BZip2 int i, j, nextSym, limitLast; int EOB, groupNo, groupPos; - limitLast = BZip2Constants.baseBlockSize * blockSize100k; + limitLast = BZip2Constants.baseBlockSize*blockSize100k; origPtr = BsGetIntVS(24); RecvDecodingTables(); @@ -614,7 +616,7 @@ namespace SharpCompress.Compressor.BZip2 for (i = 0; i <= 255; i++) { - yy[i] = (char)i; + yy[i] = (char) i; } last = -1; @@ -641,7 +643,7 @@ namespace SharpCompress.Compressor.BZip2 char thech = '\0'; try { - thech = (char)bsStream.ReadByte(); + thech = (char) bsStream.ReadByte(); } catch (IOException) { @@ -666,7 +668,6 @@ namespace SharpCompress.Compressor.BZip2 while (true) { - if (nextSym == EOB) { break; @@ -681,13 +682,13 @@ namespace SharpCompress.Compressor.BZip2 { if (nextSym == BZip2Constants.RUNA) { - s = s + (0 + 1) * N; + s = s + (0 + 1)*N; } else if (nextSym == BZip2Constants.RUNB) { - s = s + (1 + 1) * N; + s = s + (1 + 1)*N; } - N = N * 2; + N = N*2; { int zt, zn, zvec, zj; if (groupPos == 0) @@ -710,7 +711,7 @@ namespace SharpCompress.Compressor.BZip2 char thech = '\0'; try { - thech = (char)bsStream.ReadByte(); + thech = (char) bsStream.ReadByte(); } catch (IOException) { @@ -807,7 +808,7 @@ namespace SharpCompress.Compressor.BZip2 char thech = '\0'; try { - thech = (char)bsStream.ReadByte(); + thech = (char) bsStream.ReadByte(); } catch (IOException) { @@ -847,7 +848,7 @@ namespace SharpCompress.Compressor.BZip2 for (i = 0; i <= last; i++) { - ch = (char)ll8[i]; + ch = (char) ll8[i]; tt[cftab[ch]] = i; cftab[ch]++; } @@ -857,7 +858,7 @@ namespace SharpCompress.Compressor.BZip2 count = 0; i2 = 0; - ch2 = 256; /* not a char and not EOF */ + ch2 = 256; /* not a char and not EOF */ if (blockRandomised) { @@ -888,7 +889,7 @@ namespace SharpCompress.Compressor.BZip2 } } rNToGo--; - ch2 ^= (int)((rNToGo == 1) ? 1 : 0); + ch2 ^= (int) ((rNToGo == 1) ? 1 : 0); i2++; currentChar = ch2; @@ -949,7 +950,7 @@ namespace SharpCompress.Compressor.BZip2 } } rNToGo--; - z ^= (char)((rNToGo == 1) ? 1 : 0); + z ^= (char) ((rNToGo == 1) ? 1 : 0); j2 = 0; currentState = RAND_PART_C_STATE; SetupRandPartC(); @@ -964,7 +965,7 @@ namespace SharpCompress.Compressor.BZip2 private void SetupRandPartC() { - if (j2 < (int)z) + if (j2 < (int) z) { currentChar = ch2; mCrc.UpdateCRC(ch2); @@ -1008,7 +1009,7 @@ namespace SharpCompress.Compressor.BZip2 private void SetupNoRandPartC() { - if (j2 < (int)z) + if (j2 < (int) z) { currentChar = ch2; mCrc.UpdateCRC(ch2); @@ -1026,7 +1027,7 @@ namespace SharpCompress.Compressor.BZip2 private void SetDecompressStructureSizes(int newSize100k) { if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k - && blockSize100k <= 9)) + && blockSize100k <= 9)) { // throw new IOException("Invalid block size"); } @@ -1038,7 +1039,7 @@ namespace SharpCompress.Compressor.BZip2 return; } - int n = BZip2Constants.baseBlockSize * newSize100k; + int n = BZip2Constants.baseBlockSize*newSize100k; ll8 = new char[n]; tt = new int[n]; } @@ -1056,7 +1057,7 @@ namespace SharpCompress.Compressor.BZip2 c = ReadByte(); if (c == -1) break; - buffer[k + offset] = (byte)c; + buffer[k + offset] = (byte) c; } return k; } @@ -1076,45 +1077,28 @@ namespace SharpCompress.Compressor.BZip2 public override bool CanRead { - get - { - return true; - } + get { return true; } } public override bool CanSeek { - get - { - return false; - } + get { return false; } } public override bool CanWrite { - get - { - return false; - } + get { return false; } } public override long Length { - get - { - return 0; - } + get { return 0; } } public override long Position { - get - { - return 0; - } - set - { - } + get { return 0; } + set { } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/BZip2/CBZip2OutputStream.cs b/SharpCompress/Compressor/BZip2/CBZip2OutputStream.cs index f7125055..02faf223 100644 --- a/SharpCompress/Compressor/BZip2/CBZip2OutputStream.cs +++ b/SharpCompress/Compressor/BZip2/CBZip2OutputStream.cs @@ -1,4 +1,5 @@ using System.IO; + /* * Copyright 2001,2004-2005 The Apache Software Foundation * @@ -33,6 +34,7 @@ namespace SharpCompress.Compressor.BZip2 * NB: note this class has been modified to add a leading BZ to the * start of the BZIP2 stream to make it compatible with other PGP programs. */ + internal class CBZip2OutputStream : Stream { protected const int SETMASK = (1 << 21); @@ -67,8 +69,8 @@ namespace SharpCompress.Compressor.BZip2 { if (inUse[i]) { - seqToUnseq[nInUse] = (char)i; - unseqToSeq[i] = (char)nInUse; + seqToUnseq[nInUse] = (char) i; + unseqToSeq[i] = (char) nInUse; nInUse++; } } @@ -85,8 +87,8 @@ namespace SharpCompress.Compressor.BZip2 bool tooLong; int[] heap = new int[BZip2Constants.MAX_ALPHA_SIZE + 2]; - int[] weight = new int[BZip2Constants.MAX_ALPHA_SIZE * 2]; - int[] parent = new int[BZip2Constants.MAX_ALPHA_SIZE * 2]; + int[] weight = new int[BZip2Constants.MAX_ALPHA_SIZE*2]; + int[] parent = new int[BZip2Constants.MAX_ALPHA_SIZE*2]; for (i = 0; i < alphaSize; i++) { @@ -185,12 +187,12 @@ namespace SharpCompress.Compressor.BZip2 nNodes++; parent[n1] = parent[n2] = nNodes; - weight[nNodes] = (int)((uint)((weight[n1] & 0xffffff00) - + (weight[n2] & 0xffffff00)) - | (uint)(1 + (((weight[n1] & 0x000000ff) > - (weight[n2] & 0x000000ff)) ? - (weight[n1] & 0x000000ff) : - (weight[n2] & 0x000000ff)))); + weight[nNodes] = (int) ((uint) ((weight[n1] & 0xffffff00) + + (weight[n2] & 0xffffff00)) + | (uint) (1 + (((weight[n1] & 0x000000ff) > + (weight[n2] & 0x000000ff)) + ? (weight[n1] & 0x000000ff) + : (weight[n2] & 0x000000ff)))); parent[nNodes] = -1; nHeap++; @@ -207,7 +209,7 @@ namespace SharpCompress.Compressor.BZip2 heap[zz] = tmp; } } - if (!(nNodes < (BZip2Constants.MAX_ALPHA_SIZE * 2))) + if (!(nNodes < (BZip2Constants.MAX_ALPHA_SIZE*2))) { Panic(); } @@ -222,7 +224,7 @@ namespace SharpCompress.Compressor.BZip2 k = parent[k]; j++; } - len[i - 1] = (char)j; + len[i - 1] = (char) j; if (j > maxLen) { tooLong = true; @@ -237,7 +239,7 @@ namespace SharpCompress.Compressor.BZip2 for (i = 1; i < alphaSize; i++) { j = weight[i] >> 8; - j = 1 + (j / 2); + j = 1 + (j/2); weight[i] = j << 8; } } @@ -247,25 +249,25 @@ namespace SharpCompress.Compressor.BZip2 index of the last char in the block, so the block size == last + 1. */ - int last; + private int last; /* index in zptr[] of original string after sorting. */ - int origPtr; + private int origPtr; /* always: in the range 0 .. 9. The current block size is 100000 * this number. */ - int blockSize100k; + private int blockSize100k; - bool blockRandomised; + private bool blockRandomised; - int bytesOut; - int bsBuff; - int bsLive; - CRC mCrc = new CRC(); + private int bytesOut; + private int bsBuff; + private int bsLive; + private CRC mCrc = new CRC(); private bool[] inUse = new bool[256]; private int nInUse; @@ -317,8 +319,8 @@ namespace SharpCompress.Compressor.BZip2 zptr = null; ftab = null; - inStream.WriteByte((byte)'B'); - inStream.WriteByte((byte)'Z'); + inStream.WriteByte((byte) 'B'); + inStream.WriteByte((byte) 'Z'); BsSetStream(inStream, leaveOpen); @@ -342,9 +344,10 @@ namespace SharpCompress.Compressor.BZip2 * modified by Oliver Merkel, 010128 * */ + public override void WriteByte(byte bv) { - int b = (256 + bv) % 256; + int b = (256 + bv)%256; if (currentChar != -1) { if (currentChar == b) @@ -378,40 +381,40 @@ namespace SharpCompress.Compressor.BZip2 inUse[currentChar] = true; for (int i = 0; i < runLength; i++) { - mCrc.UpdateCRC((char)currentChar); + mCrc.UpdateCRC((char) currentChar); } switch (runLength) { case 1: last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; break; case 2: last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; break; case 3: last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; break; default: inUse[runLength - 4] = true; last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; last++; - block[last + 1] = (char)currentChar; + block[last + 1] = (char) currentChar; last++; - block[last + 1] = (char)(runLength - 4); + block[last + 1] = (char) (runLength - 4); break; } } @@ -423,7 +426,7 @@ namespace SharpCompress.Compressor.BZip2 } } - bool disposed = false; + private bool disposed = false; protected override void Dispose(bool disposing) { @@ -498,13 +501,13 @@ namespace SharpCompress.Compressor.BZip2 } /* 20 is just a paranoia constant */ - allowableBlockSize = BZip2Constants.baseBlockSize * blockSize100k - 20; + allowableBlockSize = BZip2Constants.baseBlockSize*blockSize100k - 20; } private void EndBlock() { blockCRC = mCrc.GetFinalCRC(); - combinedCRC = (combinedCRC << 1) | (int)(((uint)combinedCRC) >> 31); + combinedCRC = (combinedCRC << 1) | (int) (((uint) combinedCRC) >> 31); combinedCRC ^= blockCRC; /* sort the block and establish posn of original string */ @@ -570,7 +573,7 @@ namespace SharpCompress.Compressor.BZip2 } private void HbAssignCodes(int[] code, char[] length, int minLen, - int maxLen, int alphaSize) + int maxLen, int alphaSize) { int n, vec, i; @@ -584,7 +587,8 @@ namespace SharpCompress.Compressor.BZip2 code[i] = vec; vec++; } - }; + } + ; vec <<= 1; } } @@ -605,7 +609,7 @@ namespace SharpCompress.Compressor.BZip2 int ch = (bsBuff >> 24); try { - bsStream.WriteByte((byte)ch); // write 8-bit + bsStream.WriteByte((byte) ch); // write 8-bit } catch (IOException e) { @@ -624,7 +628,7 @@ namespace SharpCompress.Compressor.BZip2 int ch = (bsBuff >> 24); try { - bsStream.WriteByte((byte)ch); // write 8-bit + bsStream.WriteByte((byte) ch); // write 8-bit } catch (IOException e) { @@ -662,14 +666,14 @@ namespace SharpCompress.Compressor.BZip2 int v, t, i, j, gs, ge, totc, bt, bc, iter; int nSelectors = 0, alphaSize, minLen, maxLen, selCtr; - int nGroups;//, nBytes; + int nGroups; //, nBytes; alphaSize = nInUse + 2; for (t = 0; t < BZip2Constants.N_GROUPS; t++) { for (v = 0; v < alphaSize; v++) { - len[t][v] = (char)GREATER_ICOST; + len[t][v] = (char) GREATER_ICOST; } } @@ -709,7 +713,7 @@ namespace SharpCompress.Compressor.BZip2 gs = 0; while (nPart > 0) { - tFreq = remF / nPart; + tFreq = remF/nPart; ge = gs - 1; aFreq = 0; while (aFreq < tFreq && ge < alphaSize - 1) @@ -719,7 +723,7 @@ namespace SharpCompress.Compressor.BZip2 } if (ge > gs && nPart != nGroups && nPart != 1 - && ((nGroups - nPart) % 2 == 1)) + && ((nGroups - nPart)%2 == 1)) { aFreq -= mtfFreq[ge]; ge--; @@ -729,11 +733,11 @@ namespace SharpCompress.Compressor.BZip2 { if (v >= gs && v <= ge) { - len[nPart - 1][v] = (char)LESSER_ICOST; + len[nPart - 1][v] = (char) LESSER_ICOST; } else { - len[nPart - 1][v] = (char)GREATER_ICOST; + len[nPart - 1][v] = (char) GREATER_ICOST; } } @@ -769,7 +773,6 @@ namespace SharpCompress.Compressor.BZip2 gs = 0; while (true) { - /* Set group start & end marks. */ if (gs >= nMTF) { @@ -797,12 +800,12 @@ namespace SharpCompress.Compressor.BZip2 for (i = gs; i <= ge; i++) { short icv = szptr[i]; - cost0 += (short)len[0][icv]; - cost1 += (short)len[1][icv]; - cost2 += (short)len[2][icv]; - cost3 += (short)len[3][icv]; - cost4 += (short)len[4][icv]; - cost5 += (short)len[5][icv]; + cost0 += (short) len[0][icv]; + cost1 += (short) len[1][icv]; + cost2 += (short) len[2][icv]; + cost3 += (short) len[3][icv]; + cost4 += (short) len[4][icv]; + cost5 += (short) len[5][icv]; } cost[0] = cost0; cost[1] = cost1; @@ -818,7 +821,7 @@ namespace SharpCompress.Compressor.BZip2 short icv = szptr[i]; for (t = 0; t < nGroups; t++) { - cost[t] += (short)len[t][icv]; + cost[t] += (short) len[t][icv]; } } } @@ -836,10 +839,11 @@ namespace SharpCompress.Compressor.BZip2 bc = cost[t]; bt = t; } - }; + } + ; totc += bc; fave[bt]++; - selector[nSelectors] = (char)bt; + selector[nSelectors] = (char) bt; nSelectors++; /* @@ -870,7 +874,7 @@ namespace SharpCompress.Compressor.BZip2 { Panic(); } - if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / BZip2Constants.G_SIZE)))) + if (!(nSelectors < 32768 && nSelectors <= (2 + (900000/BZip2Constants.G_SIZE)))) { Panic(); } @@ -882,7 +886,7 @@ namespace SharpCompress.Compressor.BZip2 char ll_i, tmp2, tmp; for (i = 0; i < nGroups; i++) { - pos[i] = (char)i; + pos[i] = (char) i; } for (i = 0; i < nSelectors; i++) { @@ -897,7 +901,7 @@ namespace SharpCompress.Compressor.BZip2 pos[j] = tmp2; } pos[0] = tmp; - selectorMtf[i] = (char)j; + selectorMtf[i] = (char) j; } } @@ -938,7 +942,7 @@ namespace SharpCompress.Compressor.BZip2 inUse16[i] = false; for (j = 0; j < 16; j++) { - if (inUse[i * 16 + j]) + if (inUse[i*16 + j]) { inUse16[i] = true; } @@ -964,7 +968,7 @@ namespace SharpCompress.Compressor.BZip2 { for (j = 0; j < 16; j++) { - if (inUse[i * 16 + j]) + if (inUse[i*16 + j]) { BsW(1, 1); } @@ -975,7 +979,6 @@ namespace SharpCompress.Compressor.BZip2 } } } - } /* Now the selectors. */ @@ -1227,8 +1230,8 @@ namespace SharpCompress.Compressor.BZip2 } med = Med3(block[zptr[lo] + d + 1], - block[zptr[hi] + d + 1], - block[zptr[(lo + hi) >> 1] + d + 1]); + block[zptr[hi] + d + 1], + block[zptr[(lo + hi) >> 1] + d + 1]); unLo = ltLo = lo; unHi = gtHi = hi; @@ -1241,7 +1244,7 @@ namespace SharpCompress.Compressor.BZip2 { break; } - n = ((int)block[zptr[unLo] + d + 1]) - med; + n = ((int) block[zptr[unLo] + d + 1]) - med; if (n == 0) { int temp = 0; @@ -1251,7 +1254,8 @@ namespace SharpCompress.Compressor.BZip2 ltLo++; unLo++; continue; - }; + } + ; if (n > 0) { break; @@ -1264,7 +1268,7 @@ namespace SharpCompress.Compressor.BZip2 { break; } - n = ((int)block[zptr[unHi] + d + 1]) - med; + n = ((int) block[zptr[unHi] + d + 1]) - med; if (n == 0) { int temp = 0; @@ -1274,7 +1278,8 @@ namespace SharpCompress.Compressor.BZip2 gtHi--; unHi--; continue; - }; + } + ; if (n < 0) { break; @@ -1344,14 +1349,14 @@ namespace SharpCompress.Compressor.BZip2 // if (verbosity >= 4) fprintf ( stderr, " sort initialise ...\n" ); for (i = 0; i < BZip2Constants.NUM_OVERSHOOT_BYTES; i++) { - block[last + i + 2] = block[(i % (last + 1)) + 1]; + block[last + i + 2] = block[(i%(last + 1)) + 1]; } for (i = 0; i <= last + BZip2Constants.NUM_OVERSHOOT_BYTES; i++) { quadrant[i] = 0; } - block[0] = (char)(block[last + 1]); + block[0] = (char) (block[last + 1]); if (last < 4000) { @@ -1423,19 +1428,18 @@ namespace SharpCompress.Compressor.BZip2 int h = 1; do { - h = 3 * h + 1; - } - while (h <= 256); + h = 3*h + 1; + } while (h <= 256); do { - h = h / 3; + h = h/3; for (i = h; i <= 255; i++) { vv = runningOrder[i]; j = i; while ((ftab[((runningOrder[j - h]) + 1) << 8] - ftab[(runningOrder[j - h]) << 8]) > - (ftab[((vv) + 1) << 8] - ftab[(vv) << 8])) + (ftab[((vv) + 1) << 8] - ftab[(vv) << 8])) { runningOrder[j] = runningOrder[j - h]; j = j - h; @@ -1454,7 +1458,6 @@ namespace SharpCompress.Compressor.BZip2 */ for (i = 0; i <= 255; i++) { - /* Process big buckets, starting with the least full. */ @@ -1535,7 +1538,8 @@ namespace SharpCompress.Compressor.BZip2 } for (j = ftab[ss << 8] & CLEARMASK; - j < (ftab[(ss + 1) << 8] & CLEARMASK); j++) + j < (ftab[(ss + 1) << 8] & CLEARMASK); + j++) { c1 = block[zptr[j]]; if (!bigDone[c1]) @@ -1567,7 +1571,7 @@ namespace SharpCompress.Compressor.BZip2 { if (rNToGo == 0) { - rNToGo = (char)BZip2Constants.rNums[rTPos]; + rNToGo = (char) BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { @@ -1575,9 +1579,9 @@ namespace SharpCompress.Compressor.BZip2 } } rNToGo--; - block[i + 1] ^= (char)((rNToGo == 1) ? 1 : 0); + block[i + 1] ^= (char) ((rNToGo == 1) ? 1 : 0); // handle 16 bit signed numbers - block[i + 1] &= (char)0xFF; + block[i + 1] &= (char) 0xFF; inUse[block[i + 1]] = true; } @@ -1587,7 +1591,7 @@ namespace SharpCompress.Compressor.BZip2 { int i; - workLimit = workFactor * last; + workLimit = workFactor*last; workDone = 0; blockRandomised = false; firstAttempt = true; @@ -1611,7 +1615,8 @@ namespace SharpCompress.Compressor.BZip2 origPtr = i; break; } - }; + } + ; if (origPtr == -1) { @@ -1747,12 +1752,14 @@ namespace SharpCompress.Compressor.BZip2 { i1 -= last; i1--; - }; + } + ; if (i2 > last) { i2 -= last; i2--; - }; + } + ; k -= 4; workDone++; @@ -1767,13 +1774,17 @@ namespace SharpCompress.Compressor.BZip2 because the number of elems to sort is usually small, typically <= 20. */ - private int[] incs = { 1, 4, 13, 40, 121, 364, 1093, 3280, - 9841, 29524, 88573, 265720, - 797161, 2391484 }; + + private int[] incs = + { + 1, 4, 13, 40, 121, 364, 1093, 3280, + 9841, 29524, 88573, 265720, + 797161, 2391484 + }; private void AllocateCompressStructures() { - int n = BZip2Constants.baseBlockSize * blockSize100k; + int n = BZip2Constants.baseBlockSize*blockSize100k; block = new char[(n + 1 + BZip2Constants.NUM_OVERSHOOT_BYTES)]; quadrant = new int[(n + BZip2Constants.NUM_OVERSHOOT_BYTES)]; zptr = new int[n]; @@ -1799,7 +1810,7 @@ namespace SharpCompress.Compressor.BZip2 // szptr = zptr; - szptr = new short[2 * n]; + szptr = new short[2*n]; } private void GenerateMTFValues() @@ -1824,7 +1835,7 @@ namespace SharpCompress.Compressor.BZip2 zPend = 0; for (i = 0; i < nInUse; i++) { - yy[i] = (char)i; + yy[i] = (char) i; } @@ -1842,7 +1853,8 @@ namespace SharpCompress.Compressor.BZip2 tmp2 = tmp; tmp = yy[j]; yy[j] = tmp2; - }; + } + ; yy[0] = tmp; if (j == 0) @@ -1856,28 +1868,30 @@ namespace SharpCompress.Compressor.BZip2 zPend--; while (true) { - switch (zPend % 2) + switch (zPend%2) { case 0: - szptr[wr] = (short)BZip2Constants.RUNA; + szptr[wr] = (short) BZip2Constants.RUNA; wr++; mtfFreq[BZip2Constants.RUNA]++; break; case 1: - szptr[wr] = (short)BZip2Constants.RUNB; + szptr[wr] = (short) BZip2Constants.RUNB; wr++; mtfFreq[BZip2Constants.RUNB]++; break; - }; + } + ; if (zPend < 2) { break; } - zPend = (zPend - 2) / 2; - }; + zPend = (zPend - 2)/2; + } + ; zPend = 0; } - szptr[wr] = (short)(j + 1); + szptr[wr] = (short) (j + 1); wr++; mtfFreq[j + 1]++; } @@ -1888,15 +1902,15 @@ namespace SharpCompress.Compressor.BZip2 zPend--; while (true) { - switch (zPend % 2) + switch (zPend%2) { case 0: - szptr[wr] = (short)BZip2Constants.RUNA; + szptr[wr] = (short) BZip2Constants.RUNA; wr++; mtfFreq[BZip2Constants.RUNA]++; break; case 1: - szptr[wr] = (short)BZip2Constants.RUNB; + szptr[wr] = (short) BZip2Constants.RUNB; wr++; mtfFreq[BZip2Constants.RUNB]++; break; @@ -1905,11 +1919,11 @@ namespace SharpCompress.Compressor.BZip2 { break; } - zPend = (zPend - 2) / 2; + zPend = (zPend - 2)/2; } } - szptr[wr] = (short)EOB; + szptr[wr] = (short) EOB; wr++; mtfFreq[EOB]++; @@ -1940,45 +1954,28 @@ namespace SharpCompress.Compressor.BZip2 public override bool CanRead { - get - { - return false; - } + get { return false; } } public override bool CanSeek { - get - { - return false; - } + get { return false; } } public override bool CanWrite { - get - { - return true; - } + get { return true; } } public override long Length { - get - { - return 0; - } + get { return 0; } } public override long Position { - get - { - return 0; - } - set - { - } + get { return 0; } + set { } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/BZip2/CRC.cs b/SharpCompress/Compressor/BZip2/CRC.cs index a687ffd6..626297fb 100644 --- a/SharpCompress/Compressor/BZip2/CRC.cs +++ b/SharpCompress/Compressor/BZip2/CRC.cs @@ -1,5 +1,4 @@ - -/* +/* * Copyright 2001,2004-2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,74 +28,140 @@ namespace SharpCompress.Compressor.BZip2 * * @author Keiron Liddle */ + internal class CRC { - public static int[] crc32Table = { - unchecked((int)0x00000000), unchecked((int)0x04c11db7), unchecked((int)0x09823b6e), unchecked((int)0x0d4326d9), - unchecked((int)0x130476dc), unchecked((int)0x17c56b6b), unchecked((int)0x1a864db2), unchecked((int)0x1e475005), - unchecked((int)0x2608edb8), unchecked((int)0x22c9f00f), unchecked((int)0x2f8ad6d6), unchecked((int)0x2b4bcb61), - unchecked((int)0x350c9b64), unchecked((int)0x31cd86d3), unchecked((int)0x3c8ea00a), unchecked((int)0x384fbdbd), - unchecked((int)0x4c11db70), unchecked((int)0x48d0c6c7), unchecked((int)0x4593e01e), unchecked((int)0x4152fda9), - unchecked((int)0x5f15adac), unchecked((int)0x5bd4b01b), unchecked((int)0x569796c2), unchecked((int)0x52568b75), - unchecked((int)0x6a1936c8), unchecked((int)0x6ed82b7f), unchecked((int)0x639b0da6), unchecked((int)0x675a1011), - unchecked((int)0x791d4014), unchecked((int)0x7ddc5da3), unchecked((int)0x709f7b7a), unchecked((int)0x745e66cd), - unchecked((int)0x9823b6e0), unchecked((int)0x9ce2ab57), unchecked((int)0x91a18d8e), unchecked((int)0x95609039), - unchecked((int)0x8b27c03c), unchecked((int)0x8fe6dd8b), unchecked((int)0x82a5fb52), unchecked((int)0x8664e6e5), - unchecked((int)0xbe2b5b58), unchecked((int)0xbaea46ef), unchecked((int)0xb7a96036), unchecked((int)0xb3687d81), - unchecked((int)0xad2f2d84), unchecked((int)0xa9ee3033), unchecked((int)0xa4ad16ea), unchecked((int)0xa06c0b5d), - unchecked((int)0xd4326d90), unchecked((int)0xd0f37027), unchecked((int)0xddb056fe), unchecked((int)0xd9714b49), - unchecked((int)0xc7361b4c), unchecked((int)0xc3f706fb), unchecked((int)0xceb42022), unchecked((int)0xca753d95), - unchecked((int)0xf23a8028), unchecked((int)0xf6fb9d9f), unchecked((int)0xfbb8bb46), unchecked((int)0xff79a6f1), - unchecked((int)0xe13ef6f4), unchecked((int)0xe5ffeb43), unchecked((int)0xe8bccd9a), unchecked((int)0xec7dd02d), - unchecked((int)0x34867077), unchecked((int)0x30476dc0), unchecked((int)0x3d044b19), unchecked((int)0x39c556ae), - unchecked((int)0x278206ab), unchecked((int)0x23431b1c), unchecked((int)0x2e003dc5), unchecked((int)0x2ac12072), - unchecked((int)0x128e9dcf), unchecked((int)0x164f8078), unchecked((int)0x1b0ca6a1), unchecked((int)0x1fcdbb16), - unchecked((int)0x018aeb13), unchecked((int)0x054bf6a4), unchecked((int)0x0808d07d), unchecked((int)0x0cc9cdca), - unchecked((int)0x7897ab07), unchecked((int)0x7c56b6b0), unchecked((int)0x71159069), unchecked((int)0x75d48dde), - unchecked((int)0x6b93dddb), unchecked((int)0x6f52c06c), unchecked((int)0x6211e6b5), unchecked((int)0x66d0fb02), - unchecked((int)0x5e9f46bf), unchecked((int)0x5a5e5b08), unchecked((int)0x571d7dd1), unchecked((int)0x53dc6066), - unchecked((int)0x4d9b3063), unchecked((int)0x495a2dd4), unchecked((int)0x44190b0d), unchecked((int)0x40d816ba), - unchecked((int)0xaca5c697), unchecked((int)0xa864db20), unchecked((int)0xa527fdf9), unchecked((int)0xa1e6e04e), - unchecked((int)0xbfa1b04b), unchecked((int)0xbb60adfc), unchecked((int)0xb6238b25), unchecked((int)0xb2e29692), - unchecked((int)0x8aad2b2f), unchecked((int)0x8e6c3698), unchecked((int)0x832f1041), unchecked((int)0x87ee0df6), - unchecked((int)0x99a95df3), unchecked((int)0x9d684044), unchecked((int)0x902b669d), unchecked((int)0x94ea7b2a), - unchecked((int)0xe0b41de7), unchecked((int)0xe4750050), unchecked((int)0xe9362689), unchecked((int)0xedf73b3e), - unchecked((int)0xf3b06b3b), unchecked((int)0xf771768c), unchecked((int)0xfa325055), unchecked((int)0xfef34de2), - unchecked((int)0xc6bcf05f), unchecked((int)0xc27dede8), unchecked((int)0xcf3ecb31), unchecked((int)0xcbffd686), - unchecked((int)0xd5b88683), unchecked((int)0xd1799b34), unchecked((int)0xdc3abded), unchecked((int)0xd8fba05a), - unchecked((int)0x690ce0ee), unchecked((int)0x6dcdfd59), unchecked((int)0x608edb80), unchecked((int)0x644fc637), - unchecked((int)0x7a089632), unchecked((int)0x7ec98b85), unchecked((int)0x738aad5c), unchecked((int)0x774bb0eb), - unchecked((int)0x4f040d56), unchecked((int)0x4bc510e1), unchecked((int)0x46863638), unchecked((int)0x42472b8f), - unchecked((int)0x5c007b8a), unchecked((int)0x58c1663d), unchecked((int)0x558240e4), unchecked((int)0x51435d53), - unchecked((int)0x251d3b9e), unchecked((int)0x21dc2629), unchecked((int)0x2c9f00f0), unchecked((int)0x285e1d47), - unchecked((int)0x36194d42), unchecked((int)0x32d850f5), unchecked((int)0x3f9b762c), unchecked((int)0x3b5a6b9b), - unchecked((int)0x0315d626), unchecked((int)0x07d4cb91), unchecked((int)0x0a97ed48), unchecked((int)0x0e56f0ff), - unchecked((int)0x1011a0fa), unchecked((int)0x14d0bd4d), unchecked((int)0x19939b94), unchecked((int)0x1d528623), - unchecked((int)0xf12f560e), unchecked((int)0xf5ee4bb9), unchecked((int)0xf8ad6d60), unchecked((int)0xfc6c70d7), - unchecked((int)0xe22b20d2), unchecked((int)0xe6ea3d65), unchecked((int)0xeba91bbc), unchecked((int)0xef68060b), - unchecked((int)0xd727bbb6), unchecked((int)0xd3e6a601), unchecked((int)0xdea580d8), unchecked((int)0xda649d6f), - unchecked((int)0xc423cd6a), unchecked((int)0xc0e2d0dd), unchecked((int)0xcda1f604), unchecked((int)0xc960ebb3), - unchecked((int)0xbd3e8d7e), unchecked((int)0xb9ff90c9), unchecked((int)0xb4bcb610), unchecked((int)0xb07daba7), - unchecked((int)0xae3afba2), unchecked((int)0xaafbe615), unchecked((int)0xa7b8c0cc), unchecked((int)0xa379dd7b), - unchecked((int)0x9b3660c6), unchecked((int)0x9ff77d71), unchecked((int)0x92b45ba8), unchecked((int)0x9675461f), - unchecked((int)0x8832161a), unchecked((int)0x8cf30bad), unchecked((int)0x81b02d74), unchecked((int)0x857130c3), - unchecked((int)0x5d8a9099), unchecked((int)0x594b8d2e), unchecked((int)0x5408abf7), unchecked((int)0x50c9b640), - unchecked((int)0x4e8ee645), unchecked((int)0x4a4ffbf2), unchecked((int)0x470cdd2b), unchecked((int)0x43cdc09c), - unchecked((int)0x7b827d21), unchecked((int)0x7f436096), unchecked((int)0x7200464f), unchecked((int)0x76c15bf8), - unchecked((int)0x68860bfd), unchecked((int)0x6c47164a), unchecked((int)0x61043093), unchecked((int)0x65c52d24), - unchecked((int)0x119b4be9), unchecked((int)0x155a565e), unchecked((int)0x18197087), unchecked((int)0x1cd86d30), - unchecked((int)0x029f3d35), unchecked((int)0x065e2082), unchecked((int)0x0b1d065b), unchecked((int)0x0fdc1bec), - unchecked((int)0x3793a651), unchecked((int)0x3352bbe6), unchecked((int)0x3e119d3f), unchecked((int)0x3ad08088), - unchecked((int)0x2497d08d), unchecked((int)0x2056cd3a), unchecked((int)0x2d15ebe3), unchecked((int)0x29d4f654), - unchecked((int)0xc5a92679), unchecked((int)0xc1683bce), unchecked((int)0xcc2b1d17), unchecked((int)0xc8ea00a0), - unchecked((int)0xd6ad50a5), unchecked((int)0xd26c4d12), unchecked((int)0xdf2f6bcb), unchecked((int)0xdbee767c), - unchecked((int)0xe3a1cbc1), unchecked((int)0xe760d676), unchecked((int)0xea23f0af), unchecked((int)0xeee2ed18), - unchecked((int)0xf0a5bd1d), unchecked((int)0xf464a0aa), unchecked((int)0xf9278673), unchecked((int)0xfde69bc4), - unchecked((int)0x89b8fd09), unchecked((int)0x8d79e0be), unchecked((int)0x803ac667), unchecked((int)0x84fbdbd0), - unchecked((int)0x9abc8bd5), unchecked((int)0x9e7d9662), unchecked((int)0x933eb0bb), unchecked((int)0x97ffad0c), - unchecked((int)0xafb010b1), unchecked((int)0xab710d06), unchecked((int)0xa6322bdf), unchecked((int)0xa2f33668), - unchecked((int)0xbcb4666d), unchecked((int)0xb8757bda), unchecked((int)0xb5365d03), unchecked((int)0xb1f740b4) - }; + public static int[] crc32Table = + { + unchecked((int) 0x00000000), unchecked((int) 0x04c11db7), unchecked((int) 0x09823b6e), + unchecked((int) 0x0d4326d9), + unchecked((int) 0x130476dc), unchecked((int) 0x17c56b6b), unchecked((int) 0x1a864db2), + unchecked((int) 0x1e475005), + unchecked((int) 0x2608edb8), unchecked((int) 0x22c9f00f), unchecked((int) 0x2f8ad6d6), + unchecked((int) 0x2b4bcb61), + unchecked((int) 0x350c9b64), unchecked((int) 0x31cd86d3), unchecked((int) 0x3c8ea00a), + unchecked((int) 0x384fbdbd), + unchecked((int) 0x4c11db70), unchecked((int) 0x48d0c6c7), unchecked((int) 0x4593e01e), + unchecked((int) 0x4152fda9), + unchecked((int) 0x5f15adac), unchecked((int) 0x5bd4b01b), unchecked((int) 0x569796c2), + unchecked((int) 0x52568b75), + unchecked((int) 0x6a1936c8), unchecked((int) 0x6ed82b7f), unchecked((int) 0x639b0da6), + unchecked((int) 0x675a1011), + unchecked((int) 0x791d4014), unchecked((int) 0x7ddc5da3), unchecked((int) 0x709f7b7a), + unchecked((int) 0x745e66cd), + unchecked((int) 0x9823b6e0), unchecked((int) 0x9ce2ab57), unchecked((int) 0x91a18d8e), + unchecked((int) 0x95609039), + unchecked((int) 0x8b27c03c), unchecked((int) 0x8fe6dd8b), unchecked((int) 0x82a5fb52), + unchecked((int) 0x8664e6e5), + unchecked((int) 0xbe2b5b58), unchecked((int) 0xbaea46ef), unchecked((int) 0xb7a96036), + unchecked((int) 0xb3687d81), + unchecked((int) 0xad2f2d84), unchecked((int) 0xa9ee3033), unchecked((int) 0xa4ad16ea), + unchecked((int) 0xa06c0b5d), + unchecked((int) 0xd4326d90), unchecked((int) 0xd0f37027), unchecked((int) 0xddb056fe), + unchecked((int) 0xd9714b49), + unchecked((int) 0xc7361b4c), unchecked((int) 0xc3f706fb), unchecked((int) 0xceb42022), + unchecked((int) 0xca753d95), + unchecked((int) 0xf23a8028), unchecked((int) 0xf6fb9d9f), unchecked((int) 0xfbb8bb46), + unchecked((int) 0xff79a6f1), + unchecked((int) 0xe13ef6f4), unchecked((int) 0xe5ffeb43), unchecked((int) 0xe8bccd9a), + unchecked((int) 0xec7dd02d), + unchecked((int) 0x34867077), unchecked((int) 0x30476dc0), unchecked((int) 0x3d044b19), + unchecked((int) 0x39c556ae), + unchecked((int) 0x278206ab), unchecked((int) 0x23431b1c), unchecked((int) 0x2e003dc5), + unchecked((int) 0x2ac12072), + unchecked((int) 0x128e9dcf), unchecked((int) 0x164f8078), unchecked((int) 0x1b0ca6a1), + unchecked((int) 0x1fcdbb16), + unchecked((int) 0x018aeb13), unchecked((int) 0x054bf6a4), unchecked((int) 0x0808d07d), + unchecked((int) 0x0cc9cdca), + unchecked((int) 0x7897ab07), unchecked((int) 0x7c56b6b0), unchecked((int) 0x71159069), + unchecked((int) 0x75d48dde), + unchecked((int) 0x6b93dddb), unchecked((int) 0x6f52c06c), unchecked((int) 0x6211e6b5), + unchecked((int) 0x66d0fb02), + unchecked((int) 0x5e9f46bf), unchecked((int) 0x5a5e5b08), unchecked((int) 0x571d7dd1), + unchecked((int) 0x53dc6066), + unchecked((int) 0x4d9b3063), unchecked((int) 0x495a2dd4), unchecked((int) 0x44190b0d), + unchecked((int) 0x40d816ba), + unchecked((int) 0xaca5c697), unchecked((int) 0xa864db20), unchecked((int) 0xa527fdf9), + unchecked((int) 0xa1e6e04e), + unchecked((int) 0xbfa1b04b), unchecked((int) 0xbb60adfc), unchecked((int) 0xb6238b25), + unchecked((int) 0xb2e29692), + unchecked((int) 0x8aad2b2f), unchecked((int) 0x8e6c3698), unchecked((int) 0x832f1041), + unchecked((int) 0x87ee0df6), + unchecked((int) 0x99a95df3), unchecked((int) 0x9d684044), unchecked((int) 0x902b669d), + unchecked((int) 0x94ea7b2a), + unchecked((int) 0xe0b41de7), unchecked((int) 0xe4750050), unchecked((int) 0xe9362689), + unchecked((int) 0xedf73b3e), + unchecked((int) 0xf3b06b3b), unchecked((int) 0xf771768c), unchecked((int) 0xfa325055), + unchecked((int) 0xfef34de2), + unchecked((int) 0xc6bcf05f), unchecked((int) 0xc27dede8), unchecked((int) 0xcf3ecb31), + unchecked((int) 0xcbffd686), + unchecked((int) 0xd5b88683), unchecked((int) 0xd1799b34), unchecked((int) 0xdc3abded), + unchecked((int) 0xd8fba05a), + unchecked((int) 0x690ce0ee), unchecked((int) 0x6dcdfd59), unchecked((int) 0x608edb80), + unchecked((int) 0x644fc637), + unchecked((int) 0x7a089632), unchecked((int) 0x7ec98b85), unchecked((int) 0x738aad5c), + unchecked((int) 0x774bb0eb), + unchecked((int) 0x4f040d56), unchecked((int) 0x4bc510e1), unchecked((int) 0x46863638), + unchecked((int) 0x42472b8f), + unchecked((int) 0x5c007b8a), unchecked((int) 0x58c1663d), unchecked((int) 0x558240e4), + unchecked((int) 0x51435d53), + unchecked((int) 0x251d3b9e), unchecked((int) 0x21dc2629), unchecked((int) 0x2c9f00f0), + unchecked((int) 0x285e1d47), + unchecked((int) 0x36194d42), unchecked((int) 0x32d850f5), unchecked((int) 0x3f9b762c), + unchecked((int) 0x3b5a6b9b), + unchecked((int) 0x0315d626), unchecked((int) 0x07d4cb91), unchecked((int) 0x0a97ed48), + unchecked((int) 0x0e56f0ff), + unchecked((int) 0x1011a0fa), unchecked((int) 0x14d0bd4d), unchecked((int) 0x19939b94), + unchecked((int) 0x1d528623), + unchecked((int) 0xf12f560e), unchecked((int) 0xf5ee4bb9), unchecked((int) 0xf8ad6d60), + unchecked((int) 0xfc6c70d7), + unchecked((int) 0xe22b20d2), unchecked((int) 0xe6ea3d65), unchecked((int) 0xeba91bbc), + unchecked((int) 0xef68060b), + unchecked((int) 0xd727bbb6), unchecked((int) 0xd3e6a601), unchecked((int) 0xdea580d8), + unchecked((int) 0xda649d6f), + unchecked((int) 0xc423cd6a), unchecked((int) 0xc0e2d0dd), unchecked((int) 0xcda1f604), + unchecked((int) 0xc960ebb3), + unchecked((int) 0xbd3e8d7e), unchecked((int) 0xb9ff90c9), unchecked((int) 0xb4bcb610), + unchecked((int) 0xb07daba7), + unchecked((int) 0xae3afba2), unchecked((int) 0xaafbe615), unchecked((int) 0xa7b8c0cc), + unchecked((int) 0xa379dd7b), + unchecked((int) 0x9b3660c6), unchecked((int) 0x9ff77d71), unchecked((int) 0x92b45ba8), + unchecked((int) 0x9675461f), + unchecked((int) 0x8832161a), unchecked((int) 0x8cf30bad), unchecked((int) 0x81b02d74), + unchecked((int) 0x857130c3), + unchecked((int) 0x5d8a9099), unchecked((int) 0x594b8d2e), unchecked((int) 0x5408abf7), + unchecked((int) 0x50c9b640), + unchecked((int) 0x4e8ee645), unchecked((int) 0x4a4ffbf2), unchecked((int) 0x470cdd2b), + unchecked((int) 0x43cdc09c), + unchecked((int) 0x7b827d21), unchecked((int) 0x7f436096), unchecked((int) 0x7200464f), + unchecked((int) 0x76c15bf8), + unchecked((int) 0x68860bfd), unchecked((int) 0x6c47164a), unchecked((int) 0x61043093), + unchecked((int) 0x65c52d24), + unchecked((int) 0x119b4be9), unchecked((int) 0x155a565e), unchecked((int) 0x18197087), + unchecked((int) 0x1cd86d30), + unchecked((int) 0x029f3d35), unchecked((int) 0x065e2082), unchecked((int) 0x0b1d065b), + unchecked((int) 0x0fdc1bec), + unchecked((int) 0x3793a651), unchecked((int) 0x3352bbe6), unchecked((int) 0x3e119d3f), + unchecked((int) 0x3ad08088), + unchecked((int) 0x2497d08d), unchecked((int) 0x2056cd3a), unchecked((int) 0x2d15ebe3), + unchecked((int) 0x29d4f654), + unchecked((int) 0xc5a92679), unchecked((int) 0xc1683bce), unchecked((int) 0xcc2b1d17), + unchecked((int) 0xc8ea00a0), + unchecked((int) 0xd6ad50a5), unchecked((int) 0xd26c4d12), unchecked((int) 0xdf2f6bcb), + unchecked((int) 0xdbee767c), + unchecked((int) 0xe3a1cbc1), unchecked((int) 0xe760d676), unchecked((int) 0xea23f0af), + unchecked((int) 0xeee2ed18), + unchecked((int) 0xf0a5bd1d), unchecked((int) 0xf464a0aa), unchecked((int) 0xf9278673), + unchecked((int) 0xfde69bc4), + unchecked((int) 0x89b8fd09), unchecked((int) 0x8d79e0be), unchecked((int) 0x803ac667), + unchecked((int) 0x84fbdbd0), + unchecked((int) 0x9abc8bd5), unchecked((int) 0x9e7d9662), unchecked((int) 0x933eb0bb), + unchecked((int) 0x97ffad0c), + unchecked((int) 0xafb010b1), unchecked((int) 0xab710d06), unchecked((int) 0xa6322bdf), + unchecked((int) 0xa2f33668), + unchecked((int) 0xbcb4666d), unchecked((int) 0xb8757bda), unchecked((int) 0xb5365d03), + unchecked((int) 0xb1f740b4) + }; public CRC() { @@ -105,7 +170,7 @@ namespace SharpCompress.Compressor.BZip2 internal void InitialiseCRC() { - globalCrc = unchecked((int)0xffffffff); + globalCrc = unchecked((int) 0xffffffff); } internal int GetFinalCRC() @@ -135,4 +200,4 @@ namespace SharpCompress.Compressor.BZip2 internal int globalCrc; } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/CompressionMode.cs b/SharpCompress/Compressor/CompressionMode.cs index 4224a4ec..29dc4923 100644 --- a/SharpCompress/Compressor/CompressionMode.cs +++ b/SharpCompress/Compressor/CompressionMode.cs @@ -1,9 +1,8 @@ - -namespace SharpCompress.Compressor +namespace SharpCompress.Compressor { public enum CompressionMode { Compress = 0, Decompress = 1, } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Deflate/CRC32.cs b/SharpCompress/Compressor/Deflate/CRC32.cs index 0187fb6d..4cc14fff 100644 --- a/SharpCompress/Compressor/Deflate/CRC32.cs +++ b/SharpCompress/Compressor/Deflate/CRC32.cs @@ -102,7 +102,7 @@ namespace SharpCompress.Compressor.Deflate get { // return one's complement of the running result - return unchecked((Int32)(~runningCrc32Result)); + return unchecked((Int32) (~runningCrc32Result)); } } @@ -147,7 +147,7 @@ namespace SharpCompress.Compressor.Deflate totalBytesRead += count; } - return (Int32)(~runningCrc32Result); + return (Int32) (~runningCrc32Result); } } @@ -161,12 +161,12 @@ namespace SharpCompress.Compressor.Deflate /// The CRC-ized result. public Int32 ComputeCrc32(Int32 W, byte B) { - return _InternalComputeCrc32((UInt32)W, B); + return _InternalComputeCrc32((UInt32) W, B); } internal Int32 _InternalComputeCrc32(UInt32 W, byte B) { - return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8)); + return (Int32) (crc32Table[(W ^ B) & 0xFF] ^ (W >> 8)); } /// @@ -185,7 +185,7 @@ namespace SharpCompress.Compressor.Deflate { int x = offset + i; runningCrc32Result = ((runningCrc32Result) >> 8) ^ - crc32Table[(block[x]) ^ ((runningCrc32Result) & 0x000000FF)]; + crc32Table[(block[x]) ^ ((runningCrc32Result) & 0x000000FF)]; } totalBytesRead += count; } @@ -234,7 +234,7 @@ namespace SharpCompress.Compressor.Deflate return; uint crc1 = ~runningCrc32Result; - var crc2 = (uint)crc; + var crc2 = (uint) crc; // put operator for one zero bit in odd odd[0] = 0xEDB88320; // the CRC-32 polynomial @@ -251,7 +251,7 @@ namespace SharpCompress.Compressor.Deflate // put operator for four zero bits in odd gf2_matrix_square(odd, even); - var len2 = (uint)length; + var len2 = (uint) length; // apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even) diff --git a/SharpCompress/Compressor/Deflate/DeflateManager.cs b/SharpCompress/Compressor/Deflate/DeflateManager.cs index 59ec57a9..dba464ac 100644 --- a/SharpCompress/Compressor/Deflate/DeflateManager.cs +++ b/SharpCompress/Compressor/Deflate/DeflateManager.cs @@ -75,24 +75,24 @@ namespace SharpCompress.Compressor.Deflate { // extra bits for each length code internal static readonly int[] ExtraLengthBits = new int[] - { - 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, 0 - }; + { + 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, 0 + }; // extra bits for each distance code internal static readonly int[] ExtraDistanceBits = new int[] - { - 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 - }; + { + 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 + }; internal enum BlockState { - NeedMore = 0, // block not completed, need more input or more output - BlockDone, // block flush performed - FinishStarted, // finish started, need only more output at next deflate - FinishDone // finish done, accept no more input or output + NeedMore = 0, // block not completed, need more input or more output + BlockDone, // block flush performed + FinishStarted, // finish started, need only more output at next deflate + FinishDone // finish done, accept no more input or output } internal enum DeflateFlavor @@ -117,7 +117,7 @@ namespace SharpCompress.Compressor.Deflate // compression levels >= 4. For levels 1,2,3: MaxLazy is actually // MaxInsertLength. (See DeflateFast) - internal int MaxLazy; // do not perform lazy search above this match length + internal int MaxLazy; // do not perform lazy search above this match length internal int NiceLength; // quit search above this match length @@ -139,25 +139,25 @@ namespace SharpCompress.Compressor.Deflate public static Config Lookup(CompressionLevel level) { - return Table[(int)level]; + return Table[(int) level]; } static Config() { - Table = new Config[] { - new Config(0, 0, 0, 0, DeflateFlavor.Store), - new Config(4, 4, 8, 4, DeflateFlavor.Fast), - new Config(4, 5, 16, 8, DeflateFlavor.Fast), - new Config(4, 6, 32, 32, DeflateFlavor.Fast), - - new Config(4, 4, 16, 16, DeflateFlavor.Slow), - new Config(8, 16, 32, 32, DeflateFlavor.Slow), - new Config(8, 16, 128, 128, DeflateFlavor.Slow), - new Config(8, 32, 128, 256, DeflateFlavor.Slow), - new Config(32, 128, 258, 1024, DeflateFlavor.Slow), - new Config(32, 258, 258, 4096, DeflateFlavor.Slow), - }; + Table = new Config[] + { + new Config(0, 0, 0, 0, DeflateFlavor.Store), + new Config(4, 4, 8, 4, DeflateFlavor.Fast), + new Config(4, 5, 16, 8, DeflateFlavor.Fast), + new Config(4, 6, 32, 32, DeflateFlavor.Fast), + new Config(4, 4, 16, 16, DeflateFlavor.Slow), + new Config(8, 16, 32, 32, DeflateFlavor.Slow), + new Config(8, 16, 128, 128, DeflateFlavor.Slow), + new Config(8, 32, 128, 256, DeflateFlavor.Slow), + new Config(32, 128, 258, 1024, DeflateFlavor.Slow), + new Config(32, 258, 258, 4096, DeflateFlavor.Slow), + }; } private static readonly Config[] Table; @@ -167,18 +167,18 @@ namespace SharpCompress.Compressor.Deflate private CompressFunc DeflateFunction; private static readonly System.String[] _ErrorMessage = new System.String[] - { - "need dictionary", - "stream end", - "", - "file error", - "stream error", - "data error", - "insufficient memory", - "buffer error", - "incompatible version", - "" - }; + { + "need dictionary", + "stream end", + "", + "file error", + "stream error", + "data error", + "insufficient memory", + "buffer error", + "incompatible version", + "" + }; // preset dictionary flag in zlib header private const int PRESET_DICT = 0x20; @@ -199,29 +199,29 @@ namespace SharpCompress.Compressor.Deflate private const int Z_ASCII = 1; private const int Z_UNKNOWN = 2; - private const int Buf_size = 8 * 2; + private const int Buf_size = 8*2; private const int MIN_MATCH = 3; private const int MAX_MATCH = 258; private const int MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); - private static readonly int HEAP_SIZE = (2 * InternalConstants.L_CODES + 1); + private static readonly int HEAP_SIZE = (2*InternalConstants.L_CODES + 1); private const int END_BLOCK = 256; internal ZlibCodec _codec; // the zlib encoder/decoder - internal int status; // as the name implies - internal byte[] pending; // output still pending - waiting to be compressed - internal int nextPending; // index of next pending byte to output to the stream + internal int status; // as the name implies + internal byte[] pending; // output still pending - waiting to be compressed + internal int nextPending; // index of next pending byte to output to the stream internal int pendingCount; // number of bytes in the pending buffer - internal sbyte data_type; // UNKNOWN, BINARY or ASCII - internal int last_flush; // value of flush param for previous deflate call + internal sbyte data_type; // UNKNOWN, BINARY or ASCII + internal int last_flush; // value of flush param for previous deflate call - internal int w_size; // LZ77 window size (32K by default) - internal int w_bits; // log2(w_size) (8..16) - internal int w_mask; // w_size - 1 + internal int w_size; // LZ77 window size (32K by default) + internal int w_bits; // log2(w_size) (8..16) + internal int w_mask; // w_size - 1 //internal byte[] dictionary; internal byte[] window; @@ -243,9 +243,9 @@ namespace SharpCompress.Compressor.Deflate // array to 64K, this link is maintained only for the last 32K strings. // An index in this array is thus a window index modulo 32K. - private short[] head; // Heads of the hash chains or NIL. + private short[] head; // Heads of the hash chains or NIL. - private int ins_h; // hash index of string to be inserted + private int ins_h; // hash index of string to be inserted private int hash_size; // number of elements in hash table private int hash_bits; // log2(hash_size) private int hash_mask; // hash_size-1 @@ -262,12 +262,12 @@ namespace SharpCompress.Compressor.Deflate private int blockStart; private Config config; - private int match_length; // length of best match - private int prev_match; // previous match + private int match_length; // length of best match + private int prev_match; // previous match private int match_available; // set if previous match exists - private int strstart; // start of string to insert into.....???? - private int match_start; // start of matching string - private int lookahead; // number of valid bytes ahead in window + private int strstart; // start of string to insert into.....???? + private int match_start; // start of matching string + private int lookahead; // number of valid bytes ahead in window // Length of the best match at previous step. Matches not greater than this // are discarded. This is used in the lazy match evaluation. @@ -281,30 +281,30 @@ namespace SharpCompress.Compressor.Deflate private CompressionStrategy compressionStrategy; // favor or force Huffman coding - private short[] dyn_ltree; // literal and length tree - private short[] dyn_dtree; // distance tree - private short[] bl_tree; // Huffman tree for bit lengths + private short[] dyn_ltree; // literal and length tree + private short[] dyn_dtree; // distance tree + private short[] bl_tree; // Huffman tree for bit lengths - private Tree treeLiterals = new Tree(); // desc for literal tree - private Tree treeDistances = new Tree(); // desc for distance tree + private Tree treeLiterals = new Tree(); // desc for literal tree + private Tree treeDistances = new Tree(); // desc for distance tree private Tree treeBitLengths = new Tree(); // desc for bit length tree // number of codes at each bit length for an optimal tree private short[] bl_count = new short[InternalConstants.MAX_BITS + 1]; // heap used to build the Huffman trees - private int[] heap = new int[2 * InternalConstants.L_CODES + 1]; + private int[] heap = new int[2*InternalConstants.L_CODES + 1]; - private int heap_len; // number of elements in the heap - private int heap_max; // element of largest frequency + private int heap_len; // number of elements in the heap + private int heap_max; // element of largest frequency // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. // The same heap array is used to build all trees. // Depth of each subtree used as tie breaker for trees of equal frequency - private sbyte[] depth = new sbyte[2 * InternalConstants.L_CODES + 1]; + private sbyte[] depth = new sbyte[2*InternalConstants.L_CODES + 1]; - private int _lengthOffset; // index for literals or lengths + private int _lengthOffset; // index for literals or lengths // Size of match buffer for literals/lengths. There are 4 reasons for @@ -326,17 +326,17 @@ namespace SharpCompress.Compressor.Deflate internal int lit_bufsize; - internal int last_lit; // running index in l_buf + internal int last_lit; // running index in l_buf // Buffer for distances. To simplify the code, d_buf and l_buf have // the same number of elements. To use different lengths, an extra flag // array would be necessary. - internal int _distanceOffset; // index into pending; points to distance data?? + internal int _distanceOffset; // index into pending; points to distance data?? - internal int opt_len; // bit length of current block with optimal trees - internal int static_len; // bit length of current block with static trees - internal int matches; // number of string matches in current block + internal int opt_len; // bit length of current block with optimal trees + internal int static_len; // bit length of current block with static trees + internal int matches; // number of string matches in current block internal int last_eob_len; // bit length of EOB code for last block // Output buffer. bits are inserted starting at the bottom (least @@ -350,16 +350,16 @@ namespace SharpCompress.Compressor.Deflate internal DeflateManager() { - dyn_ltree = new short[HEAP_SIZE * 2]; - dyn_dtree = new short[(2 * InternalConstants.D_CODES + 1) * 2]; // distance tree - bl_tree = new short[(2 * InternalConstants.BL_CODES + 1) * 2]; // Huffman tree for bit lengths + dyn_ltree = new short[HEAP_SIZE*2]; + dyn_dtree = new short[(2*InternalConstants.D_CODES + 1)*2]; // distance tree + bl_tree = new short[(2*InternalConstants.BL_CODES + 1)*2]; // Huffman tree for bit lengths } // lm_init private void _InitializeLazyMatch() { - window_size = 2 * w_size; + window_size = 2*w_size; // clear the hash - workitem 9063 Array.Clear(head, 0, hash_size); @@ -400,13 +400,13 @@ namespace SharpCompress.Compressor.Deflate { // Initialize the trees. for (int i = 0; i < InternalConstants.L_CODES; i++) - dyn_ltree[i * 2] = 0; + dyn_ltree[i*2] = 0; for (int i = 0; i < InternalConstants.D_CODES; i++) - dyn_dtree[i * 2] = 0; + dyn_dtree[i*2] = 0; for (int i = 0; i < InternalConstants.BL_CODES; i++) - bl_tree[i * 2] = 0; + bl_tree[i*2] = 0; - dyn_ltree[END_BLOCK * 2] = 1; + dyn_ltree[END_BLOCK*2] = 1; opt_len = static_len = 0; last_lit = matches = 0; } @@ -431,7 +431,8 @@ namespace SharpCompress.Compressor.Deflate break; // Exchange v with the smallest son - heap[k] = heap[j]; k = j; + heap[k] = heap[j]; + k = j; // And continue down the tree, setting j to the left son of k j <<= 1; } @@ -440,8 +441,8 @@ namespace SharpCompress.Compressor.Deflate internal static bool IsSmaller(short[] tree, int n, int m, sbyte[] depth) { - short tn2 = tree[n * 2]; - short tm2 = tree[m * 2]; + short tn2 = tree[n*2]; + short tm2 = tree[m*2]; return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m])); } @@ -453,54 +454,60 @@ namespace SharpCompress.Compressor.Deflate int n; // iterates over all tree elements int prevlen = -1; // last emitted length int curlen; // length of current code - int nextlen = (int)tree[0 * 2 + 1]; // length of next code + int nextlen = (int) tree[0*2 + 1]; // length of next code int count = 0; // repeat count of the current code int max_count = 7; // max repeat count int min_count = 4; // min repeat count if (nextlen == 0) { - max_count = 138; min_count = 3; + max_count = 138; + min_count = 3; } - tree[(maxCode + 1) * 2 + 1] = (short)0x7fff; // guard //?? + tree[(maxCode + 1)*2 + 1] = (short) 0x7fff; // guard //?? for (n = 0; n <= maxCode; n++) { - curlen = nextlen; nextlen = (int)tree[(n + 1) * 2 + 1]; + curlen = nextlen; + nextlen = (int) tree[(n + 1)*2 + 1]; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { - bl_tree[curlen * 2] = (short)(bl_tree[curlen * 2] + count); + bl_tree[curlen*2] = (short) (bl_tree[curlen*2] + count); } else if (curlen != 0) { if (curlen != prevlen) - bl_tree[curlen * 2]++; - bl_tree[InternalConstants.REP_3_6 * 2]++; + bl_tree[curlen*2]++; + bl_tree[InternalConstants.REP_3_6*2]++; } else if (count <= 10) { - bl_tree[InternalConstants.REPZ_3_10 * 2]++; + bl_tree[InternalConstants.REPZ_3_10*2]++; } else { - bl_tree[InternalConstants.REPZ_11_138 * 2]++; + bl_tree[InternalConstants.REPZ_11_138*2]++; } - count = 0; prevlen = curlen; + count = 0; + prevlen = curlen; if (nextlen == 0) { - max_count = 138; min_count = 3; + max_count = 138; + min_count = 3; } else if (curlen == nextlen) { - max_count = 6; min_count = 3; + max_count = 6; + min_count = 3; } else { - max_count = 7; min_count = 4; + max_count = 7; + min_count = 4; } } } @@ -525,11 +532,11 @@ namespace SharpCompress.Compressor.Deflate // 3 but the actual value used is 4.) for (max_blindex = InternalConstants.BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] != 0) + if (bl_tree[Tree.bl_order[max_blindex]*2 + 1] != 0) break; } // Update opt_len to include the bit length tree and counts - opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + opt_len += 3*(max_blindex + 1) + 5 + 5 + 4; return max_blindex; } @@ -547,7 +554,7 @@ namespace SharpCompress.Compressor.Deflate send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt for (rank = 0; rank < blcodes; rank++) { - send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3); + send_bits(bl_tree[Tree.bl_order[rank]*2 + 1], 3); } send_tree(dyn_ltree, lcodes - 1); // literal tree send_tree(dyn_dtree, dcodes - 1); // distance tree @@ -557,22 +564,24 @@ namespace SharpCompress.Compressor.Deflate // bl_tree. internal void send_tree(short[] tree, int max_code) { - int n; // iterates over all tree elements - int prevlen = -1; // last emitted length - int curlen; // length of current code - int nextlen = tree[0 * 2 + 1]; // length of next code - int count = 0; // repeat count of the current code - int max_count = 7; // max repeat count - int min_count = 4; // min repeat count + int n; // iterates over all tree elements + int prevlen = -1; // last emitted length + int curlen; // length of current code + int nextlen = tree[0*2 + 1]; // length of next code + int count = 0; // repeat count of the current code + int max_count = 7; // max repeat count + int min_count = 4; // min repeat count if (nextlen == 0) { - max_count = 138; min_count = 3; + max_count = 138; + min_count = 3; } for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]; + curlen = nextlen; + nextlen = tree[(n + 1)*2 + 1]; if (++count < max_count && curlen == nextlen) { continue; @@ -582,14 +591,14 @@ namespace SharpCompress.Compressor.Deflate do { send_code(curlen, bl_tree); - } - while (--count != 0); + } while (--count != 0); } else if (curlen != 0) { if (curlen != prevlen) { - send_code(curlen, bl_tree); count--; + send_code(curlen, bl_tree); + count--; } send_code(InternalConstants.REP_3_6, bl_tree); send_bits(count - 3, 2); @@ -604,18 +613,22 @@ namespace SharpCompress.Compressor.Deflate send_code(InternalConstants.REPZ_11_138, bl_tree); send_bits(count - 11, 7); } - count = 0; prevlen = curlen; + count = 0; + prevlen = curlen; if (nextlen == 0) { - max_count = 138; min_count = 3; + max_count = 138; + min_count = 3; } else if (curlen == nextlen) { - max_count = 6; min_count = 3; + max_count = 6; + min_count = 3; } else { - max_count = 7; min_count = 4; + max_count = 7; + min_count = 4; } } } @@ -653,7 +666,7 @@ namespace SharpCompress.Compressor.Deflate internal void send_code(int c, short[] tree) { - int c2 = c * 2; + int c2 = c*2; send_bits((tree[c2] & 0xffff), (tree[c2 + 1] & 0xffff)); } @@ -662,24 +675,24 @@ namespace SharpCompress.Compressor.Deflate int len = length; unchecked { - if (bi_valid > (int)Buf_size - len) + if (bi_valid > (int) Buf_size - len) { //int val = value; // bi_buf |= (val << bi_valid); - bi_buf |= (short)((value << bi_valid) & 0xffff); + bi_buf |= (short) ((value << bi_valid) & 0xffff); //put_short(bi_buf); - pending[pendingCount++] = (byte)bi_buf; - pending[pendingCount++] = (byte)(bi_buf >> 8); + pending[pendingCount++] = (byte) bi_buf; + pending[pendingCount++] = (byte) (bi_buf >> 8); - bi_buf = (short)((uint)value >> (Buf_size - bi_valid)); + bi_buf = (short) ((uint) value >> (Buf_size - bi_valid)); bi_valid += len - Buf_size; } else { // bi_buf |= (value) << bi_valid; - bi_buf |= (short)((value << bi_valid) & 0xffff); + bi_buf |= (short) ((value << bi_valid) & 0xffff); bi_valid += len; } } @@ -719,26 +732,26 @@ namespace SharpCompress.Compressor.Deflate // the current block must be flushed. internal bool _tr_tally(int dist, int lc) { - pending[_distanceOffset + last_lit * 2] = unchecked((byte)((uint)dist >> 8)); - pending[_distanceOffset + last_lit * 2 + 1] = unchecked((byte)dist); - pending[_lengthOffset + last_lit] = unchecked((byte)lc); + pending[_distanceOffset + last_lit*2] = unchecked((byte) ((uint) dist >> 8)); + pending[_distanceOffset + last_lit*2 + 1] = unchecked((byte) dist); + pending[_lengthOffset + last_lit] = unchecked((byte) lc); last_lit++; if (dist == 0) { // lc is the unmatched char - dyn_ltree[lc * 2]++; + dyn_ltree[lc*2]++; } else { matches++; // Here, lc is the match length - MIN_MATCH dist--; // dist = match distance - 1 - dyn_ltree[(Tree.LengthCode[lc] + InternalConstants.LITERALS + 1) * 2]++; - dyn_dtree[Tree.DistanceCode(dist) * 2]++; + dyn_ltree[(Tree.LengthCode[lc] + InternalConstants.LITERALS + 1)*2]++; + dyn_dtree[Tree.DistanceCode(dist)*2]++; } - if ((last_lit & 0x1fff) == 0 && (int)compressionLevel > 2) + if ((last_lit & 0x1fff) == 0 && (int) compressionLevel > 2) { // Compute an upper bound for the compressed length int out_length = last_lit << 3; @@ -746,10 +759,11 @@ namespace SharpCompress.Compressor.Deflate int dcode; for (dcode = 0; dcode < InternalConstants.D_CODES; dcode++) { - out_length = (int)(out_length + (int)dyn_dtree[dcode * 2] * (5L + DeflateManager.ExtraDistanceBits[dcode])); + out_length = + (int) (out_length + (int) dyn_dtree[dcode*2]*(5L + DeflateManager.ExtraDistanceBits[dcode])); } out_length >>= 3; - if ((matches < (last_lit / 2)) && out_length < in_length / 2) + if ((matches < (last_lit/2)) && out_length < in_length/2) return true; } @@ -761,23 +775,22 @@ namespace SharpCompress.Compressor.Deflate } - // Send the block data compressed using the given Huffman trees internal void send_compressed_block(short[] ltree, short[] dtree) { int distance; // distance of matched string - int lc; // match length or unmatched char (if dist == 0) - int lx = 0; // running index in l_buf - int code; // the code to send - int extra; // number of extra bits to send + int lc; // match length or unmatched char (if dist == 0) + int lx = 0; // running index in l_buf + int code; // the code to send + int extra; // number of extra bits to send if (last_lit != 0) { do { - int ix = _distanceOffset + lx * 2; + int ix = _distanceOffset + lx*2; distance = ((pending[ix] << 8) & 0xff00) | - (pending[ix + 1] & 0xff); + (pending[ix + 1] & 0xff); lc = (pending[_lengthOffset + lx]) & 0xff; lx++; @@ -816,16 +829,14 @@ namespace SharpCompress.Compressor.Deflate } // Check that the overlay between pending and d_buf+l_buf is ok: - } - while (lx < last_lit); + } while (lx < last_lit); } send_code(END_BLOCK, ltree); - last_eob_len = ltree[END_BLOCK * 2 + 1]; + last_eob_len = ltree[END_BLOCK*2 + 1]; } - // Set the data type to ASCII or BINARY, using a crude approximation: // binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. // IN assertion: the fields freq of dyn_ltree are set and the total of all @@ -837,35 +848,37 @@ namespace SharpCompress.Compressor.Deflate int bin_freq = 0; while (n < 7) { - bin_freq += dyn_ltree[n * 2]; n++; + bin_freq += dyn_ltree[n*2]; + n++; } while (n < 128) { - ascii_freq += dyn_ltree[n * 2]; n++; + ascii_freq += dyn_ltree[n*2]; + n++; } while (n < InternalConstants.LITERALS) { - bin_freq += dyn_ltree[n * 2]; n++; + bin_freq += dyn_ltree[n*2]; + n++; } - data_type = (sbyte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII); + data_type = (sbyte) (bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII); } - // Flush the bit buffer, keeping at most 7 bits in it. internal void bi_flush() { if (bi_valid == 16) { - pending[pendingCount++] = (byte)bi_buf; - pending[pendingCount++] = (byte)(bi_buf >> 8); + pending[pendingCount++] = (byte) bi_buf; + pending[pendingCount++] = (byte) (bi_buf >> 8); bi_buf = 0; bi_valid = 0; } else if (bi_valid >= 8) { //put_byte((byte)bi_buf); - pending[pendingCount++] = (byte)bi_buf; + pending[pendingCount++] = (byte) bi_buf; bi_buf >>= 8; bi_valid -= 8; } @@ -876,13 +889,13 @@ namespace SharpCompress.Compressor.Deflate { if (bi_valid > 8) { - pending[pendingCount++] = (byte)bi_buf; - pending[pendingCount++] = (byte)(bi_buf >> 8); + pending[pendingCount++] = (byte) bi_buf; + pending[pendingCount++] = (byte) (bi_buf >> 8); } else if (bi_valid > 0) { //put_byte((byte)bi_buf); - pending[pendingCount++] = (byte)bi_buf; + pending[pendingCount++] = (byte) bi_buf; } bi_buf = 0; bi_valid = 0; @@ -899,11 +912,11 @@ namespace SharpCompress.Compressor.Deflate unchecked { //put_short((short)len); - pending[pendingCount++] = (byte)len; - pending[pendingCount++] = (byte)(len >> 8); + pending[pendingCount++] = (byte) len; + pending[pendingCount++] = (byte) (len >> 8); //put_short((short)~len); - pending[pendingCount++] = (byte)~len; - pending[pendingCount++] = (byte)(~len >> 8); + pending[pendingCount++] = (byte) ~len; + pending[pendingCount++] = (byte) (~len >> 8); } put_bytes(window, buf, len); @@ -957,8 +970,8 @@ namespace SharpCompress.Compressor.Deflate if (strstart == 0 || strstart >= max_start) { // strstart == 0 is possible when wraparound on 16-bit machine - lookahead = (int)(strstart - max_start); - strstart = (int)max_start; + lookahead = (int) (strstart - max_start); + strstart = (int) max_start; flush_block_only(false); if (_codec.AvailableBytesOut == 0) @@ -1111,20 +1124,18 @@ namespace SharpCompress.Compressor.Deflate do { m = (head[--p] & 0xffff); - head[p] = (short)((m >= w_size) ? (m - w_size) : 0); - } - while (--n != 0); + head[p] = (short) ((m >= w_size) ? (m - w_size) : 0); + } while (--n != 0); n = w_size; p = n; do { m = (prev[--p] & 0xffff); - prev[p] = (short)((m >= w_size) ? (m - w_size) : 0); + prev[p] = (short) ((m >= w_size) ? (m - w_size) : 0); // If n is not on any hash chain, prev[n] is garbage but // its value will never be used. - } - while (--n != 0); + } while (--n != 0); more += w_size; } @@ -1153,8 +1164,7 @@ namespace SharpCompress.Compressor.Deflate } // If the whole input has less than MIN_MATCH bytes, ins_h is garbage, // but this is not important since only literal bytes will be emitted. - } - while (lookahead < MIN_LOOKAHEAD && _codec.AvailableBytesIn != 0); + } while (lookahead < MIN_LOOKAHEAD && _codec.AvailableBytesIn != 0); } // Compress as much as possible from the input stream, return the current @@ -1194,7 +1204,7 @@ namespace SharpCompress.Compressor.Deflate // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; - head[ins_h] = unchecked((short)strstart); + head[ins_h] = unchecked((short) strstart); } // Find the longest match, discarding those <= prev_length. @@ -1232,12 +1242,11 @@ namespace SharpCompress.Compressor.Deflate // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; - head[ins_h] = unchecked((short)strstart); + head[ins_h] = unchecked((short) strstart); // strstart never exceeds WSIZE-MAX_MATCH, so there are // always MIN_MATCH bytes ahead. - } - while (--match_length != 0); + } while (--match_length != 0); strstart++; } else @@ -1314,7 +1323,7 @@ namespace SharpCompress.Compressor.Deflate // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; - head[ins_h] = unchecked((short)strstart); + head[ins_h] = unchecked((short) strstart); } // Find the longest match, discarding those <= prev_length. @@ -1338,7 +1347,6 @@ namespace SharpCompress.Compressor.Deflate if (match_length <= 5 && (compressionStrategy == CompressionStrategy.Filtered || (match_length == MIN_MATCH && strstart - match_start > 4096))) { - // If prev_match is also MIN_MATCH, match_start is garbage // but we will ignore the current match anyway. match_length = MIN_MATCH - 1; @@ -1366,14 +1374,14 @@ namespace SharpCompress.Compressor.Deflate { if (++strstart <= max_insert) { - ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; + ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & + hash_mask; //prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; - head[ins_h] = unchecked((short)strstart); + head[ins_h] = unchecked((short) strstart); } - } - while (--prev_length != 0); + } while (--prev_length != 0); match_available = 0; match_length = MIN_MATCH - 1; strstart++; @@ -1387,7 +1395,6 @@ namespace SharpCompress.Compressor.Deflate } else if (match_available != 0) { - // If there was no match at the previous position, output a // single literal. If there was a match but the current match // is longer, truncate the previous match to a single literal. @@ -1436,10 +1443,10 @@ namespace SharpCompress.Compressor.Deflate internal int longest_match(int cur_match) { int chain_length = config.MaxChainLength; // max hash chain length - int scan = strstart; // current string - int match; // matched string - int len; // length of current match - int best_len = prev_length; // best match length so far + int scan = strstart; // current string + int match; // matched string + int len; // length of current match + int best_len = prev_length; // best match length so far int limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0; int niceLength = config.NiceLength; @@ -1484,23 +1491,23 @@ namespace SharpCompress.Compressor.Deflate // It is not necessary to compare scan[2] and match[2] since they // are always equal when the other bytes match, given that // the hash keys are equal and that HASH_BITS >= 8. - scan += 2; match++; + scan += 2; + match++; // We check for insufficient lookahead only every 8th comparison; // the 256th check will be made at strstart+258. do { - } - while (window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && scan < strend); + } while (window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && scan < strend); - len = MAX_MATCH - (int)(strend - scan); + len = MAX_MATCH - (int) (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) @@ -1512,8 +1519,7 @@ namespace SharpCompress.Compressor.Deflate scan_end1 = window[scan + best_len - 1]; scan_end = window[scan + best_len]; } - } - while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length != 0); + } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length != 0); if (best_len <= lookahead) return best_len; @@ -1523,6 +1529,7 @@ namespace SharpCompress.Compressor.Deflate private bool Rfc1950BytesEmitted = false; private bool _WantRfc1950HeaderBytes = true; + internal bool WantRfc1950HeaderBytes { get { return _WantRfc1950HeaderBytes; } @@ -1540,12 +1547,14 @@ namespace SharpCompress.Compressor.Deflate return Initialize(codec, level, bits, MEM_LEVEL_DEFAULT, CompressionStrategy.Default); } - internal int Initialize(ZlibCodec codec, CompressionLevel level, int bits, CompressionStrategy compressionStrategy) + internal int Initialize(ZlibCodec codec, CompressionLevel level, int bits, + CompressionStrategy compressionStrategy) { return Initialize(codec, level, bits, MEM_LEVEL_DEFAULT, compressionStrategy); } - internal int Initialize(ZlibCodec codec, CompressionLevel level, int windowBits, int memLevel, CompressionStrategy strategy) + internal int Initialize(ZlibCodec codec, CompressionLevel level, int windowBits, int memLevel, + CompressionStrategy strategy) { _codec = codec; _codec.Message = null; @@ -1566,9 +1575,9 @@ namespace SharpCompress.Compressor.Deflate hash_bits = memLevel + 7; hash_size = 1 << hash_bits; hash_mask = hash_size - 1; - hash_shift = ((hash_bits + MIN_MATCH - 1) / MIN_MATCH); + hash_shift = ((hash_bits + MIN_MATCH - 1)/MIN_MATCH); - window = new byte[w_size * 2]; + window = new byte[w_size*2]; prev = new short[w_size]; head = new short[hash_size]; @@ -1579,9 +1588,9 @@ namespace SharpCompress.Compressor.Deflate // the output distance codes, and the output length codes (aka tree). // orig comment: This works just fine since the average // output size for (length,distance) codes is <= 24 bits. - pending = new byte[lit_bufsize * 4]; + pending = new byte[lit_bufsize*4]; _distanceOffset = lit_bufsize; - _lengthOffset = (1 + 2) * lit_bufsize; + _lengthOffset = (1 + 2)*lit_bufsize; // So, for memLevel 8, the length of the pending buffer is 65536. 64k. // The first 16k are pending bytes. @@ -1610,7 +1619,7 @@ namespace SharpCompress.Compressor.Deflate status = (WantRfc1950HeaderBytes) ? INIT_STATE : BUSY_STATE; _codec._Adler32 = Adler.Adler32(0, null, 0, 0); - last_flush = (int)FlushType.None; + last_flush = (int) FlushType.None; _InitializeTreeData(); _InitializeLazyMatch(); @@ -1710,13 +1719,12 @@ namespace SharpCompress.Compressor.Deflate { ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; prev[n & w_mask] = head[ins_h]; - head[ins_h] = (short)n; + head[ins_h] = (short) n; } return ZlibConstants.Z_OK; } - internal int Deflate(FlushType flush) { int old_flush; @@ -1737,27 +1745,27 @@ namespace SharpCompress.Compressor.Deflate } old_flush = last_flush; - last_flush = (int)flush; + last_flush = (int) flush; // Write the zlib (rfc1950) header bytes if (status == INIT_STATE) { int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8; - int level_flags = (((int)compressionLevel - 1) & 0xff) >> 1; + int level_flags = (((int) compressionLevel - 1) & 0xff) >> 1; if (level_flags > 3) level_flags = 3; header |= (level_flags << 6); if (strstart != 0) header |= PRESET_DICT; - header += 31 - (header % 31); + header += 31 - (header%31); status = BUSY_STATE; //putShortMSB(header); unchecked { - pending[pendingCount++] = (byte)(header >> 8); - pending[pendingCount++] = (byte)header; + pending[pendingCount++] = (byte) (header >> 8); + pending[pendingCount++] = (byte) header; } // Save the adler32 of the preset dictionary: if (strstart != 0) @@ -1765,10 +1773,10 @@ namespace SharpCompress.Compressor.Deflate ////putShortMSB((int)(SharedUtils.URShift(_codec._Adler32, 16))); //putShortMSB((int)((UInt64)_codec._Adler32 >> 16)); //putShortMSB((int)(_codec._Adler32 & 0xffff)); - pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF000000) >> 24); - pending[pendingCount++] = (byte)((_codec._Adler32 & 0x00FF0000) >> 16); - pending[pendingCount++] = (byte)((_codec._Adler32 & 0x0000FF00) >> 8); - pending[pendingCount++] = (byte)(_codec._Adler32 & 0x000000FF); + pending[pendingCount++] = (byte) ((_codec._Adler32 & 0xFF000000) >> 24); + pending[pendingCount++] = (byte) ((_codec._Adler32 & 0x00FF0000) >> 16); + pending[pendingCount++] = (byte) ((_codec._Adler32 & 0x0000FF00) >> 8); + pending[pendingCount++] = (byte) (_codec._Adler32 & 0x000000FF); } _codec._Adler32 = Adler.Adler32(0, null, 0, 0); } @@ -1794,7 +1802,7 @@ namespace SharpCompress.Compressor.Deflate // returning Z_STREAM_END instead of Z_BUFF_ERROR. } else if (_codec.AvailableBytesIn == 0 && - (int)flush <= old_flush && + (int) flush <= old_flush && flush != FlushType.Finish) { // workitem 8557 @@ -1820,7 +1828,6 @@ namespace SharpCompress.Compressor.Deflate // Start a new block or continue the current one. if (_codec.AvailableBytesIn != 0 || lookahead != 0 || (flush != FlushType.None && status != FINISH_STATE)) { - BlockState bstate = DeflateFunction(flush); if (bstate == BlockState.FinishStarted || bstate == BlockState.FinishDone) @@ -1877,10 +1884,10 @@ namespace SharpCompress.Compressor.Deflate return ZlibConstants.Z_STREAM_END; // Write the zlib trailer (adler32) - pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF000000) >> 24); - pending[pendingCount++] = (byte)((_codec._Adler32 & 0x00FF0000) >> 16); - pending[pendingCount++] = (byte)((_codec._Adler32 & 0x0000FF00) >> 8); - pending[pendingCount++] = (byte)(_codec._Adler32 & 0x000000FF); + pending[pendingCount++] = (byte) ((_codec._Adler32 & 0xFF000000) >> 24); + pending[pendingCount++] = (byte) ((_codec._Adler32 & 0x00FF0000) >> 16); + pending[pendingCount++] = (byte) ((_codec._Adler32 & 0x0000FF00) >> 8); + pending[pendingCount++] = (byte) (_codec._Adler32 & 0x000000FF); //putShortMSB((int)(SharedUtils.URShift(_codec._Adler32, 16))); //putShortMSB((int)(_codec._Adler32 & 0xffff)); @@ -1893,6 +1900,5 @@ namespace SharpCompress.Compressor.Deflate return pendingCount != 0 ? ZlibConstants.Z_OK : ZlibConstants.Z_STREAM_END; } - } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Deflate/DeflateStream.cs b/SharpCompress/Compressor/Deflate/DeflateStream.cs index 63621343..b8da300c 100644 --- a/SharpCompress/Compressor/Deflate/DeflateStream.cs +++ b/SharpCompress/Compressor/Deflate/DeflateStream.cs @@ -37,8 +37,8 @@ namespace SharpCompress.Compressor.Deflate public DeflateStream(Stream stream, CompressionMode mode, - CompressionLevel level = CompressionLevel.Default, - bool leaveOpen = false) + CompressionLevel level = CompressionLevel.Default, + bool leaveOpen = false) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.DEFLATE, leaveOpen); } diff --git a/SharpCompress/Compressor/Deflate/FlushType.cs b/SharpCompress/Compressor/Deflate/FlushType.cs index 1e2b6f22..79b8403b 100644 --- a/SharpCompress/Compressor/Deflate/FlushType.cs +++ b/SharpCompress/Compressor/Deflate/FlushType.cs @@ -1,5 +1,4 @@ - -namespace SharpCompress.Compressor.Deflate +namespace SharpCompress.Compressor.Deflate { /// /// Describes how to flush the current deflate operation. @@ -42,4 +41,4 @@ namespace SharpCompress.Compressor.Deflate /// Signals the end of the compression/decompression stream. Finish, } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Deflate/GZipStream.cs b/SharpCompress/Compressor/Deflate/GZipStream.cs index 3fe14024..3709aa57 100644 --- a/SharpCompress/Compressor/Deflate/GZipStream.cs +++ b/SharpCompress/Compressor/Deflate/GZipStream.cs @@ -423,7 +423,7 @@ namespace SharpCompress.Compressor.Deflate if (!LastModified.HasValue) LastModified = DateTime.Now; TimeSpan delta = LastModified.Value - UnixEpoch; - var timet = (Int32)delta.TotalSeconds; + var timet = (Int32) delta.TotalSeconds; Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4); i += 4; diff --git a/SharpCompress/Compressor/Deflate/InfTree.cs b/SharpCompress/Compressor/Deflate/InfTree.cs index b35eb0d4..055a1b79 100644 --- a/SharpCompress/Compressor/Deflate/InfTree.cs +++ b/SharpCompress/Compressor/Deflate/InfTree.cs @@ -179,10 +179,14 @@ namespace SharpCompress.Compressor.Deflate internal static readonly int[] fixed_td = new[] { 80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, - 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, - 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80 - , 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537 - , 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5 + 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33 + , + 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, + 80 + , 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, + 1537 + , 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92 + , 5 , 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 }; @@ -190,7 +194,8 @@ namespace SharpCompress.Compressor.Deflate //UPGRADE_NOTE: Final was removed from the declaration of 'cplens'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] cplens = new[] { - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51 + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, + 51 , 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; @@ -198,22 +203,26 @@ namespace SharpCompress.Compressor.Deflate //UPGRADE_NOTE: Final was removed from the declaration of 'cplext'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] cplext = new[] { - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4 + 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, 0, 112, 112 }; //UPGRADE_NOTE: Final was removed from the declaration of 'cpdist'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] cpdist = new[] { - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385 - , 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, + 385 + , 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, + 16385, 24577 }; //UPGRADE_NOTE: Final was removed from the declaration of 'cpdext'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] cpdext = new[] { - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, + 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 }; @@ -386,11 +395,11 @@ namespace SharpCompress.Compressor.Deflate if (h != 0) { x[h] = i; // save pattern for backing up - r[0] = (sbyte)j; // bits in this table - r[1] = (sbyte)l; // bits to dump before this table + r[0] = (sbyte) j; // bits in this table + r[1] = (sbyte) l; // bits to dump before this table j = SharedUtils.URShift(i, (w - l)); r[2] = (q - u[h - 1] - j); // offset to this table - Array.Copy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect to last table + Array.Copy(r, 0, hp, (u[h - 1] + j)*3, 3); // connect to last table } else { @@ -399,19 +408,19 @@ namespace SharpCompress.Compressor.Deflate } // set up table entry in r - r[1] = (sbyte)(k - w); + r[1] = (sbyte) (k - w); if (p >= n) { r[0] = 128 + 64; // out of values--invalid code } else if (v[p] < s) { - r[0] = (sbyte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block + r[0] = (sbyte) (v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block r[2] = v[p++]; // simple code is just the value } else { - r[0] = (sbyte)(e[v[p] - s] + 16 + 64); // non-simple--look up in lists + r[0] = (sbyte) (e[v[p] - s] + 16 + 64); // non-simple--look up in lists r[2] = d[v[p++] - s]; } @@ -419,7 +428,7 @@ namespace SharpCompress.Compressor.Deflate f = 1 << (k - w); for (j = SharedUtils.URShift(i, w); j < z; j += f) { - Array.Copy(r, 0, hp, (q + j) * 3, 3); + Array.Copy(r, 0, hp, (q + j)*3, 3); } // backwards increment the k-bit code i diff --git a/SharpCompress/Compressor/Deflate/Inflate.cs b/SharpCompress/Compressor/Deflate/Inflate.cs index 55d33a00..c4f0889b 100644 --- a/SharpCompress/Compressor/Deflate/Inflate.cs +++ b/SharpCompress/Compressor/Deflate/Inflate.cs @@ -71,7 +71,7 @@ namespace SharpCompress.Compressor.Deflate private const int MANY = 1440; // Table for deflate from PKZIP's appnote.txt. - internal static readonly int[] border = new[] { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + internal static readonly int[] border = new[] {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 @@ -99,7 +99,7 @@ namespace SharpCompress.Compressor.Deflate internal InflateBlocks(ZlibCodec codec, Object checkfn, int w) { _codec = codec; - hufts = new int[MANY * 3]; + hufts = new int[MANY*3]; window = new byte[w]; end = w; this.checkfn = checkfn; @@ -173,7 +173,7 @@ namespace SharpCompress.Compressor.Deflate t = (b & 7); last = t & 1; - switch ((uint)t >> 1) + switch ((uint) t >> 1) { case 0: // stored b >>= 3; @@ -478,8 +478,8 @@ namespace SharpCompress.Compressor.Deflate k += 8; } - t = hufts[(tb[0] + (b & InternalInflateConstants.InflateMask[t])) * 3 + 1]; - c = hufts[(tb[0] + (b & InternalInflateConstants.InflateMask[t])) * 3 + 2]; + t = hufts[(tb[0] + (b & InternalInflateConstants.InflateMask[t]))*3 + 1]; + c = hufts[(tb[0] + (b & InternalInflateConstants.InflateMask[t]))*3 + 2]; if (c < 16) { @@ -552,8 +552,8 @@ namespace SharpCompress.Compressor.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 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]; @@ -817,8 +817,8 @@ namespace SharpCompress.Compressor.Deflate internal void Init(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index) { mode = START; - lbits = (byte)bl; - dbits = (byte)bd; + lbits = (byte) bl; + dbits = (byte) bd; ltree = tl; ltree_index = tl_index; dtree = td; @@ -854,7 +854,7 @@ namespace SharpCompress.Compressor.Deflate { switch (mode) { - // waiting for "i:"=input, "o:"=output, "x:"=nothing + // waiting for "i:"=input, "o:"=output, "x:"=nothing case START: // x: set up for LEN if (m >= 258 && n >= 10) { @@ -908,7 +908,7 @@ namespace SharpCompress.Compressor.Deflate k += 8; } - tindex = (tree_index + (b & InternalInflateConstants.InflateMask[j])) * 3; + tindex = (tree_index + (b & InternalInflateConstants.InflateMask[j]))*3; b >>= (tree[tindex + 1]); k -= (tree[tindex + 1]); @@ -934,7 +934,7 @@ namespace SharpCompress.Compressor.Deflate { // next table need = e; - tree_index = tindex / 3 + tree[tindex + 2]; + tree_index = tindex/3 + tree[tindex + 2]; break; } if ((e & 32) != 0) @@ -1011,7 +1011,7 @@ namespace SharpCompress.Compressor.Deflate k += 8; } - tindex = (tree_index + (b & InternalInflateConstants.InflateMask[j])) * 3; + tindex = (tree_index + (b & InternalInflateConstants.InflateMask[j]))*3; b >>= tree[tindex + 1]; k -= tree[tindex + 1]; @@ -1029,7 +1029,7 @@ namespace SharpCompress.Compressor.Deflate { // next table need = e; - tree_index = tindex / 3 + tree[tindex + 2]; + tree_index = tindex/3 + tree[tindex + 2]; break; } mode = BADCODE; // invalid code @@ -1161,7 +1161,7 @@ namespace SharpCompress.Compressor.Deflate } r = ZlibConstants.Z_OK; - blocks.window[q++] = (byte)lit; + blocks.window[q++] = (byte) lit; m--; mode = START; @@ -1285,13 +1285,13 @@ namespace SharpCompress.Compressor.Deflate t = b & ml; tp = tl; tp_index = tl_index; - tp_index_t_3 = (tp_index + t) * 3; + tp_index_t_3 = (tp_index + t)*3; if ((e = tp[tp_index_t_3]) == 0) { b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); - s.window[q++] = (byte)tp[tp_index_t_3 + 2]; + s.window[q++] = (byte) tp[tp_index_t_3 + 2]; m--; continue; } @@ -1320,7 +1320,7 @@ namespace SharpCompress.Compressor.Deflate t = b & md; tp = td; tp_index = td_index; - tp_index_t_3 = (tp_index + t) * 3; + tp_index_t_3 = (tp_index + t)*3; e = tp[tp_index_t_3]; do @@ -1418,7 +1418,7 @@ namespace SharpCompress.Compressor.Deflate { t += tp[tp_index_t_3 + 2]; t += (b & InternalInflateConstants.InflateMask[e]); - tp_index_t_3 = (tp_index + t) * 3; + tp_index_t_3 = (tp_index + t)*3; e = tp[tp_index_t_3]; } else @@ -1448,12 +1448,12 @@ namespace SharpCompress.Compressor.Deflate { t += tp[tp_index_t_3 + 2]; t += (b & InternalInflateConstants.InflateMask[e]); - tp_index_t_3 = (tp_index + t) * 3; + tp_index_t_3 = (tp_index + t)*3; if ((e = tp[tp_index_t_3]) == 0) { b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); - s.window[q++] = (byte)tp[tp_index_t_3 + 2]; + s.window[q++] = (byte) tp[tp_index_t_3 + 2]; m--; break; } @@ -1522,7 +1522,7 @@ namespace SharpCompress.Compressor.Deflate private const int PRESET_DICT = 0x20; private const int Z_DEFLATED = 8; - private static readonly byte[] mark = new byte[] { 0, 0, 0xff, 0xff }; + private static readonly byte[] mark = new byte[] {0, 0, 0xff, 0xff}; internal ZlibCodec _codec; // pointer back to this zlib stream private bool _handleRfc1950HeaderBytes = true; @@ -1659,7 +1659,7 @@ namespace SharpCompress.Compressor.Deflate _codec.TotalBytesIn++; b = (_codec.InputBuffer[_codec.NextIn++]) & 0xff; - if ((((method << 8) + b) % 31) != 0) + if ((((method << 8) + b)%31) != 0) { mode = InflateManagerMode.BAD; _codec.Message = "incorrect header check"; @@ -1677,7 +1677,7 @@ namespace SharpCompress.Compressor.Deflate r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - expectedCheck = (uint)((_codec.InputBuffer[_codec.NextIn++] << 24) & 0xff000000); + expectedCheck = (uint) ((_codec.InputBuffer[_codec.NextIn++] << 24) & 0xff000000); mode = InflateManagerMode.DICT3; break; @@ -1686,7 +1686,7 @@ namespace SharpCompress.Compressor.Deflate r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - expectedCheck += (uint)((_codec.InputBuffer[_codec.NextIn++] << 16) & 0x00ff0000); + expectedCheck += (uint) ((_codec.InputBuffer[_codec.NextIn++] << 16) & 0x00ff0000); mode = InflateManagerMode.DICT2; break; @@ -1696,7 +1696,7 @@ namespace SharpCompress.Compressor.Deflate r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - expectedCheck += (uint)((_codec.InputBuffer[_codec.NextIn++] << 8) & 0x0000ff00); + expectedCheck += (uint) ((_codec.InputBuffer[_codec.NextIn++] << 8) & 0x0000ff00); mode = InflateManagerMode.DICT1; break; @@ -1706,7 +1706,7 @@ namespace SharpCompress.Compressor.Deflate r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - expectedCheck += (uint)(_codec.InputBuffer[_codec.NextIn++] & 0x000000ff); + expectedCheck += (uint) (_codec.InputBuffer[_codec.NextIn++] & 0x000000ff); _codec._Adler32 = expectedCheck; mode = InflateManagerMode.DICT0; return ZlibConstants.Z_NEED_DICT; @@ -1748,7 +1748,7 @@ namespace SharpCompress.Compressor.Deflate r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - expectedCheck = (uint)((_codec.InputBuffer[_codec.NextIn++] << 24) & 0xff000000); + expectedCheck = (uint) ((_codec.InputBuffer[_codec.NextIn++] << 24) & 0xff000000); mode = InflateManagerMode.CHECK3; break; @@ -1757,7 +1757,7 @@ namespace SharpCompress.Compressor.Deflate r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - expectedCheck += (uint)((_codec.InputBuffer[_codec.NextIn++] << 16) & 0x00ff0000); + expectedCheck += (uint) ((_codec.InputBuffer[_codec.NextIn++] << 16) & 0x00ff0000); mode = InflateManagerMode.CHECK2; break; @@ -1766,7 +1766,7 @@ namespace SharpCompress.Compressor.Deflate r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - expectedCheck += (uint)((_codec.InputBuffer[_codec.NextIn++] << 8) & 0x0000ff00); + expectedCheck += (uint) ((_codec.InputBuffer[_codec.NextIn++] << 8) & 0x0000ff00); mode = InflateManagerMode.CHECK1; break; @@ -1775,7 +1775,7 @@ namespace SharpCompress.Compressor.Deflate r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - expectedCheck += (uint)(_codec.InputBuffer[_codec.NextIn++] & 0x000000ff); + expectedCheck += (uint) (_codec.InputBuffer[_codec.NextIn++] & 0x000000ff); if (computedCheck != expectedCheck) { mode = InflateManagerMode.BAD; diff --git a/SharpCompress/Compressor/Deflate/ParallelDeflateOutputStream.cs b/SharpCompress/Compressor/Deflate/ParallelDeflateOutputStream.cs index 304a9b5b..66a4f626 100644 --- a/SharpCompress/Compressor/Deflate/ParallelDeflateOutputStream.cs +++ b/SharpCompress/Compressor/Deflate/ParallelDeflateOutputStream.cs @@ -40,10 +40,10 @@ namespace SharpCompress.Compressor.Deflate { buffer = new byte[size]; // alloc 5 bytes overhead for every block (margin of safety= 2) - int n = size + ((size / 32768) + 1) * 5 * 2; + int n = size + ((size/32768) + 1)*5*2; compressed = new byte[n]; - status = (int)Status.None; + status = (int) Status.None; compressor = new ZlibCodec(); compressor.InitializeDeflate(compressLevel, false); compressor.OutputBuffer = compressed; @@ -107,7 +107,7 @@ namespace SharpCompress.Compressor.Deflate /// internal class ParallelDeflateOutputStream : Stream { - private static readonly int IO_BUFFER_SIZE_DEFAULT = 64 * 1024; // 128k + private static readonly int IO_BUFFER_SIZE_DEFAULT = 64*1024; // 128k private readonly CompressionLevel _compressLevel; private readonly object _eLock = new Object(); // protects _pendingException @@ -471,7 +471,7 @@ namespace SharpCompress.Compressor.Deflate private void _InitializePoolOfWorkItems() { _pool = new List(); - for (int i = 0; i < BuffersPerCore * Environment.ProcessorCount; i++) + for (int i = 0; i < BuffersPerCore*Environment.ProcessorCount; i++) _pool.Add(new WorkItem(_bufferSize, _compressLevel, Strategy)); _pc = _pool.Count; @@ -546,7 +546,7 @@ namespace SharpCompress.Compressor.Deflate do { - int ix = _nextToFill % _pc; + int ix = _nextToFill%_pc; WorkItem workitem = _pool[ix]; lock (workitem) { @@ -559,11 +559,11 @@ namespace SharpCompress.Compressor.Deflate ); // If the status is what we want, then use the workitem. - if (workitem.status == (int)WorkItem.Status.None || - workitem.status == (int)WorkItem.Status.Done || - workitem.status == (int)WorkItem.Status.Filling) + if (workitem.status == (int) WorkItem.Status.None || + workitem.status == (int) WorkItem.Status.Done || + workitem.status == (int) WorkItem.Status.Filling) { - workitem.status = (int)WorkItem.Status.Filling; + workitem.status = (int) WorkItem.Status.Filling; int limit = ((workitem.buffer.Length - workitem.inputBytesAvailable) > count) ? count : (workitem.buffer.Length - workitem.inputBytesAvailable); @@ -577,7 +577,7 @@ namespace SharpCompress.Compressor.Deflate workitem.inputBytesAvailable += limit; if (workitem.inputBytesAvailable == workitem.buffer.Length) { - workitem.status = (int)WorkItem.Status.Filled; + workitem.status = (int) WorkItem.Status.Filled; // No need for interlocked.increment: the Write() method // is documented as not multi-thread safe, so we can assume Write() // calls come in from only one thread. @@ -599,9 +599,9 @@ namespace SharpCompress.Compressor.Deflate { int wcycles = 0; - while (workitem.status != (int)WorkItem.Status.None && - workitem.status != (int)WorkItem.Status.Done && - workitem.status != (int)WorkItem.Status.Filling) + while (workitem.status != (int) WorkItem.Status.None && + workitem.status != (int) WorkItem.Status.Done && + workitem.status != (int) WorkItem.Status.Filling) { TraceOutput(TraceBits.Fill, "Fill waiting wi({0}) stat({1}) nf({2})", @@ -614,9 +614,9 @@ namespace SharpCompress.Compressor.Deflate Monitor.Pulse(workitem); Monitor.Wait(workitem); - if (workitem.status == (int)WorkItem.Status.None || - workitem.status == (int)WorkItem.Status.Done || - workitem.status == (int)WorkItem.Status.Filling) + if (workitem.status == (int) WorkItem.Status.None || + workitem.status == (int) WorkItem.Status.Done || + workitem.status == (int) WorkItem.Status.Filling) TraceOutput(TraceBits.Fill, "Fill A-OK wi({0}) stat({1}) iba({2}) cyc({3})", workitem.index, @@ -647,12 +647,12 @@ namespace SharpCompress.Compressor.Deflate throw new NotSupportedException(); // pass any partial buffer out to the compressor workers: - WorkItem workitem = _pool[_nextToFill % _pc]; + WorkItem workitem = _pool[_nextToFill%_pc]; lock (workitem) { - if (workitem.status == (int)WorkItem.Status.Filling) + if (workitem.status == (int) WorkItem.Status.Filling) { - workitem.status = (int)WorkItem.Status.Filled; + workitem.status = (int) WorkItem.Status.Filled; _nextToFill++; // When flush is called from Close(), we set _noMore. @@ -718,7 +718,7 @@ namespace SharpCompress.Compressor.Deflate //System.Console.WriteLine(st.ToString()); // need to get Writer off the workitem, in case he's waiting forever - WorkItem workitem = _pool[_nextToFill % _pc]; + WorkItem workitem = _pool[_nextToFill%_pc]; lock (workitem) { Monitor.PulseAll(workitem); @@ -751,7 +751,6 @@ namespace SharpCompress.Compressor.Deflate // workitem 10030 - implement a new Dispose method - /// /// Resets the stream for use with another stream. /// @@ -804,7 +803,7 @@ namespace SharpCompress.Compressor.Deflate // reset all status foreach (WorkItem workitem in _pool) - workitem.status = (int)WorkItem.Status.None; + workitem.status = (int) WorkItem.Status.None; _noMoreInputForThisSegment = false; _nextToFill = _nextToWrite = 0; @@ -851,7 +850,7 @@ namespace SharpCompress.Compressor.Deflate var c = new CRC32(); do { - workitem = _pool[_nextToWrite % _pc]; + workitem = _pool[_nextToWrite%_pc]; lock (workitem) { if (_noMoreInputForThisSegment) @@ -859,12 +858,12 @@ namespace SharpCompress.Compressor.Deflate "Write drain wi({0}) stat({1}) canuse({2}) cba({3})", workitem.index, workitem.status, - (workitem.status == (int)WorkItem.Status.Compressed), + (workitem.status == (int) WorkItem.Status.Compressed), workitem.compressedBytesAvailable); do { - if (workitem.status == (int)WorkItem.Status.Compressed) + if (workitem.status == (int) WorkItem.Status.Compressed) { TraceOutput(TraceBits.WriteBegin, "Write begin wi({0}) stat({1}) cba({2})", @@ -872,13 +871,13 @@ namespace SharpCompress.Compressor.Deflate workitem.status, workitem.compressedBytesAvailable); - workitem.status = (int)WorkItem.Status.Writing; + workitem.status = (int) WorkItem.Status.Writing; _outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable); c.Combine(workitem.crc, workitem.inputBytesAvailable); _totalBytesProcessed += workitem.inputBytesAvailable; _nextToWrite++; workitem.inputBytesAvailable = 0; - workitem.status = (int)WorkItem.Status.Done; + workitem.status = (int) WorkItem.Status.Done; TraceOutput(TraceBits.WriteDone, "Write done wi({0}) stat({1}) cba({2})", @@ -895,7 +894,7 @@ namespace SharpCompress.Compressor.Deflate int wcycles = 0; // I've locked a workitem I cannot use. // Therefore, wake someone else up, and then release the lock. - while (workitem.status != (int)WorkItem.Status.Compressed) + while (workitem.status != (int) WorkItem.Status.Compressed) { TraceOutput(TraceBits.WriteWait, "Write waiting wi({0}) stat({1}) nw({2}) nf({3}) nomore({4})", @@ -914,7 +913,7 @@ namespace SharpCompress.Compressor.Deflate // release and wait Monitor.Wait(workitem); - if (workitem.status == (int)WorkItem.Status.Compressed) + if (workitem.status == (int) WorkItem.Status.Compressed) TraceOutput(TraceBits.WriteWait, "Write A-OK wi({0}) stat({1}) iba({2}) cba({3}) cyc({4})", workitem.index, @@ -995,7 +994,7 @@ namespace SharpCompress.Compressor.Deflate private void _DeflateOne(Object wi) { - var workitem = (WorkItem)wi; + var workitem = (WorkItem) wi; try { // compress one buffer @@ -1003,7 +1002,7 @@ namespace SharpCompress.Compressor.Deflate lock (workitem) { - if (workitem.status != (int)WorkItem.Status.Filled) + if (workitem.status != (int) WorkItem.Status.Filled) throw new InvalidOperationException(); var crc = new CRC32(); @@ -1016,7 +1015,7 @@ namespace SharpCompress.Compressor.Deflate DeflateOneSegment(workitem); // update status - workitem.status = (int)WorkItem.Status.Compressed; + workitem.status = (int) WorkItem.Status.Compressed; workitem.crc = crc.Crc32Result; TraceOutput(TraceBits.Compress, @@ -1062,7 +1061,7 @@ namespace SharpCompress.Compressor.Deflate // step 2: flush (sync) compressor.Deflate(FlushType.Sync); - workitem.compressedBytesAvailable = (int)compressor.TotalBytesOut; + workitem.compressedBytesAvailable = (int) compressor.TotalBytesOut; return true; } @@ -1076,7 +1075,7 @@ namespace SharpCompress.Compressor.Deflate { int tid = Thread.CurrentThread.GetHashCode(); #if !SILVERLIGHT - Console.ForegroundColor = (ConsoleColor)(tid % 8 + 8); + Console.ForegroundColor = (ConsoleColor) (tid%8 + 8); #endif Console.Write("{0:000} PDOS ", tid); Console.WriteLine(format, varParams); @@ -1136,4 +1135,5 @@ namespace SharpCompress.Compressor.Deflate #endregion } } + #endif \ No newline at end of file diff --git a/SharpCompress/Compressor/Deflate/Tree.cs b/SharpCompress/Compressor/Deflate/Tree.cs index 8fec1e90..e49708ce 100644 --- a/SharpCompress/Compressor/Deflate/Tree.cs +++ b/SharpCompress/Compressor/Deflate/Tree.cs @@ -71,13 +71,14 @@ namespace SharpCompress.Compressor.Deflate private sealed class Tree { - internal const int Buf_size = 8 * 2; - private static readonly int HEAP_SIZE = (2 * InternalConstants.L_CODES + 1); + internal const int Buf_size = 8*2; + private static readonly int HEAP_SIZE = (2*InternalConstants.L_CODES + 1); internal static readonly sbyte[] bl_order = new sbyte[] { - 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, + 14, 1, 15 }; @@ -251,18 +252,18 @@ namespace SharpCompress.Compressor.Deflate // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). - tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap + tree[s.heap[s.heap_max]*2 + 1] = 0; // root of the heap for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; - bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + bits = tree[tree[n*2 + 1]*2 + 1] + 1; if (bits > max_length) { bits = max_length; overflow++; } - tree[n * 2 + 1] = (short)bits; + tree[n*2 + 1] = (short) bits; // We overwrite tree[n*2+1] which is no longer needed if (n > max_code) @@ -272,10 +273,10 @@ namespace SharpCompress.Compressor.Deflate xbits = 0; if (n >= base_Renamed) xbits = extra[n - base_Renamed]; - f = tree[n * 2]; - s.opt_len += f * (bits + xbits); + f = tree[n*2]; + s.opt_len += f*(bits + xbits); if (stree != null) - s.static_len += f * (stree[n * 2 + 1] + xbits); + s.static_len += f*(stree[n*2 + 1] + xbits); } if (overflow == 0) return; @@ -288,7 +289,7 @@ namespace SharpCompress.Compressor.Deflate while (s.bl_count[bits] == 0) bits--; s.bl_count[bits]--; // move one leaf down the tree - s.bl_count[bits + 1] = (short)(s.bl_count[bits + 1] + 2); // move one overflow item as its brother + s.bl_count[bits + 1] = (short) (s.bl_count[bits + 1] + 2); // move one overflow item as its brother s.bl_count[max_length]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] @@ -303,10 +304,10 @@ namespace SharpCompress.Compressor.Deflate m = s.heap[--h]; if (m > max_code) continue; - if (tree[m * 2 + 1] != bits) + if (tree[m*2 + 1] != bits) { - s.opt_len = (int)(s.opt_len + (bits - (long)tree[m * 2 + 1]) * tree[m * 2]); - tree[m * 2 + 1] = (short)bits; + s.opt_len = (int) (s.opt_len + (bits - (long) tree[m*2 + 1])*tree[m*2]); + tree[m*2 + 1] = (short) bits; } n--; } @@ -336,14 +337,14 @@ namespace SharpCompress.Compressor.Deflate for (n = 0; n < elems; n++) { - if (tree[n * 2] != 0) + if (tree[n*2] != 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { - tree[n * 2 + 1] = 0; + tree[n*2 + 1] = 0; } } @@ -354,11 +355,11 @@ namespace SharpCompress.Compressor.Deflate while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); - tree[node * 2] = 1; + tree[node*2] = 1; s.depth[node] = 0; s.opt_len--; if (stree != null) - s.static_len -= stree[node * 2 + 1]; + s.static_len -= stree[node*2 + 1]; // node is 0 or 1 so it does not have extra bits } this.max_code = max_code; @@ -366,7 +367,7 @@ namespace SharpCompress.Compressor.Deflate // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: - for (n = s.heap_len / 2; n >= 1; n--) + for (n = s.heap_len/2; n >= 1; n--) s.pqdownheap(tree, n); // Construct the Huffman tree by repeatedly combining the least two @@ -385,9 +386,9 @@ namespace SharpCompress.Compressor.Deflate s.heap[--s.heap_max] = m; // Create a new node father of n and m - tree[node * 2] = unchecked((short)(tree[n * 2] + tree[m * 2])); - s.depth[node] = (sbyte)(Math.Max((byte)s.depth[n], (byte)s.depth[m]) + 1); - tree[n * 2 + 1] = tree[m * 2 + 1] = (short)node; + tree[node*2] = unchecked((short) (tree[n*2] + tree[m*2])); + s.depth[node] = (sbyte) (Math.Max((byte) s.depth[n], (byte) s.depth[m]) + 1); + tree[n*2 + 1] = tree[m*2 + 1] = (short) node; // and insert the new node in the heap s.heap[1] = node++; @@ -423,7 +424,7 @@ namespace SharpCompress.Compressor.Deflate for (bits = 1; bits <= InternalConstants.MAX_BITS; bits++) unchecked { - next_code[bits] = code = (short)((code + bl_count[bits - 1]) << 1); + next_code[bits] = code = (short) ((code + bl_count[bits - 1]) << 1); } // Check that the bit counts in bl_count are consistent. The last code @@ -434,11 +435,11 @@ namespace SharpCompress.Compressor.Deflate for (n = 0; n <= max_code; n++) { - int len = tree[n * 2 + 1]; + int len = tree[n*2 + 1]; if (len == 0) continue; // Now reverse the bits - tree[n * 2] = unchecked((short)(bi_reverse(next_code[len]++, len))); + tree[n*2] = unchecked((short) (bi_reverse(next_code[len]++, len))); } } diff --git a/SharpCompress/Compressor/Deflate/Zlib.cs b/SharpCompress/Compressor/Deflate/Zlib.cs index eaa64955..954d1936 100644 --- a/SharpCompress/Compressor/Deflate/Zlib.cs +++ b/SharpCompress/Compressor/Deflate/Zlib.cs @@ -63,11 +63,8 @@ // ----------------------------------------------------------------------- - - namespace SharpCompress.Compressor.Deflate { - /// /// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress. /// @@ -79,6 +76,7 @@ namespace SharpCompress.Compressor.Deflate /// cannot be opened with the default zip reader. Use a different CompressionLevel. /// None = 0, + /// /// Same as None. /// @@ -118,6 +116,7 @@ namespace SharpCompress.Compressor.Deflate /// The default compression level, with a good balance of speed and compression efficiency. /// Default = 6, + /// /// A synonym for Default. /// @@ -209,16 +208,16 @@ namespace SharpCompress.Compressor.Deflate /// The resulting number from the shift operation public static int URShift(int number, int bits) { - return (int)((uint)number >> bits); + return (int) ((uint) number >> bits); } #if NOT - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation + /// + /// Performs an unsigned bitwise right shift with the specified number + /// + /// Number to operate on + /// Ammount of bits to shift + /// The resulting number from the shift operation public static long URShift(long number, int bits) { return (long) ((UInt64)number >> bits); @@ -252,7 +251,7 @@ namespace SharpCompress.Compressor.Deflate if (bytesRead == 0) return -1; for (int index = start; index < start + bytesRead; index++) - target[index] = (byte)charArray[index]; + target[index] = (byte) charArray[index]; return bytesRead; } @@ -290,58 +289,97 @@ namespace SharpCompress.Compressor.Deflate // repeat a zero length 11-138 times (7 bits of repeat count) internal static readonly int REPZ_11_138 = 18; - } internal sealed class StaticTree { - internal static readonly short[] lengthAndLiteralsTreeCodes = new short[] { - 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, - 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, - 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, - 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, - 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, - 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, - 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, - 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, - 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, - 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, - 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, - 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, - 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, - 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, - 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, - 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, - 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, - 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, - 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, - 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, - 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, - 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, - 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, - 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, - 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, - 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, - 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, - 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, - 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, - 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, - 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, - 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, - 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, - 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, - 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, - 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8 - }; + internal static readonly short[] lengthAndLiteralsTreeCodes = new short[] + { + 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, + 8, 108, 8, 236, 8, + 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, + 8, 124, 8, 252, 8, + 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8 + , 98, 8, 226, 8, + 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, + 8, 114, 8, 242, 8, + 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, + 8, 106, 8, 234, 8, + 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, + 8, 122, 8, 250, 8, + 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8 + , 102, 8, 230, 8, + 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, + 8, 118, 8, 246, 8, + 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, + 8, 110, 8, 238, 8, + 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, + 8, 126, 8, 254, 8, + 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8 + , 97, 8, 225, 8, + 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, + 8, 113, 8, 241, 8, + 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8 + , 105, 8, 233, 8, + 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, + 8, 121, 8, 249, 8, + 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8 + , 101, 8, 229, 8, + 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, + 8, 117, 8, 245, 8, + 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, + 8, 109, 8, 237, 8, + 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, + 8, 125, 8, 253, 8, + 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, + 9, 211, 9, 467, 9, + 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371 + , 9, 243, 9, 499, 9, + 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, + 9, 203, 9, 459, 9, + 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363 + , 9, 235, 9, 491, 9, + 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, + 9, 219, 9, 475, 9, + 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379 + , 9, 251, 9, 507, 9, + 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, + 9, 199, 9, 455, 9, + 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359 + , 9, 231, 9, 487, 9, + 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, + 9, 215, 9, 471, 9, + 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375 + , 9, 247, 9, 503, 9, + 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, + 9, 207, 9, 463, 9, + 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367 + , 9, 239, 9, 495, 9, + 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, + 9, 223, 9, 479, 9, + 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383 + , 9, 255, 9, 511, 9, + 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, + 48, 7, 112, 7, + 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, + 56, 7, 120, 7, + 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, + 52, 7, 116, 7, + 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8 + , 99, 8, 227, 8 + }; - internal static readonly short[] distTreeCodes = new short[] { - 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, - 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, - 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, - 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 }; + internal static readonly short[] distTreeCodes = new short[] + { + 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, + 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, + 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, + 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 + }; // extra bits for each bit length code - internal static readonly int[] extra_blbits = new int[] { 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 = new int[] + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; internal static readonly StaticTree Literals; @@ -349,10 +387,10 @@ namespace SharpCompress.Compressor.Deflate internal static readonly StaticTree BitLengths; internal short[] treeCodes; // static tree or null - internal int[] extraBits; // extra bits for each code or null - internal int extraBase; // base index for extra_bits - internal int elems; // max number of elements in the tree - internal int maxLength; // max bit length for the codes + internal int[] extraBits; // extra bits for each code or null + internal int extraBase; // base index for extra_bits + internal int elems; // max number of elements in the tree + internal int maxLength; // max bit length for the codes private StaticTree(short[] treeCodes, int[] extraBits, int extraBase, int elems, int maxLength) { @@ -362,16 +400,19 @@ namespace SharpCompress.Compressor.Deflate this.elems = elems; this.maxLength = maxLength; } + static StaticTree() { - Literals = new StaticTree(lengthAndLiteralsTreeCodes, DeflateManager.ExtraLengthBits, InternalConstants.LITERALS + 1, InternalConstants.L_CODES, InternalConstants.MAX_BITS); - Distances = new StaticTree(distTreeCodes, DeflateManager.ExtraDistanceBits, 0, InternalConstants.D_CODES, InternalConstants.MAX_BITS); + Literals = new StaticTree(lengthAndLiteralsTreeCodes, DeflateManager.ExtraLengthBits, + InternalConstants.LITERALS + 1, InternalConstants.L_CODES, + InternalConstants.MAX_BITS); + Distances = new StaticTree(distTreeCodes, DeflateManager.ExtraDistanceBits, 0, InternalConstants.D_CODES, + InternalConstants.MAX_BITS); BitLengths = new StaticTree(null, extra_blbits, 0, InternalConstants.BL_CODES, InternalConstants.MAX_BL_BITS); } } - /// /// Computes an Adler-32 checksum. /// @@ -388,13 +429,13 @@ namespace SharpCompress.Compressor.Deflate // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 private static readonly int NMAX = 5552; - static internal uint Adler32(uint adler, byte[] buf, int index, int len) + internal static uint Adler32(uint adler, byte[] buf, int index, int len) { if (buf == null) return 1; - int s1 = (int)(adler & 0xffff); - int s2 = (int)((adler >> 16) & 0xffff); + int s1 = (int) (adler & 0xffff); + int s2 = (int) ((adler >> 16) & 0xffff); while (len > 0) { @@ -403,22 +444,38 @@ namespace SharpCompress.Compressor.Deflate while (k >= 16) { //s1 += (buf[index++] & 0xff); s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; - s1 += buf[index++]; s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; + s1 += buf[index++]; + s2 += s1; k -= 16; } if (k != 0) @@ -427,15 +484,12 @@ namespace SharpCompress.Compressor.Deflate { s1 += buf[index++]; s2 += s1; - } - while (--k != 0); + } while (--k != 0); } s1 %= BASE; s2 %= BASE; } - return (uint)((s2 << 16) | s1); + return (uint) ((s2 << 16) | s1); } - } - } \ No newline at end of file diff --git a/SharpCompress/Compressor/Deflate/ZlibBaseStream.cs b/SharpCompress/Compressor/Deflate/ZlibBaseStream.cs index c17e440a..c82f2f9f 100644 --- a/SharpCompress/Compressor/Deflate/ZlibBaseStream.cs +++ b/SharpCompress/Compressor/Deflate/ZlibBaseStream.cs @@ -30,8 +30,12 @@ using SharpCompress.Common; namespace SharpCompress.Compressor.Deflate { - - internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 } + internal enum ZlibStreamFlavor + { + ZLIB = 1950, + DEFLATE = 1951, + GZIP = 1952 + } internal class ZlibBaseStream : System.IO.Stream { @@ -51,13 +55,20 @@ namespace SharpCompress.Compressor.Deflate protected internal CompressionStrategy Strategy = CompressionStrategy.Default; // workitem 7159 - CRC32 crc; + private CRC32 crc; protected internal string _GzipFileName; protected internal string _GzipComment; protected internal DateTime _GzipMtime; protected internal int _gzipHeaderByteCount; - internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } } + internal int Crc32 + { + get + { + if (crc == null) return 0; + return crc.Crc32Result; + } + } public ZlibBaseStream(System.IO.Stream stream, CompressionMode compressionMode, @@ -83,10 +94,7 @@ namespace SharpCompress.Compressor.Deflate protected internal bool _wantCompress { - get - { - return (this._compressionMode == CompressionMode.Compress); - } + get { return (this._compressionMode == CompressionMode.Compress); } } private ZlibCodec z @@ -112,7 +120,6 @@ namespace SharpCompress.Compressor.Deflate } - private byte[] workingBuffer { get @@ -124,7 +131,6 @@ namespace SharpCompress.Compressor.Deflate } - public override void Write(System.Byte[] buffer, int offset, int count) { // workitem 7159 @@ -151,8 +157,8 @@ namespace SharpCompress.Compressor.Deflate _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) - ? _z.Deflate(_flushMode) - : _z.Inflate(_flushMode); + ? _z.Deflate(_flushMode) + : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); @@ -164,13 +170,10 @@ namespace SharpCompress.Compressor.Deflate // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); - - } - while (!done); + } while (!done); } - private void finish() { if (_z == null) return; @@ -184,8 +187,8 @@ namespace SharpCompress.Compressor.Deflate _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) - ? _z.Deflate(FlushType.Finish) - : _z.Inflate(FlushType.Finish); + ? _z.Deflate(FlushType.Finish) + : _z.Inflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) { @@ -205,9 +208,7 @@ namespace SharpCompress.Compressor.Deflate // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); - - } - while (!done); + } while (!done); Flush(); @@ -219,7 +220,7 @@ namespace SharpCompress.Compressor.Deflate // Emit the GZIP trailer: CRC32 and size mod 2^32 int c1 = crc.Crc32Result; _stream.Write(BitConverter.GetBytes(c1), 0, 4); - int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF); + int c2 = (Int32) (crc.TotalBytesRead & 0x00000000FFFFFFFF); _stream.Write(BitConverter.GetBytes(c2), 0, 4); } else @@ -228,7 +229,7 @@ namespace SharpCompress.Compressor.Deflate } } } - // workitem 7159 + // workitem 7159 else if (_streamMode == StreamMode.Reader) { if (_flavor == ZlibStreamFlavor.GZIP) @@ -253,8 +254,9 @@ namespace SharpCompress.Compressor.Deflate bytesNeeded); if (bytesNeeded != bytesRead) { - throw new ZlibException(String.Format("Protocol error. AvailableBytesIn={0}, expected 8", - _z.AvailableBytesIn + bytesRead)); + throw new ZlibException(String.Format( + "Protocol error. AvailableBytesIn={0}, expected 8", + _z.AvailableBytesIn + bytesRead)); } } else @@ -266,14 +268,17 @@ namespace SharpCompress.Compressor.Deflate Int32 crc32_expected = BitConverter.ToInt32(trailer, 0); Int32 crc32_actual = crc.Crc32Result; Int32 isize_expected = BitConverter.ToInt32(trailer, 4); - Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); + Int32 isize_actual = (Int32) (_z.TotalBytesOut & 0x00000000FFFFFFFF); if (crc32_actual != crc32_expected) - throw new ZlibException(String.Format("Bad CRC32 in GZIP stream. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected)); + throw new ZlibException( + String.Format("Bad CRC32 in GZIP stream. (actual({0:X8})!=expected({1:X8}))", + crc32_actual, crc32_expected)); if (isize_actual != isize_expected) - throw new ZlibException(String.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isize_actual, isize_expected)); - + throw new ZlibException( + String.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isize_actual, + isize_expected)); } else { @@ -330,6 +335,7 @@ namespace SharpCompress.Compressor.Deflate throw new NotImplementedException(); //_outStream.Seek(offset, origin); } + public override void SetLength(System.Int64 value) { _stream.SetLength(value); @@ -351,7 +357,6 @@ namespace SharpCompress.Compressor.Deflate private bool nomoreinput = false; - private string ReadZeroTerminatedString() { var list = new System.Collections.Generic.List(); @@ -401,7 +406,7 @@ namespace SharpCompress.Compressor.Deflate n = _stream.Read(header, 0, 2); // 2-byte length field totalBytesRead += n; - Int16 extraLength = (Int16)(header[0] + header[1] * 256); + Int16 extraLength = (Int16) (header[0] + header[1]*256); byte[] extra = new byte[extraLength]; n = _stream.Read(extra, 0, extra.Length); if (n != extraLength) @@ -419,7 +424,6 @@ namespace SharpCompress.Compressor.Deflate } - public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: @@ -449,7 +453,7 @@ namespace SharpCompress.Compressor.Deflate throw new ZlibException("Cannot Read after Writing."); if (count == 0) return 0; - if (nomoreinput && _wantCompress) return 0; // workitem 8557 + if (nomoreinput && _wantCompress) return 0; // workitem 8557 if (buffer == null) throw new ArgumentNullException("buffer"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset"); @@ -477,23 +481,22 @@ namespace SharpCompress.Compressor.Deflate _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) nomoreinput = true; - } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) - ? _z.Deflate(_flushMode) - : _z.Inflate(_flushMode); + ? _z.Deflate(_flushMode) + : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return 0; if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) - throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); + throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), + rc, _z.Message)); if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) break; // nothing more to read - } - //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); + } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); @@ -533,7 +536,6 @@ namespace SharpCompress.Compressor.Deflate } - public override System.Boolean CanRead { get { return this._stream.CanRead; } @@ -567,4 +569,4 @@ namespace SharpCompress.Compressor.Deflate Undefined, } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Deflate/ZlibCodec.cs b/SharpCompress/Compressor/Deflate/ZlibCodec.cs index 10aa1f5e..cd521d34 100644 --- a/SharpCompress/Compressor/Deflate/ZlibCodec.cs +++ b/SharpCompress/Compressor/Deflate/ZlibCodec.cs @@ -173,7 +173,10 @@ namespace SharpCompress.Compressor.Deflate /// /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this. /// - public int Adler32 { get { return (int)_Adler32; } } + public int Adler32 + { + get { return (int) _Adler32; } + } /// @@ -184,7 +187,9 @@ namespace SharpCompress.Compressor.Deflate /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress /// or decompress. /// - public ZlibCodec() { } + public ZlibCodec() + { + } /// /// Create a ZlibCodec that either compresses or decompresses. @@ -277,7 +282,8 @@ namespace SharpCompress.Compressor.Deflate public int InitializeInflate(int windowBits, bool expectRfc1950Header) { this.WindowBits = windowBits; - if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); + if (dstate != null) + throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); istate = new InflateManager(expectRfc1950Header); return istate.Initialize(this, windowBits); } @@ -500,7 +506,8 @@ namespace SharpCompress.Compressor.Deflate private int _InternalInitializeDeflate(bool wantRfc1950Header) { - if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate()."); + if (istate != null) + throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate()."); dstate = new DeflateManager(); dstate.WantRfc1950HeaderBytes = wantRfc1950Header; @@ -665,7 +672,7 @@ namespace SharpCompress.Compressor.Deflate OutputBuffer.Length < (NextOut + len)) { throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})", - dstate.pending.Length, dstate.pendingCount)); + dstate.pending.Length, dstate.pendingCount)); } Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len); @@ -706,6 +713,5 @@ namespace SharpCompress.Compressor.Deflate TotalBytesIn += len; return len; } - } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Deflate/ZlibConstants.cs b/SharpCompress/Compressor/Deflate/ZlibConstants.cs index 730afa10..97ffee4a 100644 --- a/SharpCompress/Compressor/Deflate/ZlibConstants.cs +++ b/SharpCompress/Compressor/Deflate/ZlibConstants.cs @@ -61,7 +61,6 @@ // ----------------------------------------------------------------------- - namespace SharpCompress.Compressor.Deflate { /// @@ -117,11 +116,10 @@ namespace SharpCompress.Compressor.Deflate #else public const int WorkingBufferSizeDefault = 16384; #endif + /// /// The minimum size of the working buffer used in the ZlibCodec class. Currently it is 128 bytes. /// public const int WorkingBufferSizeMin = 1024; } - -} - +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Filters/BCJ2Filter.cs b/SharpCompress/Compressor/Filters/BCJ2Filter.cs index c6bf2db4..a09d0cce 100644 --- a/SharpCompress/Compressor/Filters/BCJ2Filter.cs +++ b/SharpCompress/Compressor/Filters/BCJ2Filter.cs @@ -89,14 +89,8 @@ namespace SharpCompress.Compressor.Filters public override long Position { - get - { - return position; - } - set - { - throw new NotImplementedException(); - } + get { return position; } + set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) @@ -171,9 +165,15 @@ namespace SharpCompress.Compressor.Filters uint dest; if (b == 0xE8) - dest = (uint)((data1[data1Pos++] << 24) | (data1[data1Pos++] << 16) | (data1[data1Pos++] << 8) | data1[data1Pos++]); + dest = + (uint) + ((data1[data1Pos++] << 24) | (data1[data1Pos++] << 16) | (data1[data1Pos++] << 8) | + data1[data1Pos++]); else - dest = (uint)((data2[data2Pos++] << 24) | (data2[data2Pos++] << 16) | (data2[data2Pos++] << 8) | data2[data2Pos++]); + dest = + (uint) + ((data2[data2Pos++] << 24) | (data2[data2Pos++] << 16) | (data2[data2Pos++] << 8) | + data2[data2Pos++]); dest -= (uint)(position + 4); output[0] = (byte)dest; @@ -204,4 +204,4 @@ namespace SharpCompress.Compressor.Filters throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Filters/BCJFilter.cs b/SharpCompress/Compressor/Filters/BCJFilter.cs index a6861434..7cf1de33 100644 --- a/SharpCompress/Compressor/Filters/BCJFilter.cs +++ b/SharpCompress/Compressor/Filters/BCJFilter.cs @@ -5,6 +5,7 @@ namespace SharpCompress.Compressor.Filters internal class BCJFilter : Filter { private static readonly bool[] MASK_TO_ALLOWED_STATUS = new bool[] { true, true, true, false, true, false, false, false }; + private static readonly int[] MASK_TO_BIT_NUMBER = new int[] { 0, 1, 2, 2, 3, 3, 3, 3 }; private int pos; @@ -34,7 +35,8 @@ namespace SharpCompress.Compressor.Filters prevPos = i - prevPos; if ((prevPos & ~3) != 0) - { // (unsigned)prevPos > 3 + { + // (unsigned)prevPos > 3 prevMask = 0; } else @@ -43,7 +45,7 @@ namespace SharpCompress.Compressor.Filters if (prevMask != 0) { if (!MASK_TO_ALLOWED_STATUS[prevMask] || test86MSByte( - buffer[i + 4 - MASK_TO_BIT_NUMBER[prevMask]])) + buffer[i + 4 - MASK_TO_BIT_NUMBER[prevMask]])) { prevPos = i; prevMask = (prevMask << 1) | 1; @@ -98,4 +100,4 @@ namespace SharpCompress.Compressor.Filters return i; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Filters/Filter.cs b/SharpCompress/Compressor/Filters/Filter.cs index f0d10e79..80607edd 100644 --- a/SharpCompress/Compressor/Filters/Filter.cs +++ b/SharpCompress/Compressor/Filters/Filter.cs @@ -49,14 +49,8 @@ namespace SharpCompress.Compressor.Filters public override long Position { - get - { - return baseStream.Position; - } - set - { - throw new NotImplementedException(); - } + get { return baseStream.Position; } + set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) @@ -145,4 +139,4 @@ namespace SharpCompress.Compressor.Filters protected abstract int Transform(byte[] buffer, int offset, int count); } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/AesDecoderStream.cs b/SharpCompress/Compressor/LZMA/AesDecoderStream.cs index 3f58af86..18bb4531 100644 --- a/SharpCompress/Compressor/LZMA/AesDecoderStream.cs +++ b/SharpCompress/Compressor/LZMA/AesDecoderStream.cs @@ -6,7 +6,7 @@ using SharpCompress.Compressor.LZMA.Utilites; namespace SharpCompress.Compressor.LZMA { - internal class AesDecoderStream: DecoderStream2 + internal class AesDecoderStream : DecoderStream2 { #region Variables @@ -28,7 +28,7 @@ namespace SharpCompress.Compressor.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."); int numCyclesPower; @@ -38,7 +38,7 @@ namespace SharpCompress.Compressor.LZMA byte[] password = Encoding.Unicode.GetBytes(pass.CryptoGetTextPassword()); byte[] key = InitKey(numCyclesPower, salt, password); - using(var aes = Aes.Create()) + using (var aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; @@ -52,7 +52,7 @@ namespace SharpCompress.Compressor.LZMA { try { - if(disposing) + if (disposing) { mStream.Dispose(); mDecoder.Dispose(); @@ -76,14 +76,14 @@ namespace SharpCompress.Compressor.LZMA public override int Read(byte[] buffer, int offset, int count) { - if(count == 0 || mWritten == mLimit) + if (count == 0 || mWritten == mLimit) return 0; - if(mUnderflow > 0) + if (mUnderflow > 0) return HandleUnderflow(buffer, offset, count); // Need at least 16 bytes to proceed. - if(mEnding - mOffset < 16) + if (mEnding - mOffset < 16) { Buffer.BlockCopy(mBuffer, mOffset, mBuffer, 0, mEnding - mOffset); mEnding -= mOffset; @@ -92,30 +92,29 @@ namespace SharpCompress.Compressor.LZMA do { int read = mStream.Read(mBuffer, mEnding, mBuffer.Length - mEnding); - if(read == 0) + if (read == 0) { // We are not done decoding and have less than 16 bytes. throw new EndOfStreamException(); } mEnding += read; - } - while(mEnding - mOffset < 16); + } while (mEnding - mOffset < 16); } // We shouldn't return more data than we are limited to. // Currently this is handled by forcing an underflow if // the stream length is not a multiple of the block size. - if(count > mLimit - mWritten) - count = (int)(mLimit - mWritten); + if (count > mLimit - mWritten) + count = (int) (mLimit - mWritten); // We cannot transform less than 16 bytes into the target buffer, // but we also cannot return zero, so we need to handle this. // We transform the data locally and use our own buffer as cache. - if(count < 16) + if (count < 16) return HandleUnderflow(buffer, offset, count); - if(count > mEnding - mOffset) + if (count > mEnding - mOffset) count = mEnding - mOffset; // Otherwise we transform directly into the target buffer. @@ -134,7 +133,7 @@ namespace SharpCompress.Compressor.LZMA byte bt = info[0]; numCyclesPower = bt & 0x3F; - if((bt & 0xC0) == 0) + if ((bt & 0xC0) == 0) { salt = new byte[0]; iv = new byte[0]; @@ -143,48 +142,48 @@ namespace SharpCompress.Compressor.LZMA int saltSize = (bt >> 7) & 1; int ivSize = (bt >> 6) & 1; - if(info.Length == 1) + if (info.Length == 1) throw new InvalidOperationException(); byte bt2 = info[1]; saltSize += (bt2 >> 4); ivSize += (bt2 & 15); - if(info.Length < 2 + saltSize + ivSize) + if (info.Length < 2 + saltSize + ivSize) throw new InvalidOperationException(); salt = new byte[saltSize]; - for(int i = 0; i < saltSize; i++) + for (int i = 0; i < saltSize; i++) salt[i] = info[i + 2]; iv = new byte[16]; - for(int i = 0; i < ivSize; i++) + for (int i = 0; i < ivSize; i++) iv[i] = info[i + saltSize + 2]; - if(numCyclesPower > 24) + if (numCyclesPower > 24) throw new NotSupportedException(); } private byte[] InitKey(int mNumCyclesPower, byte[] salt, byte[] pass) { - if(mNumCyclesPower == 0x3F) + if (mNumCyclesPower == 0x3F) { var key = new byte[32]; int pos; - for(pos = 0; pos < salt.Length; pos++) + for (pos = 0; pos < salt.Length; pos++) key[pos] = salt[pos]; - for(int i = 0; i < pass.Length && pos < 32; i++) + for (int i = 0; i < pass.Length && pos < 32; i++) key[pos++] = pass[i]; return key; } else { - using(var sha = System.Security.Cryptography.SHA256.Create()) + using (var sha = System.Security.Cryptography.SHA256.Create()) { byte[] counter = new byte[8]; long numRounds = 1L << mNumCyclesPower; - for(long round = 0; round < numRounds; round++) + for (long round = 0; round < numRounds; round++) { sha.TransformBlock(salt, 0, salt.Length, null, 0); sha.TransformBlock(pass, 0, pass.Length, null, 0); @@ -192,8 +191,8 @@ namespace SharpCompress.Compressor.LZMA // This mirrors the counter so we don't have to convert long to byte[] each round. // (It also ensures the counter is little endian, which BitConverter does not.) - for(int i = 0; i < 8; i++) - if(++counter[i] != 0) + for (int i = 0; i < 8; i++) + if (++counter[i] != 0) break; } @@ -207,13 +206,13 @@ namespace SharpCompress.Compressor.LZMA { // If this is zero we were called to create a new underflow buffer. // Just transform as much as possible so we can feed from it as long as possible. - if(mUnderflow == 0) + if (mUnderflow == 0) { int blockSize = (mEnding - mOffset) & ~15; mUnderflow = mDecoder.TransformBlock(mBuffer, mOffset, blockSize, mBuffer, mOffset); } - if(count > mUnderflow) + if (count > mUnderflow) count = mUnderflow; Buffer.BlockCopy(mBuffer, mOffset, buffer, offset, count); @@ -225,4 +224,4 @@ namespace SharpCompress.Compressor.LZMA #endregion } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/Bcj2DecoderStream.cs b/SharpCompress/Compressor/LZMA/Bcj2DecoderStream.cs index 100c0912..fd5de275 100644 --- a/SharpCompress/Compressor/LZMA/Bcj2DecoderStream.cs +++ b/SharpCompress/Compressor/LZMA/Bcj2DecoderStream.cs @@ -4,10 +4,10 @@ using System.IO; namespace SharpCompress.Compressor.LZMA { - class Bcj2DecoderStream: DecoderStream2 + internal class Bcj2DecoderStream : DecoderStream2 { - const int kNumTopBits = 24; - const uint kTopValue = (1 << kNumTopBits); + private const int kNumTopBits = 24; + private const uint kTopValue = (1 << kNumTopBits); private class RangeDecoder { @@ -19,17 +19,17 @@ namespace SharpCompress.Compressor.LZMA { mStream = stream; Range = 0xFFFFFFFF; - for(int i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) Code = (Code << 8) | ReadByte(); } public byte ReadByte() { int bt = mStream.ReadByte(); - if(bt < 0) + if (bt < 0) throw new EndOfStreamException(); - return (byte)bt; + return (byte) bt; } public void Dispose() @@ -49,7 +49,7 @@ namespace SharpCompress.Compressor.LZMA public StatusDecoder() { - Prob = kBitModelTotal / 2; + Prob = kBitModelTotal/2; } private void UpdateModel(uint symbol) @@ -58,7 +58,7 @@ namespace SharpCompress.Compressor.LZMA Prob -= (Prob + ((symbol - 1) & ((1 << numMoveBits) - 1))) >> numMoveBits; Prob += (1 - symbol) << (kNumBitModelTotalBits - numMoveBits); */ - if(symbol == 0) + if (symbol == 0) Prob += (kBitModelTotal - Prob) >> numMoveBits; else Prob -= (Prob) >> numMoveBits; @@ -66,12 +66,12 @@ namespace SharpCompress.Compressor.LZMA public uint Decode(RangeDecoder decoder) { - uint newBound = (decoder.Range >> kNumBitModelTotalBits) * Prob; - if(decoder.Code < newBound) + uint newBound = (decoder.Range >> kNumBitModelTotalBits)*Prob; + if (decoder.Code < newBound) { decoder.Range = newBound; Prob += (kBitModelTotal - Prob) >> numMoveBits; - if(decoder.Range < kTopValue) + if (decoder.Range < kTopValue) { decoder.Code = (decoder.Code << 8) | decoder.ReadByte(); decoder.Range <<= 8; @@ -83,7 +83,7 @@ namespace SharpCompress.Compressor.LZMA decoder.Range -= newBound; decoder.Code -= newBound; Prob -= Prob >> numMoveBits; - if(decoder.Range < kTopValue) + if (decoder.Range < kTopValue) { decoder.Code = (decoder.Code << 8) | decoder.ReadByte(); decoder.Range <<= 8; @@ -105,10 +105,10 @@ namespace SharpCompress.Compressor.LZMA public Bcj2DecoderStream(Stream[] streams, byte[] info, long limit) { - if(info != null && info.Length > 0) + if (info != null && info.Length > 0) throw new NotSupportedException(); - if(streams.Length != 4) + if (streams.Length != 4) throw new NotSupportedException(); mLimit = limit; @@ -118,7 +118,7 @@ namespace SharpCompress.Compressor.LZMA mRangeDecoder = new RangeDecoder(streams[3]); mStatusDecoder = new StatusDecoder[256 + 2]; - for(int i = 0; i < mStatusDecoder.Length; i++) + for (int i = 0; i < mStatusDecoder.Length; i++) mStatusDecoder[i] = new StatusDecoder(); mIter = Run().GetEnumerator(); @@ -127,20 +127,20 @@ namespace SharpCompress.Compressor.LZMA private static bool IsJcc(byte b0, byte b1) { return b0 == 0x0F - && (b1 & 0xF0) == 0x80; + && (b1 & 0xF0) == 0x80; } private static bool IsJ(byte b0, byte b1) { return (b1 & 0xFE) == 0xE8 - || IsJcc(b0, b1); + || IsJcc(b0, b1); } private static int GetIndex(byte b0, byte b1) { - if(b1 == 0xE8) + if (b1 == 0xE8) return b0; - else if(b1 == 0xE9) + else if (b1 == 0xE9) return 256; else return 257; @@ -148,12 +148,12 @@ namespace SharpCompress.Compressor.LZMA public override int Read(byte[] buffer, int offset, int count) { - if(count == 0 || mFinished) + if (count == 0 || mFinished) return 0; - for(int i = 0; i < count; i++) + for (int i = 0; i < count; i++) { - if(!mIter.MoveNext()) + if (!mIter.MoveNext()) { mFinished = true; return i; @@ -171,49 +171,54 @@ namespace SharpCompress.Compressor.LZMA byte prevByte = 0; uint processedBytes = 0; - for(; ; ) + for (;;) { byte b = 0; uint i; - for(i = 0; i < kBurstSize; i++) + for (i = 0; i < kBurstSize; i++) { int tmp = mMainStream.ReadByte(); - if(tmp < 0) + if (tmp < 0) yield break; - b = (byte)tmp; - mWritten++; yield return b; - if(IsJ(prevByte, b)) + b = (byte) tmp; + mWritten++; + yield return b; + if (IsJ(prevByte, b)) break; prevByte = b; } processedBytes += i; - if(i == kBurstSize) + if (i == kBurstSize) continue; - if(mStatusDecoder[GetIndex(prevByte, b)].Decode(mRangeDecoder) == 1) + if (mStatusDecoder[GetIndex(prevByte, b)].Decode(mRangeDecoder) == 1) { Stream s = (b == 0xE8) ? mCallStream : mJumpStream; uint src = 0; - for(i = 0; i < 4; i++) + for (i = 0; i < 4; i++) { int b0 = s.ReadByte(); - if(b0 < 0) + if (b0 < 0) throw new EndOfStreamException(); src <<= 8; - src |= (uint)b0; + src |= (uint) b0; } - uint dest = src - (uint)(mWritten + 4); - mWritten++; yield return (byte)dest; - mWritten++; yield return (byte)(dest >> 8); - mWritten++; yield return (byte)(dest >> 16); - mWritten++; yield return (byte)(dest >> 24); - prevByte = (byte)(dest >> 24); + uint dest = src - (uint) (mWritten + 4); + mWritten++; + yield return (byte) dest; + mWritten++; + yield return (byte) (dest >> 8); + mWritten++; + yield return (byte) (dest >> 16); + mWritten++; + yield return (byte) (dest >> 24); + prevByte = (byte) (dest >> 24); processedBytes += 4; } else @@ -223,4 +228,4 @@ namespace SharpCompress.Compressor.LZMA } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/BitVector.cs b/SharpCompress/Compressor/LZMA/BitVector.cs index fa4ffa2b..181c7d04 100644 --- a/SharpCompress/Compressor/LZMA/BitVector.cs +++ b/SharpCompress/Compressor/LZMA/BitVector.cs @@ -84,4 +84,4 @@ namespace SharpCompress.Compressor.LZMA return sb.ToString(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/CRC.cs b/SharpCompress/Compressor/LZMA/CRC.cs index 20f74024..edaf3f90 100644 --- a/SharpCompress/Compressor/LZMA/CRC.cs +++ b/SharpCompress/Compressor/LZMA/CRC.cs @@ -6,22 +6,22 @@ namespace SharpCompress.Compressor.LZMA internal static class CRC { public const uint kInitCRC = 0xFFFFFFFF; - private static uint[] kTable = new uint[4 * 256]; + private static uint[] kTable = new uint[4*256]; static CRC() { const uint kCrcPoly = 0xEDB88320; - for(uint i = 0; i < 256; i++) + for (uint i = 0; i < 256; i++) { uint r = i; - for(int j = 0; j < 8; j++) + for (int j = 0; j < 8; j++) r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); kTable[i] = r; } - for(uint i = 256; i < kTable.Length; i++) + for (uint i = 256; i < kTable.Length; i++) { uint r = kTable[i - 256]; kTable[i] = kTable[r & 0xFF] ^ (r >> 8); @@ -32,10 +32,10 @@ namespace SharpCompress.Compressor.LZMA { uint crc = kInitCRC; byte[] buffer = new byte[Math.Min(length, 4 << 10)]; - while(length > 0) + while (length > 0) { - int delta = stream.Read(buffer, 0, (int)Math.Min(length, buffer.Length)); - if(delta == 0) + int delta = stream.Read(buffer, 0, (int) Math.Min(length, buffer.Length)); + if (delta == 0) throw new EndOfStreamException(); crc = Update(crc, buffer, 0, delta); length -= delta; @@ -57,24 +57,24 @@ namespace SharpCompress.Compressor.LZMA { crc ^= value; return kTable[0x300 + (crc & 0xFF)] - ^ kTable[0x200 + ((crc >> 8) & 0xFF)] - ^ kTable[0x100 + ((crc >> 16) & 0xFF)] - ^ kTable[0x000 + (crc >> 24)]; + ^ kTable[0x200 + ((crc >> 8) & 0xFF)] + ^ kTable[0x100 + ((crc >> 16) & 0xFF)] + ^ kTable[0x000 + (crc >> 24)]; } public static uint Update(uint crc, ulong value) { - return Update(Update(crc, (uint)value), (uint)(value >> 32)); + return Update(Update(crc, (uint) value), (uint) (value >> 32)); } public static uint Update(uint crc, long value) { - return Update(crc, (ulong)value); + return Update(crc, (ulong) value); } public static uint Update(uint crc, byte[] buffer, int offset, int length) { - for(int i = 0; i < length; i++) + for (int i = 0; i < length; i++) crc = Update(crc, buffer[offset + i]); return crc; @@ -83,21 +83,21 @@ namespace SharpCompress.Compressor.LZMA #if !SILVERLIGHT && !PORTABLE public static unsafe uint Update(uint crc, byte* buffer, int length) { - while(length > 0 && ((int)buffer & 3) != 0) + while (length > 0 && ((int) buffer & 3) != 0) { crc = Update(crc, *buffer); buffer++; length--; } - while(length >= 4) + while (length >= 4) { - crc = Update(crc, *(uint*)buffer); + crc = Update(crc, *(uint*) buffer); buffer += 4; length -= 4; } - while(length > 0) + while (length > 0) { crc = Update(crc, *buffer); length--; @@ -108,4 +108,4 @@ namespace SharpCompress.Compressor.LZMA #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/DecoderStream.cs b/SharpCompress/Compressor/LZMA/DecoderStream.cs index 3009e2bc..99e7f350 100644 --- a/SharpCompress/Compressor/LZMA/DecoderStream.cs +++ b/SharpCompress/Compressor/LZMA/DecoderStream.cs @@ -5,7 +5,7 @@ using SharpCompress.Compressor.LZMA.Utilites; namespace SharpCompress.Compressor.LZMA { - abstract class DecoderStream2: Stream + internal abstract class DecoderStream2 : Stream { public override bool CanRead { @@ -54,38 +54,39 @@ namespace SharpCompress.Compressor.LZMA } } - static class DecoderStreamHelper + internal static class DecoderStreamHelper { private static int FindCoderIndexForOutStreamIndex(CFolder folderInfo, int outStreamIndex) { - for(int coderIndex = 0; coderIndex < folderInfo.Coders.Count; coderIndex++) + for (int coderIndex = 0; coderIndex < folderInfo.Coders.Count; coderIndex++) { var coderInfo = folderInfo.Coders[coderIndex]; outStreamIndex -= coderInfo.NumOutStreams; - if(outStreamIndex < 0) + if (outStreamIndex < 0) return coderIndex; } throw new InvalidOperationException("Could not link output stream to coder."); } - private static void FindPrimaryOutStreamIndex(CFolder folderInfo, out int primaryCoderIndex, out int primaryOutStreamIndex) + private static void FindPrimaryOutStreamIndex(CFolder folderInfo, out int primaryCoderIndex, + out int primaryOutStreamIndex) { bool foundPrimaryOutStream = false; primaryCoderIndex = -1; primaryOutStreamIndex = -1; - for(int outStreamIndex = 0, coderIndex = 0; - coderIndex < folderInfo.Coders.Count; - coderIndex++) + for (int outStreamIndex = 0, coderIndex = 0; + coderIndex < folderInfo.Coders.Count; + coderIndex++) { - for(int coderOutStreamIndex = 0; - coderOutStreamIndex < folderInfo.Coders[coderIndex].NumOutStreams; - coderOutStreamIndex++, outStreamIndex++) + for (int coderOutStreamIndex = 0; + coderOutStreamIndex < folderInfo.Coders[coderIndex].NumOutStreams; + coderOutStreamIndex++, outStreamIndex++) { - if(folderInfo.FindBindPairForOutStream(outStreamIndex) < 0) + if (folderInfo.FindBindPairForOutStream(outStreamIndex) < 0) { - if(foundPrimaryOutStream) + if (foundPrimaryOutStream) throw new NotSupportedException("Multiple output streams."); foundPrimaryOutStream = true; @@ -95,41 +96,43 @@ namespace SharpCompress.Compressor.LZMA } } - if(!foundPrimaryOutStream) + if (!foundPrimaryOutStream) throw new NotSupportedException("No output stream."); } - private static Stream CreateDecoderStream(Stream[] packStreams, long[] packSizes, Stream[] outStreams, CFolder folderInfo, int coderIndex, IPasswordProvider pass) + private static Stream CreateDecoderStream(Stream[] packStreams, long[] packSizes, Stream[] outStreams, + CFolder folderInfo, int coderIndex, IPasswordProvider pass) { var coderInfo = folderInfo.Coders[coderIndex]; - if(coderInfo.NumOutStreams != 1) + if (coderInfo.NumOutStreams != 1) throw new NotSupportedException("Multiple output streams are not supported."); int inStreamId = 0; - for(int i = 0; i < coderIndex; i++) + for (int i = 0; i < coderIndex; i++) inStreamId += folderInfo.Coders[i].NumInStreams; int outStreamId = 0; - for(int i = 0; i < coderIndex; i++) + for (int i = 0; i < coderIndex; i++) outStreamId += folderInfo.Coders[i].NumOutStreams; Stream[] inStreams = new Stream[coderInfo.NumInStreams]; - for(int i = 0; i < inStreams.Length; i++, inStreamId++) + for (int i = 0; i < inStreams.Length; i++, inStreamId++) { int bindPairIndex = folderInfo.FindBindPairForInStream(inStreamId); - if(bindPairIndex >= 0) + if (bindPairIndex >= 0) { int pairedOutIndex = folderInfo.BindPairs[bindPairIndex].OutIndex; - if(outStreams[pairedOutIndex] != null) + if (outStreams[pairedOutIndex] != null) throw new NotSupportedException("Overlapping stream bindings are not supported."); int otherCoderIndex = FindCoderIndexForOutStreamIndex(folderInfo, pairedOutIndex); - inStreams[i] = CreateDecoderStream(packStreams, packSizes, outStreams, folderInfo, otherCoderIndex, pass); + inStreams[i] = CreateDecoderStream(packStreams, packSizes, outStreams, folderInfo, otherCoderIndex, + pass); //inStreamSizes[i] = folderInfo.UnpackSizes[pairedOutIndex]; - if(outStreams[pairedOutIndex] != null) + if (outStreams[pairedOutIndex] != null) throw new NotSupportedException("Overlapping stream bindings are not supported."); outStreams[pairedOutIndex] = inStreams[i]; @@ -137,7 +140,7 @@ namespace SharpCompress.Compressor.LZMA else { int index = folderInfo.FindPackStreamArrayIndex(inStreamId); - if(index < 0) + if (index < 0) throw new NotSupportedException("Could not find input stream binding."); inStreams[i] = packStreams[index]; @@ -149,15 +152,16 @@ namespace SharpCompress.Compressor.LZMA return DecoderRegistry.CreateDecoderStream(coderInfo.MethodId, inStreams, coderInfo.Props, pass, unpackSize); } - internal static Stream CreateDecoderStream(Stream inStream, long startPos, long[] packSizes, CFolder folderInfo, IPasswordProvider pass) + internal static Stream CreateDecoderStream(Stream inStream, long startPos, long[] packSizes, CFolder folderInfo, + IPasswordProvider pass) { - if(!folderInfo.CheckStructure()) + if (!folderInfo.CheckStructure()) throw new NotSupportedException("Unsupported stream binding structure."); // We have multiple views into the same stream which will be used by several threads - need to sync those. object sync = new object(); Stream[] inStreams = new Stream[folderInfo.PackStreams.Count]; - for(int j = 0; j < folderInfo.PackStreams.Count; j++) + for (int j = 0; j < folderInfo.PackStreams.Count; j++) { inStreams[j] = new SyncStreamView(sync, inStream, startPos, packSizes[j]); startPos += packSizes[j]; @@ -170,4 +174,4 @@ namespace SharpCompress.Compressor.LZMA return CreateDecoderStream(inStreams, packSizes, outStreams, folderInfo, primaryCoderIndex, pass); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/ICoder.cs b/SharpCompress/Compressor/LZMA/ICoder.cs index 9f98d120..5d9b8caa 100644 --- a/SharpCompress/Compressor/LZMA/ICoder.cs +++ b/SharpCompress/Compressor/LZMA/ICoder.cs @@ -7,7 +7,9 @@ namespace SharpCompress.Compressor.LZMA /// internal class DataErrorException : Exception { - public DataErrorException() : base("Data Error") { } + public DataErrorException() : base("Data Error") + { + } } /// @@ -15,7 +17,9 @@ namespace SharpCompress.Compressor.LZMA /// internal class InvalidParamException : Exception { - public InvalidParamException() : base("Invalid Parameter") { } + public InvalidParamException() : base("Invalid Parameter") + { + } } internal interface ICodeProgress @@ -53,7 +57,7 @@ namespace SharpCompress.Compressor.LZMA /// callback progress reference. /// void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress); + Int64 inSize, Int64 outSize, ICodeProgress progress); }; /* @@ -76,58 +80,72 @@ namespace SharpCompress.Compressor.LZMA /// Specifies default property. /// DefaultProp = 0, + /// /// Specifies size of dictionary. /// DictionarySize, + /// /// Specifies size of memory for PPM*. /// UsedMemorySize, + /// /// Specifies order for PPM methods. /// Order, + /// /// Specifies Block Size. /// BlockSize, + /// /// Specifies number of postion state bits for LZMA (0 - x - 4). /// PosStateBits, + /// /// Specifies number of literal context bits for LZMA (0 - x - 8). /// LitContextBits, + /// /// Specifies number of literal position bits for LZMA (0 - x - 4). /// LitPosBits, + /// /// Specifies number of fast bytes for LZ*. /// NumFastBytes, + /// /// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B". /// MatchFinder, + /// /// Specifies the number of match finder cyckes. /// MatchFinderCycles, + /// /// Specifies number of passes. /// NumPasses, + /// /// Specifies number of algorithm. /// Algorithm, + /// /// Specifies the number of threads. /// NumThreads, + /// /// Specifies mode with end marker. /// @@ -149,4 +167,4 @@ namespace SharpCompress.Compressor.LZMA { void SetDecoderProperties(byte[] properties); } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LZ/CRC.cs b/SharpCompress/Compressor/LZMA/LZ/CRC.cs index 1ab52e13..2079c63f 100644 --- a/SharpCompress/Compressor/LZMA/LZ/CRC.cs +++ b/SharpCompress/Compressor/LZMA/LZ/CRC.cs @@ -20,24 +20,30 @@ namespace SharpCompress.Compressor.LZMA.LZ } } - uint _value = 0xFFFFFFFF; + private uint _value = 0xFFFFFFFF; - public void Init() { _value = 0xFFFFFFFF; } + public void Init() + { + _value = 0xFFFFFFFF; + } public void UpdateByte(byte b) { - _value = Table[(((byte)(_value)) ^ b)] ^ (_value >> 8); + _value = Table[(((byte) (_value)) ^ b)] ^ (_value >> 8); } public void Update(byte[] data, uint offset, uint size) { for (uint i = 0; i < size; i++) - _value = Table[(((byte)(_value)) ^ data[offset + i])] ^ (_value >> 8); + _value = Table[(((byte) (_value)) ^ data[offset + i])] ^ (_value >> 8); } - public uint GetDigest() { return _value ^ 0xFFFFFFFF; } + public uint GetDigest() + { + return _value ^ 0xFFFFFFFF; + } - static uint CalculateDigest(byte[] data, uint offset, uint size) + private static uint CalculateDigest(byte[] data, uint offset, uint size) { CRC crc = new CRC(); // crc.Init(); @@ -45,9 +51,9 @@ namespace SharpCompress.Compressor.LZMA.LZ return crc.GetDigest(); } - static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size) + private static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size) { return (CalculateDigest(data, offset, size) == digest); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs b/SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs index 9762de9b..3032d0d8 100644 --- a/SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs +++ b/SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs @@ -4,30 +4,30 @@ namespace SharpCompress.Compressor.LZMA.LZ { internal class BinTree : InWindow { - UInt32 _cyclicBufferPos; - UInt32 _cyclicBufferSize = 0; - UInt32 _matchMaxLen; + private UInt32 _cyclicBufferPos; + private UInt32 _cyclicBufferSize = 0; + private UInt32 _matchMaxLen; - UInt32[] _son; - UInt32[] _hash; + private UInt32[] _son; + private UInt32[] _hash; - UInt32 _cutValue = 0xFF; - UInt32 _hashMask; - UInt32 _hashSizeSum = 0; + private UInt32 _cutValue = 0xFF; + private UInt32 _hashMask; + private UInt32 _hashSizeSum = 0; - bool HASH_ARRAY = true; + private bool HASH_ARRAY = true; - const UInt32 kHash2Size = 1 << 10; - const UInt32 kHash3Size = 1 << 16; - const UInt32 kBT2HashSize = 1 << 16; - const UInt32 kStartMaxLen = 1; - const UInt32 kHash3Offset = kHash2Size; - const UInt32 kEmptyHashValue = 0; - const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1; + private const UInt32 kHash2Size = 1 << 10; + private const UInt32 kHash3Size = 1 << 16; + private const UInt32 kBT2HashSize = 1 << 16; + private const UInt32 kStartMaxLen = 1; + private const UInt32 kHash3Offset = kHash2Size; + private const UInt32 kEmptyHashValue = 0; + private const UInt32 kMaxValForNormalize = ((UInt32) 1 << 31) - 1; - UInt32 kNumHashDirectBytes = 0; - UInt32 kMinMatchCheck = 4; - UInt32 kFixHashSize = kHash2Size + kHash3Size; + private UInt32 kNumHashDirectBytes = 0; + private UInt32 kMinMatchCheck = 4; + private UInt32 kFixHashSize = kHash2Size + kHash3Size; public void SetType(int numHashBytes) { @@ -46,8 +46,15 @@ namespace SharpCompress.Compressor.LZMA.LZ } } - public new void SetStream(System.IO.Stream stream) { base.SetStream(stream); } - public new void ReleaseStream() { base.ReleaseStream(); } + public new void SetStream(System.IO.Stream stream) + { + base.SetStream(stream); + } + + public new void ReleaseStream() + { + base.ReleaseStream(); + } public new void Init() { @@ -67,22 +74,30 @@ namespace SharpCompress.Compressor.LZMA.LZ Normalize(); } - public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); } + public new Byte GetIndexByte(Int32 index) + { + return base.GetIndexByte(index); + } public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) - { return base.GetMatchLen(index, distance, limit); } + { + return base.GetMatchLen(index, distance, limit); + } - public new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); } + public new UInt32 GetNumAvailableBytes() + { + return base.GetNumAvailableBytes(); + } public void Create(UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter) + UInt32 matchMaxLen, UInt32 keepAddBufferAfter) { if (historySize > kMaxValForNormalize - 256) throw new Exception(); _cutValue = 16 + (matchMaxLen >> 1); UInt32 windowReservSize = (historySize + keepAddBufferBefore + - matchMaxLen + keepAddBufferAfter) / 2 + 256; + matchMaxLen + keepAddBufferAfter)/2 + 256; base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); @@ -90,7 +105,7 @@ namespace SharpCompress.Compressor.LZMA.LZ UInt32 cyclicBufferSize = historySize + 1; if (_cyclicBufferSize != cyclicBufferSize) - _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2]; + _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize)*2]; UInt32 hs = kBT2HashSize; @@ -138,12 +153,12 @@ namespace SharpCompress.Compressor.LZMA.LZ { UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; hash2Value = temp & (kHash2Size - 1); - temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); + temp ^= ((UInt32) (_bufferBase[cur + 2]) << 8); hash3Value = temp & (kHash3Size - 1); hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else - hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); + hashValue = _bufferBase[cur] ^ ((UInt32) (_bufferBase[cur + 1]) << 8); UInt32 curMatch = _hash[kFixHashSize + hashValue]; if (HASH_ARRAY) @@ -187,7 +202,7 @@ namespace SharpCompress.Compressor.LZMA.LZ if (curMatch > matchMinPos) { if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != - _bufferBase[cur + kNumHashDirectBytes]) + _bufferBase[cur + kNumHashDirectBytes]) { distances[offset++] = maxLen = kNumHashDirectBytes; distances[offset++] = _pos - curMatch - 1; @@ -205,9 +220,9 @@ namespace SharpCompress.Compressor.LZMA.LZ break; } UInt32 delta = _pos - curMatch; - UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? - (_cyclicBufferPos - delta) : - (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; + UInt32 cyclicPos = ((delta <= _cyclicBufferPos) + ? (_cyclicBufferPos - delta) + : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; UInt32 pby1 = _bufferOffset + curMatch; UInt32 len = Math.Min(len0, len1); @@ -274,13 +289,13 @@ namespace SharpCompress.Compressor.LZMA.LZ UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; UInt32 hash2Value = temp & (kHash2Size - 1); _hash[hash2Value] = _pos; - temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); + temp ^= ((UInt32) (_bufferBase[cur + 2]) << 8); UInt32 hash3Value = temp & (kHash3Size - 1); _hash[kHash3Offset + hash3Value] = _pos; hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else - hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); + hashValue = _bufferBase[cur] ^ ((UInt32) (_bufferBase[cur + 1]) << 8); UInt32 curMatch = _hash[kFixHashSize + hashValue]; _hash[kFixHashSize + hashValue] = _pos; @@ -301,9 +316,9 @@ namespace SharpCompress.Compressor.LZMA.LZ } UInt32 delta = _pos - curMatch; - UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? - (_cyclicBufferPos - delta) : - (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; + UInt32 cyclicPos = ((delta <= _cyclicBufferPos) + ? (_cyclicBufferPos - delta) + : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; UInt32 pby1 = _bufferOffset + curMatch; UInt32 len = Math.Min(len0, len1); @@ -335,11 +350,10 @@ namespace SharpCompress.Compressor.LZMA.LZ } } MovePos(); - } - while (--num != 0); + } while (--num != 0); } - void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) + private void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) { for (UInt32 i = 0; i < numItems; i++) { @@ -352,14 +366,17 @@ namespace SharpCompress.Compressor.LZMA.LZ } } - void Normalize() + private void Normalize() { UInt32 subValue = _pos - _cyclicBufferSize; - NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); + NormalizeLinks(_son, _cyclicBufferSize*2, subValue); NormalizeLinks(_hash, _hashSizeSum, subValue); - ReduceOffsets((Int32)subValue); + ReduceOffsets((Int32) subValue); } - public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; } + public void SetCutValue(UInt32 cutValue) + { + _cutValue = cutValue; + } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LZ/LzInWindow.cs b/SharpCompress/Compressor/LZMA/LZ/LzInWindow.cs index 1831a51d..fb2dfc8b 100644 --- a/SharpCompress/Compressor/LZMA/LZ/LzInWindow.cs +++ b/SharpCompress/Compressor/LZMA/LZ/LzInWindow.cs @@ -5,28 +5,28 @@ namespace SharpCompress.Compressor.LZMA.LZ internal class InWindow { public Byte[] _bufferBase = null; // pointer to buffer with data - System.IO.Stream _stream; - UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done - bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream + private System.IO.Stream _stream; + private UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done + private bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream - UInt32 _pointerToLastSafePosition; + private UInt32 _pointerToLastSafePosition; public UInt32 _bufferOffset; public UInt32 _blockSize; // Size of Allocated memory block public UInt32 _pos; // offset (from _buffer) of curent byte - UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos - UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos + private UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos + private UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos public UInt32 _streamPos; // offset (from _buffer) of first not read byte from Stream public void MoveBlock() { - UInt32 offset = (UInt32)(_bufferOffset) + _pos - _keepSizeBefore; + UInt32 offset = (UInt32) (_bufferOffset) + _pos - _keepSizeBefore; // we need one additional byte, since MovePos moves on 1 byte. if (offset > 0) offset--; - UInt32 numBytes = (UInt32)(_bufferOffset) + _streamPos - offset; + UInt32 numBytes = (UInt32) (_bufferOffset) + _streamPos - offset; // check negative offset ???? for (UInt32 i = 0; i < numBytes; i++) @@ -40,27 +40,32 @@ namespace SharpCompress.Compressor.LZMA.LZ return; while (true) { - int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos); + int size = (int) ((0 - _bufferOffset) + _blockSize - _streamPos); if (size == 0) return; - int numReadBytes = _stream != null ? _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), size) : 0; + int numReadBytes = _stream != null + ? _stream.Read(_bufferBase, (int) (_bufferOffset + _streamPos), size) + : 0; if (numReadBytes == 0) { _posLimit = _streamPos; UInt32 pointerToPostion = _bufferOffset + _posLimit; if (pointerToPostion > _pointerToLastSafePosition) - _posLimit = (UInt32)(_pointerToLastSafePosition - _bufferOffset); + _posLimit = (UInt32) (_pointerToLastSafePosition - _bufferOffset); _streamEndWasReached = true; return; } - _streamPos += (UInt32)numReadBytes; + _streamPos += (UInt32) numReadBytes; if (_streamPos >= _pos + _keepSizeAfter) _posLimit = _streamPos - _keepSizeAfter; } } - void Free() { _bufferBase = null; } + private void Free() + { + _bufferBase = null; + } public void Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv) { @@ -87,7 +92,11 @@ namespace SharpCompress.Compressor.LZMA.LZ ReadBlock(); } } - public void ReleaseStream() { _stream = null; } + + public void ReleaseStream() + { + _stream = null; + } public void Init() { @@ -110,39 +119,42 @@ namespace SharpCompress.Compressor.LZMA.LZ } } - public Byte GetIndexByte(Int32 index) { return _bufferBase[_bufferOffset + _pos + index]; } + public Byte GetIndexByte(Int32 index) + { + return _bufferBase[_bufferOffset + _pos + index]; + } // index + limit have not to exceed _keepSizeAfter; public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) { if (_streamEndWasReached) if ((_pos + index) + limit > _streamPos) - limit = _streamPos - (UInt32)(_pos + index); + limit = _streamPos - (UInt32) (_pos + index); distance++; // Byte *pby = _buffer + (size_t)_pos + index; - UInt32 pby = _bufferOffset + _pos + (UInt32)index; + UInt32 pby = _bufferOffset + _pos + (UInt32) index; UInt32 i; for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++) ; return i; } - public UInt32 GetNumAvailableBytes() { return _streamPos - _pos; } + public UInt32 GetNumAvailableBytes() + { + return _streamPos - _pos; + } public void ReduceOffsets(Int32 subValue) { - _bufferOffset += (UInt32)subValue; - _posLimit -= (UInt32)subValue; - _pos -= (UInt32)subValue; - _streamPos -= (UInt32)subValue; + _bufferOffset += (UInt32) subValue; + _posLimit -= (UInt32) subValue; + _pos -= (UInt32) subValue; + _streamPos -= (UInt32) subValue; } public bool IsDataStarved { - get - { - return _streamPos - _pos < _keepSizeAfter; - } + get { return _streamPos - _pos < _keepSizeAfter; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LZ/LzOutWindow.cs b/SharpCompress/Compressor/LZMA/LZ/LzOutWindow.cs index a27e12b0..ce91c5d8 100644 --- a/SharpCompress/Compressor/LZMA/LZ/LzOutWindow.cs +++ b/SharpCompress/Compressor/LZMA/LZ/LzOutWindow.cs @@ -2,13 +2,13 @@ namespace SharpCompress.Compressor.LZMA.LZ { internal class OutWindow { - byte[] _buffer = null; - int _windowSize = 0; - int _pos; - int _streamPos; - int _pendingLen; - int _pendingDist; - System.IO.Stream _stream; + private byte[] _buffer = null; + private int _windowSize = 0; + private int _pos; + private int _streamPos; + private int _pendingLen; + private int _pendingDist; + private System.IO.Stream _stream; public long Total; public long Limit; @@ -41,7 +41,7 @@ namespace SharpCompress.Compressor.LZMA.LZ public void Train(System.IO.Stream stream) { long len = stream.Length; - int size = (len < _windowSize) ? (int)len : _windowSize; + int size = (len < _windowSize) ? (int) len : _windowSize; stream.Position = len - size; Total = 0; Limit = size; @@ -113,7 +113,7 @@ namespace SharpCompress.Compressor.LZMA.LZ { int curSize = _windowSize - _pos; if (curSize > Limit - Total) - curSize = (int)(Limit - Total); + curSize = (int) (Limit - Total); if (curSize > size) curSize = size; int numReadBytes = stream.Read(_buffer, _pos, curSize); @@ -135,18 +135,12 @@ namespace SharpCompress.Compressor.LZMA.LZ public bool HasSpace { - get - { - return _pos < _windowSize && Total < Limit; - } + get { return _pos < _windowSize && Total < Limit; } } public bool HasPending { - get - { - return _pendingLen > 0; - } + get { return _pendingLen > 0; } } public int Read(byte[] buffer, int offset, int count) @@ -175,10 +169,7 @@ namespace SharpCompress.Compressor.LZMA.LZ public int AvailableBytes { - get - { - return _pos - _streamPos; - } + get { return _pos - _streamPos; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/Log.cs b/SharpCompress/Compressor/LZMA/Log.cs index b67fda7c..ec915d8c 100644 --- a/SharpCompress/Compressor/LZMA/Log.cs +++ b/SharpCompress/Compressor/LZMA/Log.cs @@ -20,7 +20,7 @@ namespace SharpCompress.Compressor.LZMA public static void PopIndent() { - if(_indent.Count == 1) + if (_indent.Count == 1) throw new InvalidOperationException(); _indent.Pop(); @@ -28,7 +28,7 @@ namespace SharpCompress.Compressor.LZMA private static void EnsureIndent() { - if(_needsIndent) + if (_needsIndent) { _needsIndent = false; #if !SILVERLIGHT && !PORTABLE @@ -88,4 +88,4 @@ namespace SharpCompress.Compressor.LZMA _needsIndent = true; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LzmaBase.cs b/SharpCompress/Compressor/LZMA/LzmaBase.cs index 2deaf900..3508ff61 100644 --- a/SharpCompress/Compressor/LZMA/LzmaBase.cs +++ b/SharpCompress/Compressor/LZMA/LzmaBase.cs @@ -13,17 +13,38 @@ namespace SharpCompress.Compressor.LZMA public struct State { public uint Index; - public void Init() { Index = 0; } + + public void Init() + { + Index = 0; + } + public void UpdateChar() { if (Index < 4) Index = 0; else if (Index < 10) Index -= 3; else Index -= 6; } - public void UpdateMatch() { Index = (uint)(Index < 7 ? 7 : 10); } - public void UpdateRep() { Index = (uint)(Index < 7 ? 8 : 11); } - public void UpdateShortRep() { Index = (uint)(Index < 7 ? 9 : 11); } - public bool IsCharState() { return Index < 7; } + + public void UpdateMatch() + { + Index = (uint) (Index < 7 ? 7 : 10); + } + + public void UpdateRep() + { + Index = (uint) (Index < 7 ? 8 : 11); + } + + public void UpdateShortRep() + { + Index = (uint) (Index < 7 ? 9 : 11); + } + + public bool IsCharState() + { + return Index < 7; + } } public const int kNumPosSlotBits = 6; @@ -41,7 +62,7 @@ namespace SharpCompress.Compressor.LZMA len -= kMatchMinLen; if (len < kNumLenToPosStates) return len; - return (uint)(kNumLenToPosStates - 1); + return (uint) (kNumLenToPosStates - 1); } public const int kNumAlignBits = 4; @@ -52,7 +73,7 @@ namespace SharpCompress.Compressor.LZMA public const uint kEndPosModelIndex = 14; public const uint kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; - public const uint kNumFullDistances = 1 << ((int)kEndPosModelIndex / 2); + public const uint kNumFullDistances = 1 << ((int) kEndPosModelIndex/2); public const uint kNumLitPosStatesBitsEncodingMax = 4; public const uint kNumLitContextBitsMax = 8; @@ -67,8 +88,10 @@ namespace SharpCompress.Compressor.LZMA public const int kNumHighLenBits = 8; public const uint kNumLowLenSymbols = 1 << kNumLowLenBits; public const uint kNumMidLenSymbols = 1 << kNumMidLenBits; + public const uint kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + - (1 << kNumHighLenBits); + (1 << kNumHighLenBits); + public const uint kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LzmaDecoder.cs b/SharpCompress/Compressor/LZMA/LzmaDecoder.cs index d4162512..ac2d30c2 100644 --- a/SharpCompress/Compressor/LZMA/LzmaDecoder.cs +++ b/SharpCompress/Compressor/LZMA/LzmaDecoder.cs @@ -5,14 +5,14 @@ namespace SharpCompress.Compressor.LZMA { internal class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream { - class LenDecoder + private class LenDecoder { - BitDecoder m_Choice = new BitDecoder(); - BitDecoder m_Choice2 = new BitDecoder(); - BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; - BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; - BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); - uint m_NumPosStates = 0; + private BitDecoder m_Choice = new BitDecoder(); + private BitDecoder m_Choice2 = new BitDecoder(); + private BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; + private BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; + private BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); + private uint m_NumPosStates = 0; public void Create(uint numPosStates) { @@ -55,21 +55,28 @@ namespace SharpCompress.Compressor.LZMA } } - class LiteralDecoder + private class LiteralDecoder { - struct Decoder2 + private struct Decoder2 { - BitDecoder[] m_Decoders; - public void Create() { m_Decoders = new BitDecoder[0x300]; } - public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } + private BitDecoder[] m_Decoders; + + public void Create() + { + m_Decoders = new BitDecoder[0x300]; + } + + public void Init() + { + for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); + } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) { uint symbol = 1; do - symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); - while (symbol < 0x100); - return (byte)symbol; + symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); while (symbol < 0x100); + return (byte) symbol; } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) @@ -77,7 +84,7 @@ namespace SharpCompress.Compressor.LZMA uint symbol = 1; do { - uint matchBit = (uint)(matchByte >> 7) & 1; + uint matchBit = (uint) (matchByte >> 7) & 1; matchByte <<= 1; uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); symbol = (symbol << 1) | bit; @@ -87,16 +94,15 @@ namespace SharpCompress.Compressor.LZMA symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); break; } - } - while (symbol < 0x100); - return (byte)symbol; + } while (symbol < 0x100); + return (byte) symbol; } } - Decoder2[] m_Coders; - int m_NumPrevBits; - int m_NumPosBits; - uint m_PosMask; + private Decoder2[] m_Coders; + private int m_NumPrevBits; + private int m_NumPosBits; + private uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { @@ -104,9 +110,9 @@ namespace SharpCompress.Compressor.LZMA m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; - m_PosMask = ((uint)1 << numPosBits) - 1; + m_PosMask = ((uint) 1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); + uint numStates = (uint) 1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Decoder2[numStates]; for (uint i = 0; i < numStates; i++) m_Coders[i].Create(); @@ -114,46 +120,52 @@ namespace SharpCompress.Compressor.LZMA public void Init() { - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); + uint numStates = (uint) 1 << (m_NumPrevBits + m_NumPosBits); for (uint i = 0; i < numStates; i++) m_Coders[i].Init(); } - uint GetState(uint pos, byte prevByte) - { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } + private uint GetState(uint pos, byte prevByte) + { + return ((pos & m_PosMask) << m_NumPrevBits) + (uint) (prevByte >> (8 - m_NumPrevBits)); + } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) - { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } + { + return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); + } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) - { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } + { + return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); + } }; - LZ.OutWindow m_OutWindow; + private LZ.OutWindow m_OutWindow; - BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + private BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + private BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; + private BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; + private BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; + private BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; + private BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; - BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; + private BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; + private BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); + private BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); - LenDecoder m_LenDecoder = new LenDecoder(); - LenDecoder m_RepLenDecoder = new LenDecoder(); + private LenDecoder m_LenDecoder = new LenDecoder(); + private LenDecoder m_RepLenDecoder = new LenDecoder(); - LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); + private LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); - int m_DictionarySize; + private int m_DictionarySize; - uint m_PosStateMask; + private uint m_PosStateMask; - Base.State state = new Base.State(); - uint rep0, rep1, rep2, rep3; + private Base.State state = new Base.State(); + private uint rep0, rep1, rep2, rep3; public Decoder() { @@ -162,7 +174,7 @@ namespace SharpCompress.Compressor.LZMA m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } - void CreateDictionary() + private void CreateDictionary() { if (m_DictionarySize < 0) throw new InvalidParamException(); @@ -171,7 +183,7 @@ namespace SharpCompress.Compressor.LZMA m_OutWindow.Create(blockSize); } - void SetLiteralProperties(int lp, int lc) + private void SetLiteralProperties(int lp, int lc) { if (lp > 8) throw new InvalidParamException(); @@ -180,17 +192,17 @@ namespace SharpCompress.Compressor.LZMA m_LiteralDecoder.Create(lp, lc); } - void SetPosBitsProperties(int pb) + private void SetPosBitsProperties(int pb) { if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); - uint numPosStates = (uint)1 << pb; + uint numPosStates = (uint) 1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; } - void Init() + private void Init() { uint i; for (i = 0; i < Base.kNumStates; i++) @@ -226,7 +238,7 @@ namespace SharpCompress.Compressor.LZMA } public void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress) + Int64 inSize, Int64 outSize, ICodeProgress progress) { if (m_OutWindow == null) CreateDictionary(); @@ -259,16 +271,17 @@ namespace SharpCompress.Compressor.LZMA while (outWindow.HasSpace) { - uint posState = (uint)outWindow.Total & m_PosStateMask; + uint posState = (uint) outWindow.Total & m_PosStateMask; if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(rangeDecoder) == 0) { byte b; byte prevByte = outWindow.GetByte(0); if (!state.IsCharState()) b = m_LiteralDecoder.DecodeWithMatchByte(rangeDecoder, - (uint)outWindow.Total, prevByte, outWindow.GetByte((int)rep0)); + (uint) outWindow.Total, prevByte, + outWindow.GetByte((int) rep0)); else - b = m_LiteralDecoder.DecodeNormal(rangeDecoder, (uint)outWindow.Total, prevByte); + b = m_LiteralDecoder.DecodeNormal(rangeDecoder, (uint) outWindow.Total, prevByte); outWindow.PutByte(b); state.UpdateChar(); } @@ -279,10 +292,12 @@ namespace SharpCompress.Compressor.LZMA { if (m_IsRepG0Decoders[state.Index].Decode(rangeDecoder) == 0) { - if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(rangeDecoder) == 0) + if ( + m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode( + rangeDecoder) == 0) { state.UpdateShortRep(); - outWindow.PutByte(outWindow.GetByte((int)rep0)); + outWindow.PutByte(outWindow.GetByte((int) rep0)); continue; } } @@ -320,11 +335,11 @@ namespace SharpCompress.Compressor.LZMA uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(rangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { - int numDirectBits = (int)((posSlot >> 1) - 1); + int numDirectBits = (int) ((posSlot >> 1) - 1); rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, - rep0 - posSlot - 1, rangeDecoder, numDirectBits); + rep0 - posSlot - 1, rangeDecoder, numDirectBits); else { rep0 += (rangeDecoder.DecodeDirectBits( @@ -341,7 +356,7 @@ namespace SharpCompress.Compressor.LZMA return true; throw new DataErrorException(); } - outWindow.CopyBlock((int)rep0, (int)len); + outWindow.CopyBlock((int) rep0, (int) len); } } return false; @@ -351,10 +366,10 @@ namespace SharpCompress.Compressor.LZMA { if (properties.Length < 1) throw new InvalidParamException(); - int lc = properties[0] % 9; - int remainder = properties[0] / 9; - int lp = remainder % 5; - int pb = remainder / 5; + int lc = properties[0]%9; + int remainder = properties[0]/9; + int lp = remainder%5; + int pb = remainder/5; if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); SetLiteralProperties(lp, lc); @@ -364,7 +379,7 @@ namespace SharpCompress.Compressor.LZMA { m_DictionarySize = 0; for (int i = 0; i < 4; i++) - m_DictionarySize += properties[1 + i] << (i * 8); + m_DictionarySize += properties[1 + i] << (i*8); } } @@ -400,4 +415,4 @@ namespace SharpCompress.Compressor.LZMA public override void SetLength(long value) {} */ } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LzmaEncoder.cs b/SharpCompress/Compressor/LZMA/LzmaEncoder.cs index 777b097f..7026764f 100644 --- a/SharpCompress/Compressor/LZMA/LzmaEncoder.cs +++ b/SharpCompress/Compressor/LZMA/LzmaEncoder.cs @@ -3,18 +3,17 @@ using SharpCompress.Compressor.LZMA.RangeCoder; namespace SharpCompress.Compressor.LZMA { - internal class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties { - enum EMatchFinderType + private enum EMatchFinderType { BT2, BT4, }; - const UInt32 kIfinityPrice = 0xFFFFFFF; + private const UInt32 kIfinityPrice = 0xFFFFFFF; - static Byte[] g_FastPos = new Byte[1 << 11]; + private static Byte[] g_FastPos = new Byte[1 << 11]; static Encoder() { @@ -24,35 +23,35 @@ namespace SharpCompress.Compressor.LZMA g_FastPos[1] = 1; for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) { - UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1)); + UInt32 k = ((UInt32) 1 << ((slotFast >> 1) - 1)); for (UInt32 j = 0; j < k; j++, c++) g_FastPos[c] = slotFast; } } - static UInt32 GetPosSlot(UInt32 pos) + private static UInt32 GetPosSlot(UInt32 pos) { if (pos < (1 << 11)) return g_FastPos[pos]; if (pos < (1 << 21)) - return (UInt32)(g_FastPos[pos >> 10] + 20); - return (UInt32)(g_FastPos[pos >> 20] + 40); + return (UInt32) (g_FastPos[pos >> 10] + 20); + return (UInt32) (g_FastPos[pos >> 20] + 40); } - static UInt32 GetPosSlot2(UInt32 pos) + private static UInt32 GetPosSlot2(UInt32 pos) { if (pos < (1 << 17)) - return (UInt32)(g_FastPos[pos >> 6] + 12); + return (UInt32) (g_FastPos[pos >> 6] + 12); if (pos < (1 << 27)) - return (UInt32)(g_FastPos[pos >> 16] + 32); - return (UInt32)(g_FastPos[pos >> 26] + 52); + return (UInt32) (g_FastPos[pos >> 16] + 32); + return (UInt32) (g_FastPos[pos >> 26] + 52); } - Base.State _state = new Base.State(); - Byte _previousByte; - UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; + private Base.State _state = new Base.State(); + private Byte _previousByte; + private UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; - void BaseInit() + private void BaseInit() { _state.Init(); _previousByte = 0; @@ -60,25 +59,31 @@ namespace SharpCompress.Compressor.LZMA _repDistances[i] = 0; } - const int kDefaultDictionaryLogSize = 22; - const UInt32 kNumFastBytesDefault = 0x20; + private const int kDefaultDictionaryLogSize = 22; + private const UInt32 kNumFastBytesDefault = 0x20; - class LiteralEncoder + private class LiteralEncoder { public struct Encoder2 { - BitEncoder[] m_Encoders; + private BitEncoder[] m_Encoders; - public void Create() { m_Encoders = new BitEncoder[0x300]; } + public void Create() + { + m_Encoders = new BitEncoder[0x300]; + } - public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); } + public void Init() + { + for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); + } public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol) { uint context = 1; for (int i = 7; i >= 0; i--) { - uint bit = (uint)((symbol >> i) & 1); + uint bit = (uint) ((symbol >> i) & 1); m_Encoders[context].Encode(rangeEncoder, bit); context = (context << 1) | bit; } @@ -90,11 +95,11 @@ namespace SharpCompress.Compressor.LZMA bool same = true; for (int i = 7; i >= 0; i--) { - uint bit = (uint)((symbol >> i) & 1); + uint bit = (uint) ((symbol >> i) & 1); uint state = context; if (same) { - uint matchBit = (uint)((matchByte >> i) & 1); + uint matchBit = (uint) ((matchByte >> i) & 1); state += ((1 + matchBit) << 8); same = (matchBit == bit); } @@ -112,8 +117,8 @@ namespace SharpCompress.Compressor.LZMA { for (; i >= 0; i--) { - uint matchBit = (uint)(matchByte >> i) & 1; - uint bit = (uint)(symbol >> i) & 1; + uint matchBit = (uint) (matchByte >> i) & 1; + uint bit = (uint) (symbol >> i) & 1; price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit); context = (context << 1) | bit; if (matchBit != bit) @@ -125,7 +130,7 @@ namespace SharpCompress.Compressor.LZMA } for (; i >= 0; i--) { - uint bit = (uint)(symbol >> i) & 1; + uint bit = (uint) (symbol >> i) & 1; price += m_Encoders[context].GetPrice(bit); context = (context << 1) | bit; } @@ -133,19 +138,19 @@ namespace SharpCompress.Compressor.LZMA } } - Encoder2[] m_Coders; - int m_NumPrevBits; - int m_NumPosBits; - uint m_PosMask; + private Encoder2[] m_Coders; + private int m_NumPrevBits; + private int m_NumPosBits; + private uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; - m_PosMask = ((uint)1 << numPosBits) - 1; + m_PosMask = ((uint) 1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); + uint numStates = (uint) 1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Encoder2[numStates]; for (uint i = 0; i < numStates; i++) m_Coders[i].Create(); @@ -153,22 +158,24 @@ namespace SharpCompress.Compressor.LZMA public void Init() { - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); + uint numStates = (uint) 1 << (m_NumPrevBits + m_NumPosBits); for (uint i = 0; i < numStates; i++) m_Coders[i].Init(); } public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte) - { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; } + { + return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint) (prevByte >> (8 - m_NumPrevBits))]; + } } - class LenEncoder + private class LenEncoder { - RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder(); - RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder(); - RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; - RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; - RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits); + private RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder(); + private RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder(); + private RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; + private RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; + private RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits); public LenEncoder() { @@ -239,24 +246,27 @@ namespace SharpCompress.Compressor.LZMA } }; - const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; + private const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; - class LenPriceTableEncoder : LenEncoder + private class LenPriceTableEncoder : LenEncoder { - UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; - UInt32 _tableSize; - UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; + private UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; + private UInt32 _tableSize; + private UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; - public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; } + public void SetTableSize(UInt32 tableSize) + { + _tableSize = tableSize; + } public UInt32 GetPrice(UInt32 symbol, UInt32 posState) { - return _prices[posState * Base.kNumLenSymbols + symbol]; + return _prices[posState*Base.kNumLenSymbols + symbol]; } - void UpdateTable(UInt32 posState) + private void UpdateTable(UInt32 posState) { - SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); + SetPrices(posState, _tableSize, _prices, posState*Base.kNumLenSymbols); _counters[posState] = _tableSize; } @@ -274,8 +284,9 @@ namespace SharpCompress.Compressor.LZMA } } - const UInt32 kNumOpts = 1 << 12; - class Optimal + private const UInt32 kNumOpts = 1 << 12; + + private class Optimal { public Base.State State; @@ -294,71 +305,92 @@ namespace SharpCompress.Compressor.LZMA public UInt32 Backs2; public UInt32 Backs3; - public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; } - public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } - public bool IsShortRep() { return (BackPrev == 0); } + public void MakeAsChar() + { + BackPrev = 0xFFFFFFFF; + Prev1IsChar = false; + } + + public void MakeAsShortRep() + { + BackPrev = 0; + ; + Prev1IsChar = false; + } + + public bool IsShortRep() + { + return (BackPrev == 0); + } }; - Optimal[] _optimum = new Optimal[kNumOpts]; - LZ.BinTree _matchFinder = null; - RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); - RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + private Optimal[] _optimum = new Optimal[kNumOpts]; + private LZ.BinTree _matchFinder = null; + private RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); - RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates]; + private RangeCoder.BitEncoder[] _isMatch = + new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits); + private RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates]; + private RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates]; + private RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates]; + private RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates]; - LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); - LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); + private RangeCoder.BitEncoder[] _isRep0Long = + new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - LiteralEncoder _literalEncoder = new LiteralEncoder(); + private RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates]; - UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2]; + private RangeCoder.BitEncoder[] _posEncoders = + new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - UInt32 _numFastBytes = kNumFastBytesDefault; - UInt32 _longestMatchLength; - UInt32 _numDistancePairs; + private RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits); - UInt32 _additionalOffset; + private LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); + private LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); - UInt32 _optimumEndIndex; - UInt32 _optimumCurrentIndex; + private LiteralEncoder _literalEncoder = new LiteralEncoder(); - bool _longestMatchWasFound; + private UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen*2 + 2]; - UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; - UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; - UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; - UInt32 _alignPriceCount; + private UInt32 _numFastBytes = kNumFastBytesDefault; + private UInt32 _longestMatchLength; + private UInt32 _numDistancePairs; - UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2); + private UInt32 _additionalOffset; - int _posStateBits = 2; - UInt32 _posStateMask = (4 - 1); - int _numLiteralPosStateBits = 0; - int _numLiteralContextBits = 3; + private UInt32 _optimumEndIndex; + private UInt32 _optimumCurrentIndex; - UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); - UInt32 _dictionarySizePrev = 0xFFFFFFFF; - UInt32 _numFastBytesPrev = 0xFFFFFFFF; + private bool _longestMatchWasFound; - Int64 nowPos64; - bool _finished; - System.IO.Stream _inStream; + private UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; + private UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; + private UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; + private UInt32 _alignPriceCount; - EMatchFinderType _matchFinderType = EMatchFinderType.BT4; - bool _writeEndMark = false; + private UInt32 _distTableSize = (kDefaultDictionaryLogSize*2); - bool _needReleaseMFStream; - bool _processingMode; + private int _posStateBits = 2; + private UInt32 _posStateMask = (4 - 1); + private int _numLiteralPosStateBits = 0; + private int _numLiteralContextBits = 3; - void Create() + private UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); + private UInt32 _dictionarySizePrev = 0xFFFFFFFF; + private UInt32 _numFastBytesPrev = 0xFFFFFFFF; + + private Int64 nowPos64; + private bool _finished; + private System.IO.Stream _inStream; + + private EMatchFinderType _matchFinderType = EMatchFinderType.BT4; + private bool _writeEndMark = false; + + private bool _needReleaseMFStream; + private bool _processingMode; + + private void Create() { if (_matchFinder == null) { @@ -386,12 +418,12 @@ namespace SharpCompress.Compressor.LZMA _posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits); } - void SetWriteEndMarkerMode(bool writeEndMarker) + private void SetWriteEndMarkerMode(bool writeEndMarker) { _writeEndMark = writeEndMarker; } - void Init() + private void Init() { BaseInit(); _rangeEncoder.Init(); @@ -416,8 +448,8 @@ namespace SharpCompress.Compressor.LZMA for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) _posEncoders[i].Init(); - _lenEncoder.Init((UInt32)1 << _posStateBits); - _repMatchLenEncoder.Init((UInt32)1 << _posStateBits); + _lenEncoder.Init((UInt32) 1 << _posStateBits); + _repMatchLenEncoder.Init((UInt32) 1 << _posStateBits); _posAlignEncoder.Init(); @@ -427,7 +459,7 @@ namespace SharpCompress.Compressor.LZMA _additionalOffset = 0; } - void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs) + private void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs) { lenRes = 0; numDistancePairs = _matchFinder.GetMatches(_matchDistances); @@ -435,14 +467,14 @@ namespace SharpCompress.Compressor.LZMA { lenRes = _matchDistances[numDistancePairs - 2]; if (lenRes == _numFastBytes) - lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1], - Base.kMatchMaxLen - lenRes); + lenRes += _matchFinder.GetMatchLen((int) lenRes - 1, _matchDistances[numDistancePairs - 1], + Base.kMatchMaxLen - lenRes); } _additionalOffset++; } - void MovePos(UInt32 num) + private void MovePos(UInt32 num) { if (num > 0) { @@ -451,13 +483,13 @@ namespace SharpCompress.Compressor.LZMA } } - UInt32 GetRepLen1Price(Base.State state, UInt32 posState) + private UInt32 GetRepLen1Price(Base.State state, UInt32 posState) { return _isRepG0[state.Index].GetPrice0() + - _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0(); + _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0(); } - UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState) + private UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState) { UInt32 price; if (repIndex == 0) @@ -479,25 +511,25 @@ namespace SharpCompress.Compressor.LZMA return price; } - UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState) + private UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState) { UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); return price + GetPureRepPrice(repIndex, state, posState); } - UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) + private UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) { UInt32 price; UInt32 lenToPosState = Base.GetLenToPosState(len); if (pos < Base.kNumFullDistances) - price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; + price = _distancesPrices[(lenToPosState*Base.kNumFullDistances) + pos]; else price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + - _alignPrices[pos & Base.kAlignMask]; + _alignPrices[pos & Base.kAlignMask]; return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); } - UInt32 Backward(out UInt32 backRes, UInt32 cur) + private UInt32 Backward(out UInt32 backRes, UInt32 cur) { _optimumEndIndex = cur; UInt32 posMem = _optimum[cur].PosPrev; @@ -524,18 +556,17 @@ namespace SharpCompress.Compressor.LZMA _optimum[posPrev].BackPrev = backCur; _optimum[posPrev].PosPrev = cur; cur = posPrev; - } - while (cur > 0); + } while (cur > 0); backRes = _optimum[0].BackPrev; _optimumCurrentIndex = _optimum[0].PosPrev; return _optimumCurrentIndex; } - UInt32[] reps = new UInt32[Base.kNumRepDistances]; - UInt32[] repLens = new UInt32[Base.kNumRepDistances]; + private UInt32[] reps = new UInt32[Base.kNumRepDistances]; + private UInt32[] repLens = new UInt32[Base.kNumRepDistances]; - UInt32 GetOptimum(UInt32 position, out UInt32 backRes) + private UInt32 GetOptimum(UInt32 position, out UInt32 backRes) { if (_optimumEndIndex != _optimumCurrentIndex) { @@ -592,11 +623,11 @@ namespace SharpCompress.Compressor.LZMA } Byte currentByte = _matchFinder.GetIndexByte(0 - 1); - Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1)); + Byte matchByte = _matchFinder.GetIndexByte((Int32) (0 - _repDistances[0] - 1 - 1)); if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) { - backRes = (UInt32)0xFFFFFFFF; + backRes = (UInt32) 0xFFFFFFFF; return 1; } @@ -605,7 +636,8 @@ namespace SharpCompress.Compressor.LZMA UInt32 posState = (position & _posStateMask); _optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + - _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte); + _literalEncoder.GetSubCoder(position, _previousByte) + .GetPrice(!_state.IsCharState(), matchByte, currentByte); _optimum[1].MakeAsChar(); UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); @@ -638,8 +670,7 @@ namespace SharpCompress.Compressor.LZMA UInt32 len = lenEnd; do - _optimum[len--].Price = kIfinityPrice; - while (len >= 2); + _optimum[len--].Price = kIfinityPrice; while (len >= 2); for (i = 0; i < Base.kNumRepDistances; i++) { @@ -658,8 +689,7 @@ namespace SharpCompress.Compressor.LZMA optimum.BackPrev = i; optimum.Prev1IsChar = false; } - } - while (--repLen >= 2); + } while (--repLen >= 2); } UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); @@ -670,7 +700,7 @@ namespace SharpCompress.Compressor.LZMA UInt32 offs = 0; while (len > _matchDistances[offs]) offs += 2; - for (; ; len++) + for (;; len++) { UInt32 distance = _matchDistances[offs + 1]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); @@ -799,14 +829,14 @@ namespace SharpCompress.Compressor.LZMA UInt32 curPrice = _optimum[cur].Price; currentByte = _matchFinder.GetIndexByte(0 - 1); - matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1)); + matchByte = _matchFinder.GetIndexByte((Int32) (0 - reps[0] - 1 - 1)); posState = (position & _posStateMask); UInt32 curAnd1Price = curPrice + - _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + - _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). - GetPrice(!state.IsCharState(), matchByte, currentByte); + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + + _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). + GetPrice(!state.IsCharState(), matchByte, currentByte); Optimal nextOptimum = _optimum[cur + 1]; @@ -854,8 +884,9 @@ namespace SharpCompress.Compressor.LZMA state2.UpdateChar(); UInt32 posStateNext = (position + 1) & _posStateMask; UInt32 nextRepMatchPrice = curAnd1Price + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() + - _isRep[state2.Index].GetPrice1(); + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext] + .GetPrice1() + + _isRep[state2.Index].GetPrice1(); { UInt32 offset = cur + 1 + lenTest2; while (lenEnd < offset) @@ -896,8 +927,7 @@ namespace SharpCompress.Compressor.LZMA optimum.BackPrev = repIndex; optimum.Prev1IsChar = false; } - } - while (--lenTest >= 2); + } while (--lenTest >= 2); lenTest = lenTestTemp; if (repIndex == 0) @@ -907,22 +937,27 @@ namespace SharpCompress.Compressor.LZMA if (lenTest < numAvailableBytesFull) { UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t); + UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32) lenTest, reps[repIndex], t); if (lenTest2 >= 2) { Base.State state2 = state; state2.UpdateRep(); UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = - repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + - _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true, - _matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))), - _matchFinder.GetIndexByte((Int32)lenTest - 1)); + repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + + _literalEncoder.GetSubCoder(position + lenTest, + _matchFinder.GetIndexByte((Int32) lenTest - 1 - 1)) + .GetPrice(true, + _matchFinder.GetIndexByte( + (Int32) + ((Int32) lenTest - 1 - (Int32) (reps[repIndex] + 1))), + _matchFinder.GetIndexByte((Int32) lenTest - 1)); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; - UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); + UInt32 nextMatchPrice = curAndLenCharPrice + + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext] + .GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); // for(; lenTest2 >= 2; lenTest2--) @@ -930,7 +965,8 @@ namespace SharpCompress.Compressor.LZMA UInt32 offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); + UInt32 curAndLenPrice = nextRepMatchPrice + + GetRepPrice(0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { @@ -964,7 +1000,7 @@ namespace SharpCompress.Compressor.LZMA while (startLen > _matchDistances[offs]) offs += 2; - for (UInt32 lenTest = startLen; ; lenTest++) + for (UInt32 lenTest = startLen;; lenTest++) { UInt32 curBack = _matchDistances[offs + 1]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); @@ -982,22 +1018,32 @@ namespace SharpCompress.Compressor.LZMA if (lenTest < numAvailableBytesFull) { UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t); + UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32) lenTest, curBack, t); if (lenTest2 >= 2) { Base.State state2 = state; state2.UpdateMatch(); UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = curAndLenPrice + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + - _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)). - GetPrice(true, - _matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1), - _matchFinder.GetIndexByte((Int32)lenTest - 1)); + _isMatch[ + (state2.Index << Base.kNumPosStatesBitsMax) + + posStateNext].GetPrice0() + + _literalEncoder.GetSubCoder(position + lenTest, + _matchFinder.GetIndexByte( + (Int32) lenTest - 1 - 1)) + . + GetPrice(true, + _matchFinder.GetIndexByte( + (Int32) lenTest - + (Int32) (curBack + 1) - 1), + _matchFinder.GetIndexByte( + (Int32) lenTest - 1)); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; - UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); + UInt32 nextMatchPrice = curAndLenCharPrice + + _isMatch[ + (state2.Index << Base.kNumPosStatesBitsMax) + + posStateNext].GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); UInt32 offset = lenTest + 1 + lenTest2; @@ -1026,13 +1072,13 @@ namespace SharpCompress.Compressor.LZMA } } - bool ChangePair(UInt32 smallDist, UInt32 bigDist) + private bool ChangePair(UInt32 smallDist, UInt32 bigDist) { const int kDif = 7; - return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif)); + return (smallDist < ((UInt32) (1) << (32 - kDif)) && bigDist >= (smallDist << kDif)); } - void WriteEndMarker(UInt32 posState) + private void WriteEndMarker(UInt32 posState) { if (!_writeEndMark) return; @@ -1046,12 +1092,12 @@ namespace SharpCompress.Compressor.LZMA UInt32 lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); int footerBits = 30; - UInt32 posReduced = (((UInt32)1) << footerBits) - 1; + UInt32 posReduced = (((UInt32) 1) << footerBits) - 1; _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); } - void Flush(UInt32 nowPos) + private void Flush(UInt32 nowPos) { ReleaseMFStream(); WriteEndMarker(nowPos & _posStateMask); @@ -1094,16 +1140,16 @@ namespace SharpCompress.Compressor.LZMA } if (_matchFinder.GetNumAvailableBytes() == 0) { - Flush((UInt32)nowPos64); + Flush((UInt32) nowPos64); return; } UInt32 len, numDistancePairs; // it's not used ReadMatchDistances(out len, out numDistancePairs); - UInt32 posState = (UInt32)(nowPos64) & _posStateMask; + UInt32 posState = (UInt32) (nowPos64) & _posStateMask; _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0); _state.UpdateChar(); - Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); - _literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); + Byte curByte = _matchFinder.GetIndexByte((Int32) (0 - _additionalOffset)); + _literalEncoder.GetSubCoder((UInt32) (nowPos64), _previousByte).Encode(_rangeEncoder, curByte); _previousByte = curByte; _additionalOffset--; nowPos64++; @@ -1115,7 +1161,7 @@ namespace SharpCompress.Compressor.LZMA } if (_matchFinder.GetNumAvailableBytes() == 0) { - Flush((UInt32)nowPos64); + Flush((UInt32) nowPos64); return; } while (true) @@ -1127,18 +1173,19 @@ namespace SharpCompress.Compressor.LZMA } UInt32 pos; - UInt32 len = GetOptimum((UInt32)nowPos64, out pos); + UInt32 len = GetOptimum((UInt32) nowPos64, out pos); - UInt32 posState = ((UInt32)nowPos64) & _posStateMask; + UInt32 posState = ((UInt32) nowPos64) & _posStateMask; UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState; if (len == 1 && pos == 0xFFFFFFFF) { _isMatch[complexState].Encode(_rangeEncoder, 0); - Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); - LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte); + Byte curByte = _matchFinder.GetIndexByte((Int32) (0 - _additionalOffset)); + LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32) nowPos64, _previousByte); if (!_state.IsCharState()) { - Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset)); + Byte matchByte = + _matchFinder.GetIndexByte((Int32) (0 - _repDistances[0] - 1 - _additionalOffset)); subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); } else @@ -1198,16 +1245,18 @@ namespace SharpCompress.Compressor.LZMA if (posSlot >= Base.kStartPosModelIndex) { - int footerBits = (int)((posSlot >> 1) - 1); + int footerBits = (int) ((posSlot >> 1) - 1); UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); UInt32 posReduced = pos - baseVal; if (posSlot < Base.kEndPosModelIndex) RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders, - baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); + baseVal - posSlot - 1, _rangeEncoder, footerBits, + posReduced); else { - _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); + _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, + footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); _alignPriceCount++; } @@ -1218,7 +1267,7 @@ namespace SharpCompress.Compressor.LZMA _repDistances[0] = distance; _matchPriceCount++; } - _previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset)); + _previousByte = _matchFinder.GetIndexByte((Int32) (len - 1 - _additionalOffset)); } _additionalOffset -= len; nowPos64 += len; @@ -1238,7 +1287,7 @@ namespace SharpCompress.Compressor.LZMA } if (_matchFinder.GetNumAvailableBytes() == 0) { - Flush((UInt32)nowPos64); + Flush((UInt32) nowPos64); return; } @@ -1252,7 +1301,7 @@ namespace SharpCompress.Compressor.LZMA } } - void ReleaseMFStream() + private void ReleaseMFStream() { if (_matchFinder != null && _needReleaseMFStream) { @@ -1261,17 +1310,24 @@ namespace SharpCompress.Compressor.LZMA } } - void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); } - void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } + private void SetOutStream(System.IO.Stream outStream) + { + _rangeEncoder.SetStream(outStream); + } - void ReleaseStreams() + private void ReleaseOutStream() + { + _rangeEncoder.ReleaseStream(); + } + + private void ReleaseStreams() { ReleaseMFStream(); ReleaseOutStream(); } public void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize) + Int64 inSize, Int64 outSize) { _inStream = inStream; _finished = false; @@ -1287,16 +1343,16 @@ namespace SharpCompress.Compressor.LZMA } _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); - _lenEncoder.UpdateTables((UInt32)1 << _posStateBits); + _lenEncoder.UpdateTables((UInt32) 1 << _posStateBits); _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); - _repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits); + _repMatchLenEncoder.UpdateTables((UInt32) 1 << _posStateBits); nowPos64 = 0; } public void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress) + Int64 inSize, Int64 outSize, ICodeProgress progress) { _needReleaseMFStream = false; _processingMode = false; @@ -1351,7 +1407,7 @@ namespace SharpCompress.Compressor.LZMA { if (nowPos64 > 0) throw new InvalidOperationException(); - _trainSize = (uint)trainStream.Length; + _trainSize = (uint) trainStream.Length; if (_trainSize > 0) { _matchFinder.SetStream(trainStream); @@ -1363,29 +1419,29 @@ namespace SharpCompress.Compressor.LZMA } } - const int kPropSize = 5; - Byte[] properties = new Byte[kPropSize]; + private const int kPropSize = 5; + private Byte[] properties = new Byte[kPropSize]; public void WriteCoderProperties(System.IO.Stream outStream) { - properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); + properties[0] = (Byte) ((_posStateBits*5 + _numLiteralPosStateBits)*9 + _numLiteralContextBits); for (int i = 0; i < 4; i++) - properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF); + properties[1 + i] = (Byte) ((_dictionarySize >> (8*i)) & 0xFF); outStream.Write(properties, 0, kPropSize); } - UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; - UInt32 _matchPriceCount; + private UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; + private UInt32 _matchPriceCount; - void FillDistancesPrices() + private void FillDistancesPrices() { for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) { UInt32 posSlot = GetPosSlot(i); - int footerBits = (int)((posSlot >> 1) - 1); + int footerBits = (int) ((posSlot >> 1) - 1); UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, - baseVal - posSlot - 1, footerBits, i - baseVal); + baseVal - posSlot - 1, footerBits, i - baseVal); } for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) @@ -1397,9 +1453,10 @@ namespace SharpCompress.Compressor.LZMA for (posSlot = 0; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) - _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits); + _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << + RangeCoder.BitEncoder.kNumBitPriceShiftBits); - UInt32 st2 = lenToPosState * Base.kNumFullDistances; + UInt32 st2 = lenToPosState*Base.kNumFullDistances; UInt32 i; for (i = 0; i < Base.kStartPosModelIndex; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + i]; @@ -1409,7 +1466,7 @@ namespace SharpCompress.Compressor.LZMA _matchPriceCount = 0; } - void FillAlignPrices() + private void FillAlignPrices() { for (UInt32 i = 0; i < Base.kAlignTableSize; i++) _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); @@ -1417,13 +1474,13 @@ namespace SharpCompress.Compressor.LZMA } - static string[] kMatchFinderIDs = - { - "BT2", - "BT4", - }; + private static string[] kMatchFinderIDs = + { + "BT2", + "BT4", + }; - static int FindMatchFinder(string s) + private static int FindMatchFinder(string s) { for (int m = 0; m < kMatchFinderIDs.Length; m++) if (s == kMatchFinderIDs[m]) @@ -1442,10 +1499,10 @@ namespace SharpCompress.Compressor.LZMA { if (!(prop is Int32)) throw new InvalidParamException(); - Int32 numFastBytes = (Int32)prop; + Int32 numFastBytes = (Int32) prop; if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) throw new InvalidParamException(); - _numFastBytes = (UInt32)numFastBytes; + _numFastBytes = (UInt32) numFastBytes; break; } case CoderPropID.Algorithm: @@ -1464,10 +1521,10 @@ namespace SharpCompress.Compressor.LZMA if (!(prop is String)) throw new InvalidParamException(); EMatchFinderType matchFinderIndexPrev = _matchFinderType; - int m = FindMatchFinder(((string)prop).ToUpper()); + int m = FindMatchFinder(((string) prop).ToUpper()); if (m < 0) throw new InvalidParamException(); - _matchFinderType = (EMatchFinderType)m; + _matchFinderType = (EMatchFinderType) m; if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) { _dictionarySizePrev = 0xFFFFFFFF; @@ -1479,55 +1536,57 @@ namespace SharpCompress.Compressor.LZMA { const int kDicLogSizeMaxCompress = 30; if (!(prop is Int32)) - throw new InvalidParamException(); ; - Int32 dictionarySize = (Int32)prop; - if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) || - dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress)) throw new InvalidParamException(); - _dictionarySize = (UInt32)dictionarySize; + ; + Int32 dictionarySize = (Int32) prop; + if (dictionarySize < (UInt32) (1 << Base.kDicLogSizeMin) || + dictionarySize > (UInt32) (1 << kDicLogSizeMaxCompress)) + throw new InvalidParamException(); + _dictionarySize = (UInt32) dictionarySize; int dicLogSize; - for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) - if (dictionarySize <= ((UInt32)(1) << dicLogSize)) + for (dicLogSize = 0; dicLogSize < (UInt32) kDicLogSizeMaxCompress; dicLogSize++) + if (dictionarySize <= ((UInt32) (1) << dicLogSize)) break; - _distTableSize = (UInt32)dicLogSize * 2; + _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.kNumPosStatesBitsEncodingMax) + Int32 v = (Int32) prop; + if (v < 0 || v > (UInt32) Base.kNumPosStatesBitsEncodingMax) throw new InvalidParamException(); - _posStateBits = (int)v; - _posStateMask = (((UInt32)1) << (int)_posStateBits) - 1; + _posStateBits = (int) v; + _posStateMask = (((UInt32) 1) << (int) _posStateBits) - 1; break; } case CoderPropID.LitPosBits: { if (!(prop is Int32)) throw new InvalidParamException(); - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax) + Int32 v = (Int32) prop; + if (v < 0 || v > (UInt32) Base.kNumLitPosStatesBitsEncodingMax) throw new InvalidParamException(); - _numLiteralPosStateBits = (int)v; + _numLiteralPosStateBits = (int) v; break; } case CoderPropID.LitContextBits: { if (!(prop is Int32)) throw new InvalidParamException(); - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax) - throw new InvalidParamException(); ; - _numLiteralContextBits = (int)v; + Int32 v = (Int32) prop; + if (v < 0 || v > (UInt32) Base.kNumLitContextBitsMax) + throw new InvalidParamException(); + ; + _numLiteralContextBits = (int) v; break; } case CoderPropID.EndMarker: { if (!(prop is Boolean)) throw new InvalidParamException(); - SetWriteEndMarkerMode((Boolean)prop); + SetWriteEndMarkerMode((Boolean) prop); break; } default: @@ -1536,11 +1595,11 @@ namespace SharpCompress.Compressor.LZMA } } - uint _trainSize = 0; + private uint _trainSize = 0; + public void SetTrainSize(uint trainSize) { _trainSize = trainSize; } - } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LzmaEncoderProperties.cs b/SharpCompress/Compressor/LZMA/LzmaEncoderProperties.cs index 61c096de..07ca6bd2 100644 --- a/SharpCompress/Compressor/LZMA/LzmaEncoderProperties.cs +++ b/SharpCompress/Compressor/LZMA/LzmaEncoderProperties.cs @@ -29,27 +29,27 @@ string mf = "bt4"; propIDs = new CoderPropID[] - { - CoderPropID.DictionarySize, - CoderPropID.PosStateBits, - CoderPropID.LitContextBits, - CoderPropID.LitPosBits, - CoderPropID.Algorithm, - CoderPropID.NumFastBytes, - CoderPropID.MatchFinder, - CoderPropID.EndMarker - }; + { + CoderPropID.DictionarySize, + CoderPropID.PosStateBits, + CoderPropID.LitContextBits, + CoderPropID.LitPosBits, + CoderPropID.Algorithm, + CoderPropID.NumFastBytes, + CoderPropID.MatchFinder, + CoderPropID.EndMarker + }; properties = new object[] - { - dictionary, - posStateBits, - litContextBits, - litPosBits, - algorithm, - numFastBytes, - mf, - eos - }; + { + dictionary, + posStateBits, + litContextBits, + litPosBits, + algorithm, + numFastBytes, + mf, + eos + }; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/LzmaStream.cs b/SharpCompress/Compressor/LZMA/LzmaStream.cs index f9a8aeaf..21d3929d 100644 --- a/SharpCompress/Compressor/LZMA/LzmaStream.cs +++ b/SharpCompress/Compressor/LZMA/LzmaStream.cs @@ -46,7 +46,7 @@ namespace SharpCompress.Compressor.LZMA } public LzmaStream(byte[] properties, Stream inputStream, long inputSize, long outputSize, - Stream presetDictionary, bool isLZMA2) + Stream presetDictionary, bool isLZMA2) { this.inputStream = inputStream; this.inputSize = inputSize; @@ -147,14 +147,8 @@ namespace SharpCompress.Compressor.LZMA public override long Position { - get - { - return position; - } - set - { - throw new NotImplementedException(); - } + get { return position; } + set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) @@ -185,7 +179,7 @@ namespace SharpCompress.Compressor.LZMA inputPosition += outWindow.CopyStream(inputStream, toProcess); } else if (decoder.Code(dictionarySize, outWindow, rangeDecoder) - && outputSize < 0) + && outputSize < 0) { availableBytes = outWindow.AvailableBytes; } @@ -296,10 +290,7 @@ namespace SharpCompress.Compressor.LZMA public byte[] Properties { - get - { - return props; - } + get { return props; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoder.cs b/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoder.cs index c82ffe4f..bac7eb63 100644 --- a/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoder.cs +++ b/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoder.cs @@ -6,12 +6,12 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { public const uint kTopValue = (1 << 24); - System.IO.Stream Stream; + private System.IO.Stream Stream; public UInt64 Low; public uint Range; - uint _cacheSize; - byte _cache; + private uint _cacheSize; + private byte _cache; //long StartPosition; @@ -53,7 +53,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void Encode(uint start, uint size, uint total) { - Low += start * (Range /= total); + Low += start*(Range /= total); Range *= size; while (Range < kTopValue) { @@ -64,19 +64,18 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void ShiftLow() { - if ((uint)Low < (uint)0xFF000000 || (uint)(Low >> 32) == 1) + if ((uint) Low < (uint) 0xFF000000 || (uint) (Low >> 32) == 1) { byte temp = _cache; do { - Stream.WriteByte((byte)(temp + (Low >> 32))); + Stream.WriteByte((byte) (temp + (Low >> 32))); temp = 0xFF; - } - while (--_cacheSize != 0); - _cache = (byte)(((uint)Low) >> 24); + } while (--_cacheSize != 0); + _cache = (byte) (((uint) Low) >> 24); } _cacheSize++; - Low = ((uint)Low) << 8; + Low = ((uint) Low) << 8; } public void EncodeDirectBits(uint v, int numTotalBits) @@ -96,7 +95,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void EncodeBit(uint size0, int numTotalBits, uint symbol) { - uint newBound = (Range >> numTotalBits) * size0; + uint newBound = (Range >> numTotalBits)*size0; if (symbol == 0) Range = newBound; else @@ -136,7 +135,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder Code = 0; Range = 0xFFFFFFFF; for (int i = 0; i < 5; i++) - Code = (Code << 8) | (byte)Stream.ReadByte(); + Code = (Code << 8) | (byte) Stream.ReadByte(); Total = 5; } @@ -155,7 +154,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { while (Range < kTopValue) { - Code = (Code << 8) | (byte)Stream.ReadByte(); + Code = (Code << 8) | (byte) Stream.ReadByte(); Range <<= 8; Total++; } @@ -165,7 +164,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { if (Range < kTopValue) { - Code = (Code << 8) | (byte)Stream.ReadByte(); + Code = (Code << 8) | (byte) Stream.ReadByte(); Range <<= 8; Total++; } @@ -173,12 +172,12 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public uint GetThreshold(uint total) { - return Code / (Range /= total); + return Code/(Range /= total); } public void Decode(uint start, uint size) { - Code -= start * Range; + Code -= start*Range; Range *= size; Normalize(); } @@ -205,7 +204,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder if (range < kTopValue) { - code = (code << 8) | (byte)Stream.ReadByte(); + code = (code << 8) | (byte) Stream.ReadByte(); range <<= 8; Total++; } @@ -217,7 +216,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public uint DecodeBit(uint size0, int numTotalBits) { - uint newBound = (Range >> numTotalBits) * size0; + uint newBound = (Range >> numTotalBits)*size0; uint symbol; if (Code < newBound) { @@ -236,12 +235,9 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public bool IsFinished { - get - { - return Code == 0; - } + get { return Code == 0; } } // ulong GetProcessedSize() {return Stream.GetProcessedSize(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBit.cs b/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBit.cs index 25f812f1..24767224 100644 --- a/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBit.cs +++ b/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBit.cs @@ -6,13 +6,16 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { public const int kNumBitModelTotalBits = 11; public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - const int kNumMoveBits = 5; - const int kNumMoveReducingBits = 2; + private const int kNumMoveBits = 5; + private const int kNumMoveReducingBits = 2; public const int kNumBitPriceShiftBits = 6; - uint Prob; + private uint Prob; - public void Init() { Prob = kBitModelTotal >> 1; } + public void Init() + { + Prob = kBitModelTotal >> 1; + } public void UpdateModel(uint symbol) { @@ -26,7 +29,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { // encoder.EncodeBit(Prob, kNumBitModelTotalBits, symbol); // UpdateModel(symbol); - uint newBound = (encoder.Range >> kNumBitModelTotalBits) * Prob; + uint newBound = (encoder.Range >> kNumBitModelTotalBits)*Prob; if (symbol == 0) { encoder.Range = newBound; @@ -52,29 +55,37 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); for (int i = kNumBits - 1; i >= 0; i--) { - UInt32 start = (UInt32)1 << (kNumBits - i - 1); - UInt32 end = (UInt32)1 << (kNumBits - i); + UInt32 start = (UInt32) 1 << (kNumBits - i - 1); + UInt32 end = (UInt32) 1 << (kNumBits - i); for (UInt32 j = start; j < end; j++) - ProbPrices[j] = ((UInt32)i << kNumBitPriceShiftBits) + - (((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1)); + ProbPrices[j] = ((UInt32) i << kNumBitPriceShiftBits) + + (((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1)); } } public uint GetPrice(uint symbol) { - return ProbPrices[(((Prob - symbol) ^ ((-(int)symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; + return ProbPrices[(((Prob - symbol) ^ ((-(int) symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; + } + + public uint GetPrice0() + { + return ProbPrices[Prob >> kNumMoveReducingBits]; + } + + public uint GetPrice1() + { + return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; } - public uint GetPrice0() { return ProbPrices[Prob >> kNumMoveReducingBits]; } - public uint GetPrice1() { return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; } } internal struct BitDecoder { public const int kNumBitModelTotalBits = 11; public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - const int kNumMoveBits = 5; + private const int kNumMoveBits = 5; - uint Prob; + private uint Prob; public void UpdateModel(int numMoveBits, uint symbol) { @@ -84,18 +95,21 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder Prob -= (Prob) >> numMoveBits; } - public void Init() { Prob = kBitModelTotal >> 1; } + public void Init() + { + Prob = kBitModelTotal >> 1; + } public uint Decode(RangeCoder.Decoder rangeDecoder) { - uint newBound = (uint)(rangeDecoder.Range >> kNumBitModelTotalBits) * (uint)Prob; + uint newBound = (uint) (rangeDecoder.Range >> kNumBitModelTotalBits)*(uint) Prob; if (rangeDecoder.Code < newBound) { rangeDecoder.Range = newBound; Prob += (kBitModelTotal - Prob) >> kNumMoveBits; if (rangeDecoder.Range < Decoder.kTopValue) { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); + rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte) rangeDecoder.Stream.ReadByte(); rangeDecoder.Range <<= 8; rangeDecoder.Total++; } @@ -108,7 +122,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder Prob -= (Prob) >> kNumMoveBits; if (rangeDecoder.Range < Decoder.kTopValue) { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); + rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte) rangeDecoder.Stream.ReadByte(); rangeDecoder.Range <<= 8; rangeDecoder.Total++; } @@ -116,4 +130,4 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBitTree.cs b/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBitTree.cs index 41e0de7b..b30dab7e 100644 --- a/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBitTree.cs +++ b/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBitTree.cs @@ -4,8 +4,8 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { internal struct BitTreeEncoder { - BitEncoder[] Models; - int NumBitLevels; + private BitEncoder[] Models; + private int NumBitLevels; public BitTreeEncoder(int numBitLevels) { @@ -22,7 +22,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void Encode(Encoder rangeEncoder, UInt32 symbol) { UInt32 m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; ) + for (int bitIndex = NumBitLevels; bitIndex > 0;) { bitIndex--; UInt32 bit = (symbol >> bitIndex) & 1; @@ -47,7 +47,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { UInt32 price = 0; UInt32 m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; ) + for (int bitIndex = NumBitLevels; bitIndex > 0;) { bitIndex--; UInt32 bit = (symbol >> bitIndex) & 1; @@ -72,7 +72,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder } public static UInt32 ReverseGetPrice(BitEncoder[] Models, UInt32 startIndex, - int NumBitLevels, UInt32 symbol) + int NumBitLevels, UInt32 symbol) { UInt32 price = 0; UInt32 m = 1; @@ -87,7 +87,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder } public static void ReverseEncode(BitEncoder[] Models, UInt32 startIndex, - Encoder rangeEncoder, int NumBitLevels, UInt32 symbol) + Encoder rangeEncoder, int NumBitLevels, UInt32 symbol) { UInt32 m = 1; for (int i = 0; i < NumBitLevels; i++) @@ -102,8 +102,8 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder internal struct BitTreeDecoder { - BitDecoder[] Models; - int NumBitLevels; + private BitDecoder[] Models; + private int NumBitLevels; public BitTreeDecoder(int numBitLevels) { @@ -122,7 +122,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder uint m = 1; for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--) m = (m << 1) + Models[m].Decode(rangeDecoder); - return m - ((uint)1 << NumBitLevels); + return m - ((uint) 1 << NumBitLevels); } public uint ReverseDecode(RangeCoder.Decoder rangeDecoder) @@ -140,7 +140,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder } public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, - RangeCoder.Decoder rangeDecoder, int NumBitLevels) + RangeCoder.Decoder rangeDecoder, int NumBitLevels) { uint m = 1; uint symbol = 0; @@ -154,4 +154,4 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder return symbol; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/Registry.cs b/SharpCompress/Compressor/LZMA/Registry.cs index afdacad3..321b5670 100644 --- a/SharpCompress/Compressor/LZMA/Registry.cs +++ b/SharpCompress/Compressor/LZMA/Registry.cs @@ -11,17 +11,18 @@ namespace SharpCompress.Compressor.LZMA { internal static class DecoderRegistry { - const uint k_Copy = 0x0; - const uint k_Delta = 3; - const uint k_LZMA2 = 0x21; - const uint k_LZMA = 0x030101; - const uint k_PPMD = 0x030401; - const uint k_BCJ = 0x03030103; - const uint k_BCJ2 = 0x0303011B; - const uint k_Deflate = 0x040108; - const uint k_BZip2 = 0x040202; + private const uint k_Copy = 0x0; + private const uint k_Delta = 3; + private const uint k_LZMA2 = 0x21; + private const uint k_LZMA = 0x030101; + private const uint k_PPMD = 0x030401; + private const uint k_BCJ = 0x03030103; + private const uint k_BCJ2 = 0x0303011B; + private const uint k_Deflate = 0x040108; + private const uint k_BZip2 = 0x040202; - internal static Stream CreateDecoderStream(CMethodId id, Stream[] inStreams, byte[] info, IPasswordProvider pass, long limit) + internal static Stream CreateDecoderStream(CMethodId id, Stream[] inStreams, byte[] info, IPasswordProvider pass, + long limit) { switch (id.Id) { @@ -49,4 +50,4 @@ namespace SharpCompress.Compressor.LZMA } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/Utilites/CrcBuilderStream.cs b/SharpCompress/Compressor/LZMA/Utilites/CrcBuilderStream.cs index b4b44483..29fc2447 100644 --- a/SharpCompress/Compressor/LZMA/Utilites/CrcBuilderStream.cs +++ b/SharpCompress/Compressor/LZMA/Utilites/CrcBuilderStream.cs @@ -3,7 +3,7 @@ using System.IO; namespace SharpCompress.Compressor.LZMA.Utilites { - class CrcBuilderStream: Stream + internal class CrcBuilderStream : Stream { private long mProcessed; private Stream mTarget; @@ -23,7 +23,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites public uint Finish() { - if(!mFinished) + if (!mFinished) { mFinished = true; mCRC = CRC.Finish(mCRC); @@ -79,7 +79,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites public override void Write(byte[] buffer, int offset, int count) { - if(mFinished) + if (mFinished) throw new InvalidOperationException("CRC calculation has been finished."); mProcessed += count; @@ -88,7 +88,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites } } - class ReadingCrcBuilderStream: Stream + internal class ReadingCrcBuilderStream : Stream { private long mProcessed; private Stream mSource; @@ -105,7 +105,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites { try { - if(disposing) + if (disposing) mSource.Dispose(); } finally @@ -121,7 +121,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites public uint Finish() { - if(!mFinished) + if (!mFinished) { mFinished = true; mCRC = CRC.Finish(mCRC); @@ -163,10 +163,10 @@ namespace SharpCompress.Compressor.LZMA.Utilites public override int Read(byte[] buffer, int offset, int count) { - if(count > 0 && !mFinished) + if (count > 0 && !mFinished) { int read = mSource.Read(buffer, offset, count); - if(read > 0) + if (read > 0) { mProcessed += read; mCRC = CRC.Update(mCRC, buffer, offset, read); @@ -194,4 +194,4 @@ namespace SharpCompress.Compressor.LZMA.Utilites throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/Utilites/CrcCheckStream.cs b/SharpCompress/Compressor/LZMA/Utilites/CrcCheckStream.cs index 1c9b09f9..1cb2070a 100644 --- a/SharpCompress/Compressor/LZMA/Utilites/CrcCheckStream.cs +++ b/SharpCompress/Compressor/LZMA/Utilites/CrcCheckStream.cs @@ -3,7 +3,7 @@ using System.IO; namespace SharpCompress.Compressor.LZMA.Utilites { - class CrcCheckStream: Stream + internal class CrcCheckStream : Stream { private readonly uint mExpectedCRC; private uint mCurrentCRC; @@ -24,12 +24,12 @@ namespace SharpCompress.Compressor.LZMA.Utilites throw new InvalidOperationException(); try { - if(disposing && !mClosed) + if (disposing && !mClosed) { mClosed = true; mCurrentCRC = CRC.Finish(mCurrentCRC); #if DEBUG - if(mCurrentCRC == mExpectedCRC) + if (mCurrentCRC == mExpectedCRC) System.Diagnostics.Debug.WriteLine("CRC ok: " + mExpectedCRC.ToString("x8")); else { @@ -37,17 +37,17 @@ namespace SharpCompress.Compressor.LZMA.Utilites System.Diagnostics.Debug.WriteLine("bad CRC"); } - double lengthInv = 1.0 / mLength; + double lengthInv = 1.0/mLength; double entropy = 0; - for(int i = 0; i < 256; i++) + for (int i = 0; i < 256; i++) { - if(mBytes[i] != 0) + if (mBytes[i] != 0) { - double p = lengthInv * mBytes[i]; - entropy -= p * Math.Log(p, 256); + double p = lengthInv*mBytes[i]; + entropy -= p*Math.Log(p, 256); } } - System.Diagnostics.Debug.WriteLine("entropy: " + (int)(entropy * 100) + "%"); + System.Diagnostics.Debug.WriteLine("entropy: " + (int) (entropy*100) + "%"); #endif } } @@ -105,10 +105,10 @@ namespace SharpCompress.Compressor.LZMA.Utilites public override void Write(byte[] buffer, int offset, int count) { mLength += count; - for(int i = 0; i < count; i++) + for (int i = 0; i < count; i++) mBytes[buffer[offset + i]]++; mCurrentCRC = CRC.Update(mCurrentCRC, buffer, offset, count); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/Utilites/IPasswordProvider.cs b/SharpCompress/Compressor/LZMA/Utilites/IPasswordProvider.cs index 07a696a1..f03533a6 100644 --- a/SharpCompress/Compressor/LZMA/Utilites/IPasswordProvider.cs +++ b/SharpCompress/Compressor/LZMA/Utilites/IPasswordProvider.cs @@ -4,4 +4,4 @@ { string CryptoGetTextPassword(); } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/Utilites/SyncStreamView.cs b/SharpCompress/Compressor/LZMA/Utilites/SyncStreamView.cs index 6400a202..c8d0aaf3 100644 --- a/SharpCompress/Compressor/LZMA/Utilites/SyncStreamView.cs +++ b/SharpCompress/Compressor/LZMA/Utilites/SyncStreamView.cs @@ -6,7 +6,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites /// /// Allows reading the same stream from multiple threads by synchronizing read access. /// - class SyncStreamView: Stream + internal class SyncStreamView : Stream { private object mSync; private Stream mStream; @@ -53,7 +53,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites get { return mOffset; } set { - if(value < 0 || value > Length) + if (value < 0 || value > Length) throw new ArgumentOutOfRangeException("value"); mOffset = value; @@ -63,14 +63,14 @@ namespace SharpCompress.Compressor.LZMA.Utilites public override int Read(byte[] buffer, int offset, int count) { long remaining = mEnding - mOrigin - mOffset; - if(count > remaining) - count = (int)remaining; + if (count > remaining) + count = (int) remaining; - if(count == 0) + if (count == 0) return 0; int delta; - lock(mSync) + lock (mSync) { mStream.Position = mOrigin + mOffset; delta = mStream.Read(buffer, offset, count); @@ -82,16 +82,16 @@ namespace SharpCompress.Compressor.LZMA.Utilites public override long Seek(long offset, SeekOrigin origin) { - switch(origin) + switch (origin) { - case SeekOrigin.Begin: - return Position = offset; - case SeekOrigin.Current: - return Position += offset; - case SeekOrigin.End: - return Position = Length + offset; - default: - throw new ArgumentOutOfRangeException("origin"); + case SeekOrigin.Begin: + return Position = offset; + case SeekOrigin.Current: + return Position += offset; + case SeekOrigin.End: + return Position = Length + offset; + default: + throw new ArgumentOutOfRangeException("origin"); } } @@ -105,4 +105,4 @@ namespace SharpCompress.Compressor.LZMA.Utilites throw new InvalidOperationException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/LZMA/Utilites/Utils.cs b/SharpCompress/Compressor/LZMA/Utilites/Utils.cs index 0eabcb82..f535324d 100644 --- a/SharpCompress/Compressor/LZMA/Utilites/Utils.cs +++ b/SharpCompress/Compressor/LZMA/Utilites/Utils.cs @@ -4,7 +4,7 @@ using System.IO; namespace SharpCompress.Compressor.LZMA.Utilites { - internal enum BlockType: byte + internal enum BlockType : byte { #region Constants @@ -43,9 +43,9 @@ namespace SharpCompress.Compressor.LZMA.Utilites [Conditional("DEBUG")] public static void Assert(bool expression) { - if(!expression) + if (!expression) { - if(Debugger.IsAttached) + if (Debugger.IsAttached) Debugger.Break(); throw new Exception("Assertion failed."); @@ -54,22 +54,22 @@ namespace SharpCompress.Compressor.LZMA.Utilites public static void ReadExact(this Stream stream, byte[] buffer, int offset, int length) { - if(stream == null) + if (stream == null) throw new ArgumentNullException("stream"); - if(buffer == null) + if (buffer == null) throw new ArgumentNullException("buffer"); - if(offset < 0 || offset > buffer.Length) + if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); - if(length < 0 || length > buffer.Length - offset) + if (length < 0 || length > buffer.Length - offset) throw new ArgumentOutOfRangeException("length"); - while(length > 0) + while (length > 0) { int fetched = stream.Read(buffer, offset, length); - if(fetched <= 0) + if (fetched <= 0) throw new EndOfStreamException(); offset += fetched; @@ -77,4 +77,4 @@ namespace SharpCompress.Compressor.LZMA.Utilites } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/H/FreqData.cs b/SharpCompress/Compressor/PPMd/H/FreqData.cs index addcd8d6..a37ea93a 100644 --- a/SharpCompress/Compressor/PPMd/H/FreqData.cs +++ b/SharpCompress/Compressor/PPMd/H/FreqData.cs @@ -1,4 +1,5 @@ using System.Text; + namespace SharpCompress.Compressor.PPMd.H { internal class FreqData : Pointer @@ -18,16 +19,9 @@ namespace SharpCompress.Compressor.PPMd.H internal int SummFreq { - get - { - return Utility.readShortLittleEndian(Memory, Address) & 0xffff; - } - - set - { - Utility.WriteLittleEndian(Memory, Address, (short)value); - } + get { return Utility.readShortLittleEndian(Memory, Address) & 0xffff; } + set { Utility.WriteLittleEndian(Memory, Address, (short) value); } } internal FreqData Initialize(byte[] mem) @@ -37,7 +31,7 @@ namespace SharpCompress.Compressor.PPMd.H internal void IncrementSummFreq(int dSummFreq) { - Utility.incShortLittleEndian(Memory, Address, (short)dSummFreq); + Utility.incShortLittleEndian(Memory, Address, (short) dSummFreq); } internal int GetStats() diff --git a/SharpCompress/Compressor/PPMd/H/ModelPPM.cs b/SharpCompress/Compressor/PPMd/H/ModelPPM.cs index b3d0672e..d371d721 100644 --- a/SharpCompress/Compressor/PPMd/H/ModelPPM.cs +++ b/SharpCompress/Compressor/PPMd/H/ModelPPM.cs @@ -17,156 +17,94 @@ namespace SharpCompress.Compressor.PPMd.H binSumm[i2] = new int[64]; } } + public SubAllocator SubAlloc { - get - { - return subAlloc; - } - + get { return subAlloc; } } - virtual public SEE2Context DummySEE2Cont + + public virtual SEE2Context DummySEE2Cont { - get - { - return dummySEE2Cont; - } - + get { return dummySEE2Cont; } } - virtual public int InitRL + + public virtual int InitRL { - get - { - return initRL; - } - + get { return initRL; } } - virtual public int EscCount + + public virtual int EscCount { - get - { - return escCount; - } - - set - { - this.escCount = value & 0xff; - } + get { return escCount; } + set { this.escCount = value & 0xff; } } - virtual public int[] CharMask + + public virtual int[] CharMask { - get - { - return charMask; - } - + get { return charMask; } } - virtual public int NumMasked + + public virtual int NumMasked { - get - { - return numMasked; - } - - set - { - this.numMasked = value; - } + get { return numMasked; } + set { this.numMasked = value; } } - virtual public int PrevSuccess + + public virtual int PrevSuccess { - get - { - return prevSuccess; - } - - set - { - this.prevSuccess = value & 0xff; - } + get { return prevSuccess; } + set { this.prevSuccess = value & 0xff; } } - virtual public int InitEsc + + public virtual int InitEsc { - get - { - return initEsc; - } - - set - { - this.initEsc = value; - } + get { return initEsc; } + set { this.initEsc = value; } } - virtual public int RunLength + + public virtual int RunLength { - get - { - return runLength; - } - - set - { - this.runLength = value; - } + get { return runLength; } + set { this.runLength = value; } } - virtual public int HiBitsFlag + + public virtual int HiBitsFlag { - get - { - return hiBitsFlag; - } - - set - { - this.hiBitsFlag = value & 0xff; - } + get { return hiBitsFlag; } + set { this.hiBitsFlag = value & 0xff; } } - virtual public int[][] BinSumm + + public virtual int[][] BinSumm { - get - { - return binSumm; - } - + get { return binSumm; } } + internal RangeCoder Coder { - get - { - return coder; - } - + get { return coder; } } + internal State FoundState { - get - { - return foundState; - } - + get { return foundState; } } - virtual public byte[] Heap + + public virtual byte[] Heap { - get - { - return subAlloc.Heap; - } - + get { return subAlloc.Heap; } } - virtual public int OrderFall + + public virtual int OrderFall { - get - { - return orderFall; - } - + get { return orderFall; } } + public const int MAX_O = 64; /* maximum allowed model order */ public const int INT_BITS = 7; @@ -213,7 +151,7 @@ namespace SharpCompress.Compressor.PPMd.H private SubAllocator subAlloc = new SubAllocator(); - private static int[] InitBinEsc = new int[] { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051 }; + private static int[] InitBinEsc = new int[] {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'" @@ -260,7 +198,7 @@ namespace SharpCompress.Compressor.PPMd.H minContext.NumStats = 256; minContext.FreqData.SummFreq = minContext.NumStats + 1; - addr = subAlloc.allocUnits(256 / 2); + addr = subAlloc.allocUnits(256/2); foundState.Address = addr; minContext.FreqData.SetStats(addr); @@ -270,7 +208,7 @@ namespace SharpCompress.Compressor.PPMd.H prevSuccess = 0; for (int i = 0; i < 256; i++) { - state.Address = addr + i * State.Size; + state.Address = addr + i*State.Size; state.Symbol = i; state.Freq = 1; state.SetSuccessor(0); @@ -282,7 +220,7 @@ namespace SharpCompress.Compressor.PPMd.H { for (int m = 0; m < 64; m += 8) { - binSumm[i][k + m] = BIN_SCALE - InitBinEsc[k] / (i + 2); + binSumm[i][k + m] = BIN_SCALE - InitBinEsc[k]/(i + 2); } } } @@ -290,7 +228,7 @@ namespace SharpCompress.Compressor.PPMd.H { for (int k = 0; k < 16; k++) { - SEE2Cont[i][k].Initialize(5 * i + 10); + SEE2Cont[i][k].Initialize(5*i + 10); } } } @@ -344,7 +282,6 @@ namespace SharpCompress.Compressor.PPMd.H internal bool decodeInit(Unpack unpackRead, int escChar) { - int MaxOrder = unpackRead.Char & 0xff; bool reset = ((MaxOrder & 0x20) != 0); @@ -371,7 +308,7 @@ namespace SharpCompress.Compressor.PPMd.H MaxOrder = (MaxOrder & 0x1f) + 1; if (MaxOrder > 16) { - MaxOrder = 16 + (MaxOrder - 16) * 3; + MaxOrder = 16 + (MaxOrder - 16)*3; } if (MaxOrder == 1) { @@ -408,7 +345,8 @@ namespace SharpCompress.Compressor.PPMd.H if (minContext.NumStats != 1) { - if (minContext.FreqData.GetStats() <= subAlloc.PText || minContext.FreqData.GetStats() > subAlloc.HeapEnd) + if (minContext.FreqData.GetStats() <= subAlloc.PText || + minContext.FreqData.GetStats() > subAlloc.HeapEnd) { return (-1); } @@ -433,8 +371,7 @@ namespace SharpCompress.Compressor.PPMd.H { return (-1); } - } - while (minContext.NumStats == numMasked); + } while (minContext.NumStats == numMasked); if (!minContext.decodeSymbol2(this)) { return (-1); @@ -540,8 +477,7 @@ namespace SharpCompress.Compressor.PPMd.H do { p.IncrementAddress(); - } - while (p.Symbol != foundState.Symbol); + } while (p.Symbol != foundState.Symbol); } } else @@ -556,8 +492,7 @@ namespace SharpCompress.Compressor.PPMd.H break; } ps[pps++] = p.Address; - } - while (pc.getSuffix() != 0); + } while (pc.getSuffix() != 0); } // NO_LOOP: if (pps == 0) { @@ -579,13 +514,12 @@ namespace SharpCompress.Compressor.PPMd.H do { p.IncrementAddress(); - } - while (p.Symbol != upState.Symbol); + } while (p.Symbol != upState.Symbol); } int cf = p.Freq - 1; int s0 = pc.FreqData.SummFreq - pc.NumStats - cf; // UpState.Freq=1+((2*cf <= s0)?(5*cf > s0):((2*cf+3*s0-1)/(2*s0))); - upState.Freq = 1 + ((2 * cf <= s0) ? (5 * cf > s0 ? 1 : 0) : ((2 * cf + 3 * s0 - 1) / (2 * s0))); + upState.Freq = 1 + ((2*cf <= s0) ? (5*cf > s0 ? 1 : 0) : ((2*cf + 3*s0 - 1)/(2*s0))); } else { @@ -600,8 +534,7 @@ namespace SharpCompress.Compressor.PPMd.H { return 0; } - } - while (pps != 0); + } while (pps != 0); return pc.Address; } @@ -625,7 +558,7 @@ namespace SharpCompress.Compressor.PPMd.H int ns1, ns, cf, sf, s0; pc.Address = minContext.getSuffix(); - if (fs.Freq < MAX_FREQ / 4 && pc.Address != 0) + if (fs.Freq < MAX_FREQ/4 && pc.Address != 0) { if (pc.NumStats != 1) { @@ -635,8 +568,7 @@ namespace SharpCompress.Compressor.PPMd.H do { p.IncrementAddress(); - } - while (p.Symbol != fs.Symbol); + } while (p.Symbol != fs.Symbol); tempState.Address = p.Address - State.Size; if (p.Freq >= tempState.Freq) { @@ -671,7 +603,7 @@ namespace SharpCompress.Compressor.PPMd.H } return; } - subAlloc.Heap[subAlloc.PText] = (byte)fs.Symbol; + subAlloc.Heap[subAlloc.PText] = (byte) fs.Symbol; subAlloc.incPText(); successor.Address = subAlloc.PText; if (subAlloc.PText >= subAlloc.FakeUnitsStart) @@ -728,7 +660,8 @@ namespace SharpCompress.Compressor.PPMd.H // int sum = ((2 * ns1 < ns) ? 1 : 0) + // 2 * ((4 * ((ns1 <= ns) ? 1 : 0)) & ((pc.getFreqData() // .getSummFreq() <= 8 * ns1) ? 1 : 0)); - int sum = ((2 * ns1 < ns) ? 1 : 0) + 2 * (((4 * ns1 <= ns) ? 1 : 0) & ((pc.FreqData.SummFreq <= 8 * ns1) ? 1 : 0)); + int sum = ((2*ns1 < ns) ? 1 : 0) + + 2*(((4*ns1 <= ns) ? 1 : 0) & ((pc.FreqData.SummFreq <= 8*ns1) ? 1 : 0)); pc.FreqData.IncrementSummFreq(sum); } else @@ -741,7 +674,7 @@ namespace SharpCompress.Compressor.PPMd.H } p.SetValues(pc.getOneState()); pc.FreqData.SetStats(p); - if (p.Freq < MAX_FREQ / 4 - 1) + if (p.Freq < MAX_FREQ/4 - 1) { p.IncrementFreq(p.Freq); } @@ -751,19 +684,19 @@ namespace SharpCompress.Compressor.PPMd.H } pc.FreqData.SummFreq = (p.Freq + initEsc + (ns > 3 ? 1 : 0)); } - cf = 2 * fs.Freq * (pc.FreqData.SummFreq + 6); + cf = 2*fs.Freq*(pc.FreqData.SummFreq + 6); sf = s0 + pc.FreqData.SummFreq; - if (cf < 6 * sf) + if (cf < 6*sf) { - cf = 1 + (cf > sf ? 1 : 0) + (cf >= 4 * sf ? 1 : 0); + cf = 1 + (cf > sf ? 1 : 0) + (cf >= 4*sf ? 1 : 0); pc.FreqData.IncrementSummFreq(3); } else { - cf = 4 + (cf >= 9 * sf ? 1 : 0) + (cf >= 12 * sf ? 1 : 0) + (cf >= 15 * sf ? 1 : 0); + cf = 4 + (cf >= 9*sf ? 1 : 0) + (cf >= 12*sf ? 1 : 0) + (cf >= 15*sf ? 1 : 0); pc.FreqData.IncrementSummFreq(cf); } - p.Address = pc.FreqData.GetStats() + ns1 * State.Size; + p.Address = pc.FreqData.GetStats() + ns1*State.Size; p.SetSuccessor(successor); p.Symbol = fs.Symbol; p.Freq = cf; @@ -867,11 +800,11 @@ namespace SharpCompress.Compressor.PPMd.H s.Address = minContext.FreqData.GetStats(); int i; int count, hiCnt; - if ((count = (int)decoder.GetThreshold((uint)minContext.FreqData.SummFreq)) < (hiCnt = s.Freq)) + if ((count = (int) decoder.GetThreshold((uint) minContext.FreqData.SummFreq)) < (hiCnt = s.Freq)) { byte symbol; - decoder.Decode(0, (uint)s.Freq); - symbol = (byte)s.Symbol; + decoder.Decode(0, (uint) s.Freq); + symbol = (byte) s.Symbol; minContext.update1_0(this, s.Address); nextContext(); return symbol; @@ -884,18 +817,17 @@ namespace SharpCompress.Compressor.PPMd.H if ((hiCnt += s.Freq) > count) { byte symbol; - decoder.Decode((uint)(hiCnt - s.Freq), (uint)s.Freq); - symbol = (byte)s.Symbol; + decoder.Decode((uint) (hiCnt - s.Freq), (uint) s.Freq); + symbol = (byte) s.Symbol; minContext.update1(this, s.Address); nextContext(); return symbol; } - } - while (--i > 0); + } while (--i > 0); if (count >= minContext.FreqData.SummFreq) return -2; hiBitsFlag = HB2Flag[foundState.Symbol]; - decoder.Decode((uint)hiCnt, (uint)(minContext.FreqData.SummFreq - hiCnt)); + decoder.Decode((uint) hiCnt, (uint) (minContext.FreqData.SummFreq - hiCnt)); for (i = 0; i < 256; i++) charMask[i] = -1; charMask[s.Symbol] = 0; @@ -904,8 +836,7 @@ namespace SharpCompress.Compressor.PPMd.H { s.DecrementAddress(); charMask[s.Symbol] = 0; - } - while (--i > 0); + } while (--i > 0); } else { @@ -915,12 +846,12 @@ namespace SharpCompress.Compressor.PPMd.H int off1 = rs.Freq - 1; int off2 = minContext.getArrayIndex(this, rs); int bs = binSumm[off1][off2]; - if (decoder.DecodeBit((uint)bs, 14) == 0) + if (decoder.DecodeBit((uint) bs, 14) == 0) { byte symbol; binSumm[off1][off2] = (bs + INTERVAL - minContext.getMean(bs, PERIOD_BITS, 2)) & 0xFFFF; foundState.Address = rs.Address; - symbol = (byte)rs.Symbol; + symbol = (byte) rs.Symbol; rs.IncrementFreq((rs.Freq < 128) ? 1 : 0); prevSuccess = 1; incRunLength(1); @@ -949,8 +880,7 @@ namespace SharpCompress.Compressor.PPMd.H minContext.Address = minContext.getSuffix(); if (minContext.Address <= subAlloc.PText || minContext.Address > subAlloc.HeapEnd) return -1; - } - while (minContext.NumStats == numMasked); + } while (minContext.NumStats == numMasked); hiCnt = 0; s.Address = minContext.FreqData.GetStats(); i = 0; @@ -962,36 +892,36 @@ namespace SharpCompress.Compressor.PPMd.H minContext.ps[i] = s.Address; s.IncrementAddress(); i -= k; - } - while (i != num); + } while (i != num); see = minContext.makeEscFreq(this, numMasked, out freqSum); freqSum += hiCnt; - count = (int)decoder.GetThreshold((uint)freqSum); + count = (int) decoder.GetThreshold((uint) freqSum); if (count < hiCnt) { byte symbol; State ps = tempState2.Initialize(Heap); - for (hiCnt = 0, i = 0, ps.Address = minContext.ps[i]; (hiCnt += ps.Freq) <= count; i++, ps.Address = minContext.ps[i]); + for (hiCnt = 0, i = 0, ps.Address = minContext.ps[i]; + (hiCnt += ps.Freq) <= count; + i++, ps.Address = minContext.ps[i]) ; s.Address = ps.Address; - decoder.Decode((uint)(hiCnt - s.Freq), (uint)s.Freq); + decoder.Decode((uint) (hiCnt - s.Freq), (uint) s.Freq); see.update(); - symbol = (byte)s.Symbol; + symbol = (byte) s.Symbol; minContext.update2(this, s.Address); updateModel(); return symbol; } if (count >= freqSum) return -2; - decoder.Decode((uint)hiCnt, (uint)(freqSum - hiCnt)); + decoder.Decode((uint) hiCnt, (uint) (freqSum - hiCnt)); see.Summ = see.Summ + freqSum; do { s.Address = minContext.ps[--i]; charMask[s.Symbol] = 0; - } - while (i != 0); + } while (i != 0); } } } diff --git a/SharpCompress/Compressor/PPMd/H/PPMContext.cs b/SharpCompress/Compressor/PPMd/H/PPMContext.cs index 27132d4a..8b36bf6d 100644 --- a/SharpCompress/Compressor/PPMd/H/PPMContext.cs +++ b/SharpCompress/Compressor/PPMd/H/PPMContext.cs @@ -1,23 +1,21 @@ using System.Text; + namespace SharpCompress.Compressor.PPMd.H { internal class PPMContext : Pointer { internal FreqData FreqData { - get - { - return freqData; - } + get { return freqData; } set { this.freqData.SummFreq = value.SummFreq; this.freqData.SetStats(value.GetStats()); } - } - virtual public int NumStats + + public virtual int NumStats { get { @@ -33,10 +31,9 @@ namespace SharpCompress.Compressor.PPMd.H this.numStats = value & 0xffff; if (Memory != null) { - Utility.WriteLittleEndian(Memory, Address, (short)value); + Utility.WriteLittleEndian(Memory, Address, (short) value); } } - } //UPGRADE_NOTE: Final was removed from the declaration of 'unionSize '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" @@ -61,7 +58,7 @@ namespace SharpCompress.Compressor.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[] ExpEscape = new int[] { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; + public static readonly int[] ExpEscape = new int[] {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'" @@ -127,10 +124,7 @@ namespace SharpCompress.Compressor.PPMd.H internal override int Address { - get - { - return base.Address; - } + get { return base.Address; } set { base.Address = value; @@ -203,20 +197,17 @@ namespace SharpCompress.Compressor.PPMd.H p1.SetValues(temp2); p1.DecrementAddress(); temp3.Address = p1.Address - State.Size; - } - while (p1.Address != freqData.GetStats() && tmp.Freq > temp3.Freq); + } while (p1.Address != freqData.GetStats() && tmp.Freq > temp3.Freq); p1.SetValues(tmp); } - } - while (--i != 0); + } while (--i != 0); if (p.Freq == 0) { do { i++; p.DecrementAddress(); - } - while (p.Freq == 0); + } while (p.Freq == 0); EscFreq += i; NumStats = NumStats - i; if (NumStats == 1) @@ -230,8 +221,7 @@ namespace SharpCompress.Compressor.PPMd.H // tmp.Freq-=(tmp.Freq >> 1) tmp.DecrementFreq(Utility.URShift(tmp.Freq, 1)); EscFreq = Utility.URShift(EscFreq, 1); - } - while (EscFreq > 1); + } while (EscFreq > 1); model.SubAlloc.freeUnits(freqData.GetStats(), Utility.URShift((OldNS + 1), 1)); oneState.SetValues(tmp); model.FoundState.Address = oneState.Address; @@ -255,7 +245,7 @@ namespace SharpCompress.Compressor.PPMd.H int ret = 0; ret += Model.PrevSuccess; ret += Model.getNS2BSIndx()[tempSuffix.NumStats - 1]; - ret += Model.HiBitsFlag + 2 * Model.getHB2Flag()[rs.Symbol]; + ret += Model.HiBitsFlag + 2*Model.getHB2Flag()[rs.Symbol]; ret += ((Utility.URShift(Model.RunLength, 26)) & 0x20); return ret; } @@ -335,7 +325,7 @@ namespace SharpCompress.Compressor.PPMd.H internal void update1_0(ModelPPM model, int p) { model.FoundState.Address = p; - model.PrevSuccess = 2 * model.FoundState.Freq > freqData.SummFreq ? 1 : 0; + model.PrevSuccess = 2*model.FoundState.Freq > freqData.SummFreq ? 1 : 0; model.incRunLength(model.PrevSuccess); freqData.IncrementSummFreq(4); model.FoundState.IncrementFreq(4); @@ -361,12 +351,10 @@ namespace SharpCompress.Compressor.PPMd.H do { p.IncrementAddress(); // p++; - } - while (model.CharMask[p.Symbol] == model.EscCount); + } while (model.CharMask[p.Symbol] == model.EscCount); hiCnt += p.Freq; ps[pps++] = p.Address; - } - while (--i != 0); + } while (--i != 0); coder.SubRange.incScale(hiCnt); count = coder.CurrentCount; if (count >= coder.SubRange.Scale) @@ -397,9 +385,8 @@ namespace SharpCompress.Compressor.PPMd.H { temp.Address = ps[++pps]; // (*++pps) model.CharMask[temp.Symbol] = model.EscCount; - } - while (--i != 0); - psee2c.incSumm((int)coder.SubRange.Scale); + } while (--i != 0); + psee2c.incSumm((int) coder.SubRange.Scale); model.NumMasked = NumStats; } return (true); @@ -431,8 +418,8 @@ namespace SharpCompress.Compressor.PPMd.H int idx1 = model.getNS2Indx()[Diff - 1]; int idx2 = 0; idx2 += ((Diff < suff.NumStats - numStats) ? 1 : 0); - idx2 += 2 * ((freqData.SummFreq < 11 * numStats) ? 1 : 0); - idx2 += 4 * ((model.NumMasked > Diff) ? 1 : 0); + idx2 += 2*((freqData.SummFreq < 11*numStats) ? 1 : 0); + idx2 += 4*((model.NumMasked > Diff) ? 1 : 0); idx2 += model.HiBitsFlag; psee2c = model.getSEE2Cont()[idx1][idx2]; model.Coder.SubRange.Scale = psee2c.Mean; @@ -457,8 +444,8 @@ namespace SharpCompress.Compressor.PPMd.H int idx1 = model.getNS2Indx()[nonMasked - 1]; int idx2 = 0; idx2 += ((nonMasked < suff.NumStats - numStats) ? 1 : 0); - idx2 += 2 * ((freqData.SummFreq < 11 * numStats) ? 1 : 0); - idx2 += 4 * ((numMasked > nonMasked) ? 1 : 0); + idx2 += 2*((freqData.SummFreq < 11*numStats) ? 1 : 0); + idx2 += 4*((numMasked > nonMasked) ? 1 : 0); idx2 += model.HiBitsFlag; psee2c = model.getSEE2Cont()[idx1][idx2]; escFreq = psee2c.Mean; @@ -473,7 +460,6 @@ namespace SharpCompress.Compressor.PPMd.H internal bool decodeSymbol1(ModelPPM model) { - RangeCoder coder = model.Coder; coder.SubRange.Scale = freqData.SummFreq; State p = new State(model.Heap); @@ -487,7 +473,7 @@ namespace SharpCompress.Compressor.PPMd.H if (count < (HiCnt = p.Freq)) { coder.SubRange.HighCount = HiCnt; - model.PrevSuccess = (2 * HiCnt > coder.SubRange.Scale) ? 1 : 0; + model.PrevSuccess = (2*HiCnt > coder.SubRange.Scale) ? 1 : 0; model.incRunLength(model.PrevSuccess); HiCnt += 4; model.FoundState.Address = p.Address; @@ -523,8 +509,7 @@ namespace SharpCompress.Compressor.PPMd.H do { model.CharMask[p.DecrementAddress().Symbol] = model.EscCount; - } - while (--i != 0); + } while (--i != 0); coder.SubRange.HighCount = coder.SubRange.Scale; return (true); } @@ -554,6 +539,7 @@ namespace SharpCompress.Compressor.PPMd.H buffer.Append("\n]"); return buffer.ToString(); } + static PPMContext() { unionSize = System.Math.Max(FreqData.Size, State.Size); diff --git a/SharpCompress/Compressor/PPMd/H/Pointer.cs b/SharpCompress/Compressor/PPMd/H/Pointer.cs index cb9b8ce9..c5230c87 100644 --- a/SharpCompress/Compressor/PPMd/H/Pointer.cs +++ b/SharpCompress/Compressor/PPMd/H/Pointer.cs @@ -1,4 +1,3 @@ - namespace SharpCompress.Compressor.PPMd.H { internal abstract class Pointer @@ -11,17 +10,9 @@ namespace SharpCompress.Compressor.PPMd.H Memory = mem; } - internal byte[] Memory - { - get; - private set; - } + internal byte[] Memory { get; private set; } - internal virtual int Address - { - get; - set; - } + internal virtual int Address { get; set; } protected T Initialize(byte[] mem) where T : Pointer diff --git a/SharpCompress/Compressor/PPMd/H/RangeCoder.cs b/SharpCompress/Compressor/PPMd/H/RangeCoder.cs index e291dc4b..e3b48200 100644 --- a/SharpCompress/Compressor/PPMd/H/RangeCoder.cs +++ b/SharpCompress/Compressor/PPMd/H/RangeCoder.cs @@ -43,10 +43,9 @@ namespace SharpCompress.Compressor.PPMd.H { get { - range = (range / SubRange.Scale) & UintMask; - return (int)((code - low) / (range)); + range = (range/SubRange.Scale) & UintMask; + return (int) ((code - low)/(range)); } - } private long Char @@ -59,26 +58,21 @@ namespace SharpCompress.Compressor.PPMd.H return stream.ReadByte(); return -1; } - } - internal SubRange SubRange - { - get; - private set; - } + internal SubRange SubRange { get; private set; } internal long GetCurrentShiftCount(int SHIFT) { range = Utility.URShift(range, SHIFT); - return ((code - low) / (range)) & UintMask; + return ((code - low)/(range)) & UintMask; } internal void Decode() { - low = (low + (range * SubRange.LowCount)) & UintMask; - range = (range * (SubRange.HighCount - SubRange.LowCount)) & UintMask; + low = (low + (range*SubRange.LowCount)) & UintMask; + range = (range*(SubRange.HighCount - SubRange.LowCount)) & UintMask; } internal void AriDecNormalize() @@ -135,44 +129,23 @@ namespace SharpCompress.Compressor.PPMd.H internal long HighCount { - get - { - return highCount; - } - - set - { - this.highCount = value & RangeCoder.UintMask; - } + get { return highCount; } + set { this.highCount = value & RangeCoder.UintMask; } } internal long LowCount { - get - { - return lowCount & RangeCoder.UintMask; - } - - set - { - this.lowCount = value & RangeCoder.UintMask; - } + get { return lowCount & RangeCoder.UintMask; } + set { this.lowCount = value & RangeCoder.UintMask; } } internal long Scale { - get - { - return scale; - } - - set - { - this.scale = value & RangeCoder.UintMask; - } + get { return scale; } + set { this.scale = value & RangeCoder.UintMask; } } // Debug diff --git a/SharpCompress/Compressor/PPMd/H/RarMemBlock.cs b/SharpCompress/Compressor/PPMd/H/RarMemBlock.cs index ca93e18b..52f601d8 100644 --- a/SharpCompress/Compressor/PPMd/H/RarMemBlock.cs +++ b/SharpCompress/Compressor/PPMd/H/RarMemBlock.cs @@ -1,4 +1,3 @@ - namespace SharpCompress.Compressor.PPMd.H { internal class RarMemBlock : Pointer @@ -30,10 +29,9 @@ namespace SharpCompress.Compressor.PPMd.H this.stamp = value; if (Memory != null) { - Utility.WriteLittleEndian(Memory, Address, (short)value); + Utility.WriteLittleEndian(Memory, Address, (short) value); } } - } internal void InsertAt(RarMemBlock p) @@ -95,7 +93,7 @@ namespace SharpCompress.Compressor.PPMd.H NU = nu & 0xffff; if (Memory != null) { - Utility.WriteLittleEndian(Memory, Address + 2, (short)nu); + Utility.WriteLittleEndian(Memory, Address + 2, (short) nu); } } diff --git a/SharpCompress/Compressor/PPMd/H/SEE2Context.cs b/SharpCompress/Compressor/PPMd/H/SEE2Context.cs index f7444a19..c9688124 100644 --- a/SharpCompress/Compressor/PPMd/H/SEE2Context.cs +++ b/SharpCompress/Compressor/PPMd/H/SEE2Context.cs @@ -1,9 +1,10 @@ using System.Text; + namespace SharpCompress.Compressor.PPMd.H { internal class SEE2Context { - virtual public int Mean + public virtual int Mean { get { @@ -11,47 +12,29 @@ namespace SharpCompress.Compressor.PPMd.H summ -= retVal; return retVal + ((retVal == 0) ? 1 : 0); } - } - virtual public int Count + + public virtual int Count { - get - { - return count; - } - - set - { - this.count = value & 0xff; - } + get { return count; } + set { this.count = value & 0xff; } } - virtual public int Shift + + public virtual int Shift { - get - { - return shift; - } - - set - { - this.shift = value & 0xff; - } + get { return shift; } + set { this.shift = value & 0xff; } } - virtual public int Summ + + public virtual int Summ { - get - { - return summ; - } - - set - { - this.summ = value & 0xffff; - } + get { return summ; } + set { this.summ = value & 0xffff; } } + public const int size = 4; // ushort Summ; diff --git a/SharpCompress/Compressor/PPMd/H/State.cs b/SharpCompress/Compressor/PPMd/H/State.cs index 40cd1eb3..a459321e 100644 --- a/SharpCompress/Compressor/PPMd/H/State.cs +++ b/SharpCompress/Compressor/PPMd/H/State.cs @@ -14,29 +14,16 @@ namespace SharpCompress.Compressor.PPMd.H internal int Symbol { - get - { - return Memory[Address] & 0xff; - } - - set - { - Memory[Address] = (byte)value; - } + get { return Memory[Address] & 0xff; } + set { Memory[Address] = (byte) value; } } + internal int Freq { - get - { - return Memory[Address + 1] & 0xff; - } - - set - { - Memory[Address + 1] = (byte)value; - } + get { return Memory[Address + 1] & 0xff; } + set { Memory[Address + 1] = (byte) value; } } internal State Initialize(byte[] mem) @@ -46,7 +33,7 @@ namespace SharpCompress.Compressor.PPMd.H internal void IncrementFreq(int dFreq) { - Memory[Address + 1] = (byte)(Memory[Address + 1] + dFreq); + Memory[Address + 1] = (byte) (Memory[Address + 1] + dFreq); } internal int GetSuccessor() diff --git a/SharpCompress/Compressor/PPMd/H/StateRef.cs b/SharpCompress/Compressor/PPMd/H/StateRef.cs index a303a2b5..ee2eb37b 100644 --- a/SharpCompress/Compressor/PPMd/H/StateRef.cs +++ b/SharpCompress/Compressor/PPMd/H/StateRef.cs @@ -12,29 +12,16 @@ namespace SharpCompress.Compressor.PPMd.H internal int Symbol { - get - { - return symbol; - } - - set - { - this.symbol = value & 0xff; - } + get { return symbol; } + set { this.symbol = value & 0xff; } } + internal int Freq { - get - { - return freq; - } - - set - { - this.freq = value & 0xff; - } + get { return freq; } + set { this.freq = value & 0xff; } } internal State Values diff --git a/SharpCompress/Compressor/PPMd/H/SubAllocator.cs b/SharpCompress/Compressor/PPMd/H/SubAllocator.cs index e23b3f1b..dd209cb7 100644 --- a/SharpCompress/Compressor/PPMd/H/SubAllocator.cs +++ b/SharpCompress/Compressor/PPMd/H/SubAllocator.cs @@ -1,69 +1,46 @@ using System; using System.Text; + namespace SharpCompress.Compressor.PPMd.H { internal class SubAllocator { - virtual public int FakeUnitsStart + public virtual int FakeUnitsStart { - get - { - return fakeUnitsStart; - } - - set - { - this.fakeUnitsStart = value; - } + get { return fakeUnitsStart; } + set { this.fakeUnitsStart = value; } } - virtual public int HeapEnd + + public virtual int HeapEnd { - get - { - return heapEnd; - } - + get { return heapEnd; } } - virtual public int PText + + public virtual int PText { - get - { - return pText; - } - - set - { - pText = value; - } + get { return pText; } + set { pText = value; } } - virtual public int UnitsStart + + public virtual int UnitsStart { - get - { - return unitsStart; - } - - set - { - this.unitsStart = value; - } + get { return unitsStart; } + set { this.unitsStart = value; } } - virtual public byte[] Heap + + public virtual byte[] Heap { - get - { - return heap; - } - + get { return heap; } } + //UPGRADE_NOTE: Final was removed from the declaration of 'N4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public const int N1 = 4; public const int N2 = 4; public const int N3 = 4; - public static readonly int N4 = (128 + 3 - 1 * N1 - 2 * N2 - 3 * N3) / 4; + public static readonly int N4 = (128 + 3 - 1*N1 - 2*N2 - 3*N3)/4; //UPGRADE_NOTE: Final was removed from the declaration of 'N_INDEXES '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public static readonly int N_INDEXES = N1 + N2 + N3 + N4; @@ -136,10 +113,11 @@ namespace SharpCompress.Compressor.PPMd.H private int U2B(int NU) { - return UNIT_SIZE * NU; + return UNIT_SIZE*NU; } /* memblockptr */ + private int MBPtr(int BasePtr, int Items) { return (BasePtr + U2B(Items)); @@ -189,11 +167,11 @@ namespace SharpCompress.Compressor.PPMd.H return true; } stopSubAllocator(); - int allocSize = t / FIXED_UNIT_SIZE * UNIT_SIZE + UNIT_SIZE; + int allocSize = t/FIXED_UNIT_SIZE*UNIT_SIZE + UNIT_SIZE; // adding space for freelist (needed for poiters) // 1+ for null pointer - int realAllocSize = 1 + allocSize + 4 * N_INDEXES; + int realAllocSize = 1 + allocSize + 4*N_INDEXES; // adding space for an additional memblock tempMemBlockPos = realAllocSize; realAllocSize += RarMemBlock.size; @@ -295,7 +273,7 @@ namespace SharpCompress.Compressor.PPMd.H { glueCount--; i = U2B(indx2Units[indx]); - int j = FIXED_UNIT_SIZE * indx2Units[indx]; + int j = FIXED_UNIT_SIZE*indx2Units[indx]; if (fakeUnitsStart - pText > j) { fakeUnitsStart -= j; @@ -304,8 +282,7 @@ namespace SharpCompress.Compressor.PPMd.H } return (0); } - } - while (freeList[i].GetNext() == 0); + } while (freeList[i].GetNext() == 0); int retVal = removeNode(i); splitBlock(retVal, i, indx); return retVal; @@ -398,14 +375,14 @@ namespace SharpCompress.Compressor.PPMd.H public virtual void initSubAllocator() { int i, k; - Utility.Fill(heap, freeListPos, freeListPos + sizeOfFreeList(), (byte)0); + Utility.Fill(heap, freeListPos, freeListPos + sizeOfFreeList(), (byte) 0); pText = heapStart; - int size2 = FIXED_UNIT_SIZE * (subAllocatorSize / 8 / FIXED_UNIT_SIZE * 7); - int realSize2 = size2 / FIXED_UNIT_SIZE * UNIT_SIZE; + int size2 = FIXED_UNIT_SIZE*(subAllocatorSize/8/FIXED_UNIT_SIZE*7); + int realSize2 = size2/FIXED_UNIT_SIZE*UNIT_SIZE; int size1 = subAllocatorSize - size2; - int realSize1 = size1 / FIXED_UNIT_SIZE * UNIT_SIZE + size1 % FIXED_UNIT_SIZE; + int realSize1 = size1/FIXED_UNIT_SIZE*UNIT_SIZE + size1%FIXED_UNIT_SIZE; hiUnit = heapStart + subAllocatorSize; loUnit = unitsStart = heapStart + realSize1; fakeUnitsStart = heapStart + size1; @@ -437,7 +414,7 @@ namespace SharpCompress.Compressor.PPMd.H private int sizeOfFreeList() { - return freeList.Length * RarNode.size; + return freeList.Length*RarNode.size; } // Debug @@ -480,6 +457,7 @@ namespace SharpCompress.Compressor.PPMd.H buffer.Append("\n]"); return buffer.ToString(); } + static SubAllocator() { UNIT_SIZE = System.Math.Max(PPMContext.size, RarMemBlock.size); diff --git a/SharpCompress/Compressor/PPMd/I1/Allocator.cs b/SharpCompress/Compressor/PPMd/I1/Allocator.cs index 945ea35f..f47ca24a 100644 --- a/SharpCompress/Compressor/PPMd/I1/Allocator.cs +++ b/SharpCompress/Compressor/PPMd/I1/Allocator.cs @@ -1,12 +1,9 @@ #region Using - - #endregion namespace SharpCompress.Compressor.PPMd.I1 { - /// Allocate a single, large array and then provide sections of this array to callers. Callers are provided with /// instances of (which simply contain a single address value, representing a location /// in the large array). Callers can then cast to one of the following structures (all @@ -14,13 +11,16 @@ namespace SharpCompress.Compressor.PPMd.I1 internal class Allocator { private const uint UnitSize = 12; - private const uint LocalOffset = 4; // reserve the first four bytes for Pointer.Zero - private const uint NodeOffset = LocalOffset + MemoryNode.Size; // reserve space for a single memory node - private const uint HeapOffset = NodeOffset + IndexCount * MemoryNode.Size; // reserve space for the array of memory nodes + private const uint LocalOffset = 4; // reserve the first four bytes for Pointer.Zero + private const uint NodeOffset = LocalOffset + MemoryNode.Size; // reserve space for a single memory node + + private const uint HeapOffset = NodeOffset + IndexCount*MemoryNode.Size; + // reserve space for the array of memory nodes + private const uint N1 = 4; private const uint N2 = 4; private const uint N3 = 4; - private const uint N4 = (128 + 3 - 1 * N1 - 2 * N2 - 3 * N3) / 4; + private const uint N4 = (128 + 3 - 1*N1 - 2*N2 - 3*N3)/4; private const uint IndexCount = N1 + N2 + N3 + N4; private static readonly byte[] indexToUnits; @@ -53,16 +53,16 @@ namespace SharpCompress.Compressor.PPMd.I1 indexToUnits = new byte[IndexCount]; for (index = 0, unitCount = 1; index < N1; index++, unitCount += 1) - indexToUnits[index] = (byte)unitCount; + indexToUnits[index] = (byte) unitCount; for (unitCount++; index < N1 + N2; index++, unitCount += 2) - indexToUnits[index] = (byte)unitCount; + indexToUnits[index] = (byte) unitCount; for (unitCount++; index < N1 + N2 + N3; index++, unitCount += 3) - indexToUnits[index] = (byte)unitCount; + indexToUnits[index] = (byte) unitCount; for (unitCount++; index < N1 + N2 + N3 + N4; index++, unitCount += 4) - indexToUnits[index] = (byte)unitCount; + indexToUnits[index] = (byte) unitCount; // Construct the static units to index lookup array. It will contain the following values. // @@ -75,8 +75,8 @@ namespace SharpCompress.Compressor.PPMd.I1 for (unitCount = index = 0; unitCount < 128; unitCount++) { - index += (uint)((indexToUnits[index] < unitCount + 1) ? 1 : 0); - unitsToIndex[unitCount] = (byte)index; + index += (uint) ((indexToUnits[index] < unitCount + 1) ? 1 : 0); + unitsToIndex[unitCount] = (byte) index; } } @@ -95,7 +95,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { for (int index = 0; index < IndexCount; index++) { - MemoryNodes[index] = new MemoryNode((uint)(NodeOffset + index * MemoryNode.Size), Memory); + MemoryNodes[index] = new MemoryNode((uint) (NodeOffset + index*MemoryNode.Size), Memory); MemoryNodes[index].Stamp = 0; MemoryNodes[index].Next = MemoryNode.Zero; MemoryNodes[index].UnitCount = 0; @@ -103,7 +103,7 @@ namespace SharpCompress.Compressor.PPMd.I1 Text = Heap; - uint difference = UnitSize * (AllocatorSize / 8 / UnitSize * 7); + uint difference = UnitSize*(AllocatorSize/8/UnitSize*7); HighUnit = Heap + AllocatorSize; LowUnit = HighUnit - difference; @@ -121,12 +121,12 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public void Start(int allocatorSize) { - uint size = (uint)allocatorSize; + uint size = (uint) allocatorSize; if (AllocatorSize != size) { Stop(); - Memory = new byte[HeapOffset + size]; // the single, large array of bytes - Heap = new Pointer(HeapOffset, Memory); // reserve bytes in the range 0 .. HeapOffset - 1 + Memory = new byte[HeapOffset + size]; // the single, large array of bytes + Heap = new Pointer(HeapOffset, Memory); // reserve bytes in the range 0 .. HeapOffset - 1 AllocatorSize = size; } } @@ -156,7 +156,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { uint memoryUsed = AllocatorSize - (HighUnit - LowUnit) - (BaseUnit - Text); for (uint index = 0; index < IndexCount; index++) - memoryUsed -= UnitSize * indexToUnits[index] * MemoryNodes[index].Stamp; + memoryUsed -= UnitSize*indexToUnits[index]*MemoryNodes[index].Stamp; return memoryUsed; } @@ -173,11 +173,11 @@ namespace SharpCompress.Compressor.PPMd.I1 return MemoryNodes[index].Remove(); Pointer allocatedBlock = LowUnit; - LowUnit += indexToUnits[index] * UnitSize; + LowUnit += indexToUnits[index]*UnitSize; if (LowUnit <= HighUnit) return allocatedBlock; - LowUnit -= indexToUnits[index] * UnitSize; + LowUnit -= indexToUnits[index]*UnitSize; return AllocateUnitsRare(index); } @@ -279,7 +279,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { uint index = unitsToIndex[unitCount - 1]; - if (oldPointer > BaseUnit + 16 * 1024 || oldPointer > MemoryNodes[index].Next) + if (oldPointer > BaseUnit + 16*1024 || oldPointer > MemoryNodes[index].Next) return oldPointer; Pointer pointer = MemoryNodes[index].Remove(); @@ -289,7 +289,7 @@ namespace SharpCompress.Compressor.PPMd.I1 if (oldPointer != BaseUnit) MemoryNodes[index].Insert(oldPointer, unitCount); else - BaseUnit += unitCount * UnitSize; + BaseUnit += unitCount*UnitSize; return pointer; } @@ -344,7 +344,7 @@ namespace SharpCompress.Compressor.PPMd.I1 if (++oldIndex == IndexCount) { GlueCount--; - oldIndex = indexToUnits[index] * UnitSize; + oldIndex = indexToUnits[index]*UnitSize; return (BaseUnit - Text > oldIndex) ? (BaseUnit -= oldIndex) : Pointer.Zero; } } while (!MemoryNodes[oldIndex].Available); @@ -356,15 +356,15 @@ namespace SharpCompress.Compressor.PPMd.I1 private void SplitBlock(Pointer pointer, uint oldIndex, uint newIndex) { - uint unitCountDifference = (uint)(indexToUnits[oldIndex] - indexToUnits[newIndex]); - Pointer newPointer = pointer + indexToUnits[newIndex] * UnitSize; + uint unitCountDifference = (uint) (indexToUnits[oldIndex] - indexToUnits[newIndex]); + Pointer newPointer = pointer + indexToUnits[newIndex]*UnitSize; uint index = unitsToIndex[unitCountDifference - 1]; if (indexToUnits[index] != unitCountDifference) { uint unitCount = indexToUnits[--index]; MemoryNodes[index].Insert(newPointer, unitCount); - newPointer += unitCount * UnitSize; + newPointer += unitCount*UnitSize; unitCountDifference -= unitCount; } @@ -421,7 +421,8 @@ namespace SharpCompress.Compressor.PPMd.I1 if (indexToUnits[index] != unitCount) { uint unitCountDifference = unitCount - indexToUnits[--index]; - MemoryNodes[unitCountDifference - 1].Insert(memoryNode0 + (unitCount - unitCountDifference), unitCountDifference); + MemoryNodes[unitCountDifference - 1].Insert(memoryNode0 + (unitCount - unitCountDifference), + unitCountDifference); } MemoryNodes[index].Insert(memoryNode0, indexToUnits[index]); @@ -454,4 +455,4 @@ namespace SharpCompress.Compressor.PPMd.I1 #endregion } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/I1/Coder.cs b/SharpCompress/Compressor/PPMd/I1/Coder.cs index cdff6ef4..005bb08e 100644 --- a/SharpCompress/Compressor/PPMd/I1/Coder.cs +++ b/SharpCompress/Compressor/PPMd/I1/Coder.cs @@ -34,7 +34,8 @@ namespace SharpCompress.Compressor.PPMd.I1 public void RangeEncoderNormalize(Stream stream) { - while ((low ^ (low + range)) < RangeTop || range < RangeBottom && ((range = (uint) -low & (RangeBottom - 1)) != 0 || true)) + while ((low ^ (low + range)) < RangeTop || + range < RangeBottom && ((range = (uint) -low & (RangeBottom - 1)) != 0 || true)) { stream.WriteByte((byte) (low >> 24)); range <<= 8; @@ -44,13 +45,13 @@ namespace SharpCompress.Compressor.PPMd.I1 public void RangeEncodeSymbol() { - low += LowCount * (range /= Scale); + low += LowCount*(range /= Scale); range *= HighCount - LowCount; } public void RangeShiftEncodeSymbol(int rangeShift) { - low += LowCount * (range >>= rangeShift); + low += LowCount*(range >>= rangeShift); range *= HighCount - LowCount; } @@ -74,7 +75,8 @@ namespace SharpCompress.Compressor.PPMd.I1 public void RangeDecoderNormalize(Stream stream) { - while ((low ^ (low + range)) < RangeTop || range < RangeBottom && ((range = (uint) -low & (RangeBottom - 1)) != 0 || true)) + while ((low ^ (low + range)) < RangeTop || + range < RangeBottom && ((range = (uint) -low & (RangeBottom - 1)) != 0 || true)) { code = (code << 8) | (byte) stream.ReadByte(); range <<= 8; @@ -84,18 +86,18 @@ namespace SharpCompress.Compressor.PPMd.I1 public uint RangeGetCurrentCount() { - return (code - low) / (range /= Scale); + return (code - low)/(range /= Scale); } public uint RangeGetCurrentShiftCount(int rangeShift) { - return (code - low) / (range >>= rangeShift); + return (code - low)/(range >>= rangeShift); } public void RangeRemoveSubrange() { - low += range * LowCount; + low += range*LowCount; range *= HighCount - LowCount; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/I1/MemoryNode.cs b/SharpCompress/Compressor/PPMd/I1/MemoryNode.cs index 44ca2777..7bb99f2b 100644 --- a/SharpCompress/Compressor/PPMd/I1/MemoryNode.cs +++ b/SharpCompress/Compressor/PPMd/I1/MemoryNode.cs @@ -48,7 +48,11 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public uint Stamp { - get { return ((uint) Memory[Address]) | ((uint) Memory[Address + 1]) << 8 | ((uint) Memory[Address + 2]) << 16 | ((uint) Memory[Address + 3]) << 24; } + get + { + return ((uint) Memory[Address]) | ((uint) Memory[Address + 1]) << 8 | ((uint) Memory[Address + 2]) << 16 | + ((uint) Memory[Address + 3]) << 24; + } set { Memory[Address] = (byte) value; @@ -63,7 +67,13 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public MemoryNode Next { - get { return new MemoryNode(((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); } + get + { + return + new MemoryNode( + ((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | + ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); + } set { Memory[Address + 4] = (byte) value.Address; @@ -78,7 +88,11 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public uint UnitCount { - get { return ((uint) Memory[Address + 8]) | ((uint) Memory[Address + 9]) << 8 | ((uint) Memory[Address + 10]) << 16 | ((uint) Memory[Address + 11]) << 24; } + get + { + return ((uint) Memory[Address + 8]) | ((uint) Memory[Address + 9]) << 8 | + ((uint) Memory[Address + 10]) << 16 | ((uint) Memory[Address + 11]) << 24; + } set { Memory[Address + 8] = (byte) value; @@ -157,7 +171,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static MemoryNode operator +(MemoryNode memoryNode, int offset) { - memoryNode.Address = (uint) (memoryNode.Address + offset * Size); + memoryNode.Address = (uint) (memoryNode.Address + offset*Size); return memoryNode; } @@ -169,7 +183,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static MemoryNode operator +(MemoryNode memoryNode, uint offset) { - memoryNode.Address += offset * Size; + memoryNode.Address += offset*Size; return memoryNode; } @@ -181,7 +195,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static MemoryNode operator -(MemoryNode memoryNode, int offset) { - memoryNode.Address = (uint) (memoryNode.Address - offset * Size); + memoryNode.Address = (uint) (memoryNode.Address - offset*Size); return memoryNode; } @@ -193,7 +207,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static MemoryNode operator -(MemoryNode memoryNode, uint offset) { - memoryNode.Address -= offset * Size; + memoryNode.Address -= offset*Size; return memoryNode; } @@ -243,4 +257,4 @@ namespace SharpCompress.Compressor.PPMd.I1 return Address.GetHashCode(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/I1/Model.cs b/SharpCompress/Compressor/PPMd/I1/Model.cs index c3efbcf4..0b536b7b 100644 --- a/SharpCompress/Compressor/PPMd/I1/Model.cs +++ b/SharpCompress/Compressor/PPMd/I1/Model.cs @@ -7,6 +7,7 @@ using System.IO; // This is a port of Dmitry Shkarin's PPMd Variant I Revision 1. // Ported by Michael Bone (mjbone03@yahoo.com.au). + namespace SharpCompress.Compressor.PPMd.I1 { /// @@ -16,7 +17,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { public const uint Signature = 0x84acaf8fU; public const char Variant = 'I'; - public const int MaximumOrder = 16; // maximum allowed model order + public const int MaximumOrder = 16; // maximum allowed model order private const byte UpperFrequency = 5; private const byte IntervalBitCount = 7; @@ -30,7 +31,7 @@ namespace SharpCompress.Compressor.PPMd.I1 private See2Context[,] see2Contexts; private See2Context emptySee2Context; private PpmContext maximumContext; - private ushort[,] binarySummary = new ushort[25, 64]; // binary SEE-contexts + private ushort[,] binarySummary = new ushort[25,64]; // binary SEE-contexts private byte[] numberStatisticsToBinarySummaryIndex = new byte[256]; private byte[] probabilities = new byte[260]; private byte[] characterMask = new byte[256]; @@ -43,7 +44,7 @@ namespace SharpCompress.Compressor.PPMd.I1 private byte previousSuccess; private byte numberMasked; private ModelRestorationMethod method; - private PpmState foundState; // found next state transition + private PpmState foundState; // found next state transition private Allocator Allocator; private Coder Coder; @@ -51,8 +52,13 @@ namespace SharpCompress.Compressor.PPMd.I1 private byte numberStatistics; private PpmState[] decodeStates = new PpmState[256]; - private static readonly ushort[] InitialBinaryEscapes = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051 }; - private static readonly byte[] ExponentialEscapes = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; + private static readonly ushort[] InitialBinaryEscapes = + { + 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, + 0x6051 + }; + + private static readonly byte[] ExponentialEscapes = {25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2}; #region Public Methods @@ -69,12 +75,12 @@ namespace SharpCompress.Compressor.PPMd.I1 // 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 // 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 - numberStatisticsToBinarySummaryIndex[0] = 2 * 0; - numberStatisticsToBinarySummaryIndex[1] = 2 * 1; + numberStatisticsToBinarySummaryIndex[0] = 2*0; + numberStatisticsToBinarySummaryIndex[1] = 2*1; for (int index = 2; index < 11; index++) - numberStatisticsToBinarySummaryIndex[index] = 2 * 2; + numberStatisticsToBinarySummaryIndex[index] = 2*2; for (int index = 11; index < 256; index++) - numberStatisticsToBinarySummaryIndex[index] = 2 * 3; + numberStatisticsToBinarySummaryIndex[index] = 2*3; // Construct the probability table. Initially it will contain the following values (depending on the value of // the upper frequency). @@ -94,11 +100,11 @@ namespace SharpCompress.Compressor.PPMd.I1 uint probability = UpperFrequency; for (int index = 0; index < UpperFrequency; index++) - probabilities[index] = (byte)index; + probabilities[index] = (byte) index; for (int index = UpperFrequency; index < 260; index++) { - probabilities[index] = (byte)probability; + probabilities[index] = (byte) probability; count--; if (count == 0) { @@ -110,7 +116,7 @@ namespace SharpCompress.Compressor.PPMd.I1 // Create the context array. - see2Contexts = new See2Context[24, 32]; + see2Contexts = new See2Context[24,32]; for (int index1 = 0; index1 < 24; index1++) for (int index2 = 0; index2 < 32; index2++) see2Contexts[index1, index2] = new See2Context(); @@ -118,9 +124,9 @@ namespace SharpCompress.Compressor.PPMd.I1 // Set the signature (identifying the algorithm). emptySee2Context = new See2Context(); - emptySee2Context.Summary = (ushort)(Signature & 0x0000ffff); - emptySee2Context.Shift = (byte)((Signature >> 16) & 0x000000ff); - emptySee2Context.Count = (byte)(Signature >> 24); + emptySee2Context.Summary = (ushort) (Signature & 0x0000ffff); + emptySee2Context.Shift = (byte) ((Signature >> 16) & 0x000000ff); + emptySee2Context.Count = (byte) (Signature >> 24); } /// @@ -183,7 +189,7 @@ namespace SharpCompress.Compressor.PPMd.I1 Coder.RangeEncodeSymbol(); } - if (orderFall == 0 && (Pointer)foundState.Successor >= Allocator.BaseUnit) + if (orderFall == 0 && (Pointer) foundState.Successor >= Allocator.BaseUnit) { maximumContext = foundState.Successor; } @@ -197,7 +203,7 @@ namespace SharpCompress.Compressor.PPMd.I1 Coder.RangeEncoderNormalize(target); } - StopEncoding: + StopEncoding: Coder.RangeEncoderFlush(target); } @@ -266,7 +272,7 @@ namespace SharpCompress.Compressor.PPMd.I1 offset++; total++; - if (orderFall == 0 && (Pointer)foundState.Successor >= Allocator.BaseUnit) + if (orderFall == 0 && (Pointer) foundState.Successor >= Allocator.BaseUnit) { maximumContext = foundState.Successor; } @@ -282,7 +288,7 @@ namespace SharpCompress.Compressor.PPMd.I1 Coder.RangeDecoderNormalize(source); } - StopDecoding: + StopDecoding: return total; } @@ -322,14 +328,15 @@ namespace SharpCompress.Compressor.PPMd.I1 maximumContext = Allocator.AllocateContext(); maximumContext.Suffix = PpmContext.Zero; maximumContext.NumberStatistics = 255; - maximumContext.SummaryFrequency = (ushort)(maximumContext.NumberStatistics + 2); - maximumContext.Statistics = Allocator.AllocateUnits(256 / 2); // allocates enough space for 256 PPM states (each is 6 bytes) + maximumContext.SummaryFrequency = (ushort) (maximumContext.NumberStatistics + 2); + maximumContext.Statistics = Allocator.AllocateUnits(256/2); + // allocates enough space for 256 PPM states (each is 6 bytes) previousSuccess = 0; for (int index = 0; index < 256; index++) { PpmState state = maximumContext.Statistics[index]; - state.Symbol = (byte)index; + state.Symbol = (byte) index; state.Frequency = 1; state.Successor = PpmContext.Zero; } @@ -340,7 +347,8 @@ namespace SharpCompress.Compressor.PPMd.I1 while (probabilities[index1] == probability) index1++; for (int index2 = 0; index2 < 8; index2++) - binarySummary[probability, index2] = (ushort)(BinaryScale - InitialBinaryEscapes[index2] / (index1 + 1)); + binarySummary[probability, index2] = + (ushort) (BinaryScale - InitialBinaryEscapes[index2]/(index1 + 1)); for (int index2 = 8; index2 < 64; index2 += 8) for (int index3 = 0; index3 < 8; index3++) binarySummary[probability, index2 + index3] = binarySummary[probability, index3]; @@ -352,7 +360,7 @@ namespace SharpCompress.Compressor.PPMd.I1 while (probabilities[index1 + 3] == probability + 3) index1++; for (int index2 = 0; index2 < 32; index2++) - see2Contexts[probability, index2].Initialize(2 * index1 + 5); + see2Contexts[probability, index2].Initialize(2*index1 + 5); } } @@ -374,7 +382,7 @@ namespace SharpCompress.Compressor.PPMd.I1 PpmContext foundStateSuccessor = foundState.Successor; PpmContext context = minimumContext.Suffix; - if ((foundStateFrequency < MaximumFrequency / 4) && (context != PpmContext.Zero)) + if ((foundStateFrequency < MaximumFrequency/4) && (context != PpmContext.Zero)) { if (context.NumberStatistics != 0) { @@ -392,14 +400,14 @@ namespace SharpCompress.Compressor.PPMd.I1 state--; } } - cf = (uint)((state.Frequency < MaximumFrequency - 9) ? 2 : 0); - state.Frequency += (byte)cf; - context.SummaryFrequency += (byte)cf; + cf = (uint) ((state.Frequency < MaximumFrequency - 9) ? 2 : 0); + state.Frequency += (byte) cf; + context.SummaryFrequency += (byte) cf; } else { state = context.FirstState; - state.Frequency += (byte)((state.Frequency < 32) ? 1 : 0); + state.Frequency += (byte) ((state.Frequency < 32) ? 1 : 0); } } @@ -446,7 +454,7 @@ namespace SharpCompress.Compressor.PPMd.I1 numberStatistics = minimumContext.NumberStatistics; s0 = minimumContext.SummaryFrequency - numberStatistics - foundStateFrequency; - flag = (byte)((foundStateSymbol >= 0x40) ? 0x08 : 0x00); + flag = (byte) ((foundStateSymbol >= 0x40) ? 0x08 : 0x00); for (; currentContext != minimumContext; currentContext = currentContext.Suffix) { ns1 = currentContext.NumberStatistics; @@ -459,7 +467,7 @@ namespace SharpCompress.Compressor.PPMd.I1 goto RestartModel; currentContext.Statistics = state; } - currentContext.SummaryFrequency += (ushort)((3 * ns1 + 1 < numberStatistics) ? 1 : 0); + currentContext.SummaryFrequency += (ushort) ((3*ns1 + 1 < numberStatistics) ? 1 : 0); } else { @@ -468,38 +476,39 @@ namespace SharpCompress.Compressor.PPMd.I1 goto RestartModel; Copy(state, currentContext.FirstState); currentContext.Statistics = state; - if (state.Frequency < MaximumFrequency / 4 - 1) + if (state.Frequency < MaximumFrequency/4 - 1) state.Frequency += state.Frequency; else - state.Frequency = (byte)(MaximumFrequency - 4); - currentContext.SummaryFrequency = (ushort)(state.Frequency + initialEscape + ((numberStatistics > 2) ? 1 : 0)); + state.Frequency = (byte) (MaximumFrequency - 4); + currentContext.SummaryFrequency = + (ushort) (state.Frequency + initialEscape + ((numberStatistics > 2) ? 1 : 0)); } - cf = (uint)(2 * foundStateFrequency * (currentContext.SummaryFrequency + 6)); + cf = (uint) (2*foundStateFrequency*(currentContext.SummaryFrequency + 6)); sf = s0 + currentContext.SummaryFrequency; - if (cf < 6 * sf) + if (cf < 6*sf) { - cf = (uint)(1 + ((cf > sf) ? 1 : 0) + ((cf >= 4 * sf) ? 1 : 0)); + cf = (uint) (1 + ((cf > sf) ? 1 : 0) + ((cf >= 4*sf) ? 1 : 0)); currentContext.SummaryFrequency += 4; } else { - cf = (uint)(4 + ((cf > 9 * sf) ? 1 : 0) + ((cf > 12 * sf) ? 1 : 0) + ((cf > 15 * sf) ? 1 : 0)); - currentContext.SummaryFrequency += (ushort)cf; + cf = (uint) (4 + ((cf > 9*sf) ? 1 : 0) + ((cf > 12*sf) ? 1 : 0) + ((cf > 15*sf) ? 1 : 0)); + currentContext.SummaryFrequency += (ushort) cf; } state = currentContext.Statistics + (++currentContext.NumberStatistics); state.Successor = Successor; state.Symbol = foundStateSymbol; - state.Frequency = (byte)cf; + state.Frequency = (byte) cf; currentContext.Flags |= flag; } maximumContext = foundStateSuccessor; return; - RestartModel: + RestartModel: RestoreModel(currentContext, minimumContext, foundStateSuccessor); } @@ -545,17 +554,18 @@ namespace SharpCompress.Compressor.PPMd.I1 state++; } while (temporary != symbol); } - temporary = (byte)((state.Frequency < MaximumFrequency - 9) ? 1 : 0); + temporary = (byte) ((state.Frequency < MaximumFrequency - 9) ? 1 : 0); state.Frequency += temporary; context.SummaryFrequency += temporary; } else { state = context.FirstState; - state.Frequency += (byte)(((context.Suffix.NumberStatistics == 0) ? 1 : 0) & ((state.Frequency < 24) ? 1 : 0)); + state.Frequency += + (byte) (((context.Suffix.NumberStatistics == 0) ? 1 : 0) & ((state.Frequency < 24) ? 1 : 0)); } - LoopEntry: + LoopEntry: if (state.Successor != upBranch) { context = state.Successor; @@ -564,17 +574,17 @@ namespace SharpCompress.Compressor.PPMd.I1 states[stateIndex++] = state; } while (context.Suffix != PpmContext.Zero); - NoLoop: + NoLoop: if (stateIndex == 0) return context; byte localNumberStatistics = 0; - byte localFlags = (byte)((symbol >= 0x40) ? 0x10 : 0x00); + byte localFlags = (byte) ((symbol >= 0x40) ? 0x10 : 0x00); symbol = upBranch.NumberStatistics; byte localSymbol = symbol; byte localFrequency; - PpmContext localSuccessor = ((Pointer)upBranch) + 1; - localFlags |= (byte)((symbol >= 0x40) ? 0x08 : 0x00); + PpmContext localSuccessor = ((Pointer) upBranch) + 1; + localFlags |= (byte) ((symbol >= 0x40) ? 0x08 : 0x00); if (context.NumberStatistics != 0) { @@ -588,9 +598,9 @@ namespace SharpCompress.Compressor.PPMd.I1 state++; } while (temporary != symbol); } - uint cf = (uint)(state.Frequency - 1); - uint s0 = (uint)(context.SummaryFrequency - context.NumberStatistics - cf); - localFrequency = (byte)(1 + ((2 * cf <= s0) ? (uint)((5 * cf > s0) ? 1 : 0) : ((cf + 2 * s0 - 3) / s0))); + uint cf = (uint) (state.Frequency - 1); + uint s0 = (uint) (context.SummaryFrequency - context.NumberStatistics - cf); + localFrequency = (byte) (1 + ((2*cf <= s0) ? (uint) ((5*cf > s0) ? 1 : 0) : ((cf + 2*s0 - 3)/s0))); } else { @@ -670,17 +680,17 @@ namespace SharpCompress.Compressor.PPMd.I1 state++; } while (temporary != symbol); } - temporary = (byte)((state.Frequency < MaximumFrequency - 9) ? 2 : 0); + temporary = (byte) ((state.Frequency < MaximumFrequency - 9) ? 2 : 0); state.Frequency += temporary; context.SummaryFrequency += temporary; } else { state = context.FirstState; - state.Frequency += (byte)((state.Frequency < 32) ? 1 : 0); + state.Frequency += (byte) ((state.Frequency < 32) ? 1 : 0); } - LoopEntry: + LoopEntry: if (state.Successor != PpmContext.Zero) break; states[stateIndex++] = state; @@ -725,30 +735,32 @@ namespace SharpCompress.Compressor.PPMd.I1 { if (--currentContext.NumberStatistics == 0) { - currentContext.Flags = (byte)((currentContext.Flags & 0x10) + ((currentContext.Statistics.Symbol >= 0x40) ? 0x08 : 0x00)); + currentContext.Flags = + (byte) + ((currentContext.Flags & 0x10) + ((currentContext.Statistics.Symbol >= 0x40) ? 0x08 : 0x00)); PpmState state = currentContext.Statistics; Copy(currentContext.FirstState, state); Allocator.SpecialFreeUnits(state); - currentContext.FirstStateFrequency = (byte)((currentContext.FirstStateFrequency + 11) >> 3); + currentContext.FirstStateFrequency = (byte) ((currentContext.FirstStateFrequency + 11) >> 3); } else { - Refresh((uint)((currentContext.NumberStatistics + 3) >> 1), false, currentContext); + Refresh((uint) ((currentContext.NumberStatistics + 3) >> 1), false, currentContext); } } for (; currentContext != minimumContext; currentContext = currentContext.Suffix) { if (currentContext.NumberStatistics == 0) - currentContext.FirstStateFrequency -= (byte)(currentContext.FirstStateFrequency >> 1); - else if ((currentContext.SummaryFrequency += 4) > 128 + 4 * currentContext.NumberStatistics) - Refresh((uint)((currentContext.NumberStatistics + 2) >> 1), true, currentContext); + currentContext.FirstStateFrequency -= (byte) (currentContext.FirstStateFrequency >> 1); + else if ((currentContext.SummaryFrequency += 4) > 128 + 4*currentContext.NumberStatistics) + Refresh((uint) ((currentContext.NumberStatistics + 2) >> 1), true, currentContext); } if (method > ModelRestorationMethod.Freeze) { maximumContext = foundStateSuccessor; - Allocator.GlueCount += (uint)(((Allocator.MemoryNodes[1].Stamp & 1) == 0) ? 1 : 0); + Allocator.GlueCount += (uint) (((Allocator.MemoryNodes[1].Stamp & 1) == 0) ? 1 : 0); } else if (method == ModelRestorationMethod.Freeze) { @@ -756,11 +768,12 @@ namespace SharpCompress.Compressor.PPMd.I1 maximumContext = maximumContext.Suffix; RemoveBinaryContexts(0, maximumContext); - method = (ModelRestorationMethod)(method + 1); + method = (ModelRestorationMethod) (method + 1); Allocator.GlueCount = 0; orderFall = modelOrder; } - else if (method == ModelRestorationMethod.Restart || Allocator.GetMemoryUsed() < (Allocator.AllocatorSize >> 1)) + else if (method == ModelRestorationMethod.Restart || + Allocator.GetMemoryUsed() < (Allocator.AllocatorSize >> 1)) { StartModel(modelOrder, method); escapeCount = 0; @@ -774,7 +787,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { CutOff(0, maximumContext); Allocator.ExpandText(); - } while (Allocator.GetMemoryUsed() > 3 * (Allocator.AllocatorSize >> 2)); + } while (Allocator.GetMemoryUsed() > 3*(Allocator.AllocatorSize >> 2)); Allocator.GlueCount = 0; orderFall = modelOrder; @@ -816,4 +829,4 @@ namespace SharpCompress.Compressor.PPMd.I1 #endregion } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/I1/ModelRestorationMethod.cs b/SharpCompress/Compressor/PPMd/I1/ModelRestorationMethod.cs index 2bb8af30..c0c2a2fb 100644 --- a/SharpCompress/Compressor/PPMd/I1/ModelRestorationMethod.cs +++ b/SharpCompress/Compressor/PPMd/I1/ModelRestorationMethod.cs @@ -26,4 +26,4 @@ namespace SharpCompress.Compressor.PPMd.I1 /// Freeze = 2 } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/I1/Pointer.cs b/SharpCompress/Compressor/PPMd/I1/Pointer.cs index 4944d971..2e696484 100644 --- a/SharpCompress/Compressor/PPMd/I1/Pointer.cs +++ b/SharpCompress/Compressor/PPMd/I1/Pointer.cs @@ -45,18 +45,18 @@ namespace SharpCompress.Compressor.PPMd.I1 { get { - #if DEBUG +#if DEBUG if (Address == 0) throw new InvalidOperationException("The pointer being indexed is a null pointer."); - #endif +#endif return Memory[Address + offset]; } set { - #if DEBUG +#if DEBUG if (Address == 0) throw new InvalidOperationException("The pointer being indexed is a null pointer."); - #endif +#endif Memory[Address + offset] = value; } } @@ -99,10 +99,10 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static Pointer operator +(Pointer pointer, int offset) { - #if DEBUG +#if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer is a null pointer."); - #endif +#endif pointer.Address = (uint) (pointer.Address + offset); return pointer; } @@ -115,10 +115,10 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static Pointer operator +(Pointer pointer, uint offset) { - #if DEBUG +#if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer is a null pointer."); - #endif +#endif pointer.Address += offset; return pointer; } @@ -130,10 +130,10 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static Pointer operator ++(Pointer pointer) { - #if DEBUG +#if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer being incremented is a null pointer."); - #endif +#endif pointer.Address++; return pointer; } @@ -146,10 +146,10 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static Pointer operator -(Pointer pointer, int offset) { - #if DEBUG +#if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer is a null pointer."); - #endif +#endif pointer.Address = (uint) (pointer.Address - offset); return pointer; } @@ -162,10 +162,10 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static Pointer operator -(Pointer pointer, uint offset) { - #if DEBUG +#if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer is a null pointer."); - #endif +#endif pointer.Address -= offset; return pointer; } @@ -177,10 +177,10 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static Pointer operator --(Pointer pointer) { - #if DEBUG +#if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer being decremented is a null pointer."); - #endif +#endif pointer.Address--; return pointer; } @@ -193,12 +193,14 @@ namespace SharpCompress.Compressor.PPMd.I1 /// The number of bytes between the two pointers. public static uint operator -(Pointer pointer1, Pointer pointer2) { - #if DEBUG +#if DEBUG if (pointer1.Address == 0) - throw new InvalidOperationException("The pointer to the left of the subtraction operator is a null pointer."); + throw new InvalidOperationException( + "The pointer to the left of the subtraction operator is a null pointer."); if (pointer2.Address == 0) - throw new InvalidOperationException("The pointer to the right of the subtraction operator is a null pointer."); - #endif + throw new InvalidOperationException( + "The pointer to the right of the subtraction operator is a null pointer."); +#endif return pointer1.Address - pointer2.Address; } @@ -210,12 +212,14 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static bool operator <(Pointer pointer1, Pointer pointer2) { - #if DEBUG +#if DEBUG if (pointer1.Address == 0) - throw new InvalidOperationException("The pointer to the left of the less than operator is a null pointer."); + throw new InvalidOperationException( + "The pointer to the left of the less than operator is a null pointer."); if (pointer2.Address == 0) - throw new InvalidOperationException("The pointer to the right of the less than operator is a null pointer."); - #endif + throw new InvalidOperationException( + "The pointer to the right of the less than operator is a null pointer."); +#endif return pointer1.Address < pointer2.Address; } @@ -227,12 +231,14 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static bool operator <=(Pointer pointer1, Pointer pointer2) { - #if DEBUG +#if DEBUG if (pointer1.Address == 0) - throw new InvalidOperationException("The pointer to the left of the less than or equal to operator is a null pointer."); + throw new InvalidOperationException( + "The pointer to the left of the less than or equal to operator is a null pointer."); if (pointer2.Address == 0) - throw new InvalidOperationException("The pointer to the right of the less than or equal to operator is a null pointer."); - #endif + throw new InvalidOperationException( + "The pointer to the right of the less than or equal to operator is a null pointer."); +#endif return pointer1.Address <= pointer2.Address; } @@ -244,12 +250,14 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static bool operator >(Pointer pointer1, Pointer pointer2) { - #if DEBUG +#if DEBUG if (pointer1.Address == 0) - throw new InvalidOperationException("The pointer to the left of the greater than operator is a null pointer."); + throw new InvalidOperationException( + "The pointer to the left of the greater than operator is a null pointer."); if (pointer2.Address == 0) - throw new InvalidOperationException("The pointer to the right of the greater than operator is a null pointer."); - #endif + throw new InvalidOperationException( + "The pointer to the right of the greater than operator is a null pointer."); +#endif return pointer1.Address > pointer2.Address; } @@ -261,12 +269,14 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static bool operator >=(Pointer pointer1, Pointer pointer2) { - #if DEBUG +#if DEBUG if (pointer1.Address == 0) - throw new InvalidOperationException("The pointer to the left of the greater than or equal to operator is a null pointer."); + throw new InvalidOperationException( + "The pointer to the left of the greater than or equal to operator is a null pointer."); if (pointer2.Address == 0) - throw new InvalidOperationException("The pointer to the right of the greater than or equal to operator is a null pointer."); - #endif + throw new InvalidOperationException( + "The pointer to the right of the greater than or equal to operator is a null pointer."); +#endif return pointer1.Address >= pointer2.Address; } @@ -316,4 +326,4 @@ namespace SharpCompress.Compressor.PPMd.I1 return Address.GetHashCode(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/I1/PpmContext.cs b/SharpCompress/Compressor/PPMd/I1/PpmContext.cs index 72d4c431..3c9e3bb4 100644 --- a/SharpCompress/Compressor/PPMd/I1/PpmContext.cs +++ b/SharpCompress/Compressor/PPMd/I1/PpmContext.cs @@ -1,7 +1,5 @@ #region Using - - #endregion namespace SharpCompress.Compressor.PPMd.I1 @@ -60,11 +58,11 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public ushort SummaryFrequency { - get { return (ushort)(((ushort)Memory[Address + 2]) | ((ushort)Memory[Address + 3]) << 8); } + get { return (ushort) (((ushort) Memory[Address + 2]) | ((ushort) Memory[Address + 3]) << 8); } set { - Memory[Address + 2] = (byte)value; - Memory[Address + 3] = (byte)(value >> 8); + Memory[Address + 2] = (byte) value; + Memory[Address + 3] = (byte) (value >> 8); } } @@ -73,13 +71,19 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public PpmState Statistics { - get { return new PpmState(((uint)Memory[Address + 4]) | ((uint)Memory[Address + 5]) << 8 | ((uint)Memory[Address + 6]) << 16 | ((uint)Memory[Address + 7]) << 24, Memory); } + get + { + return + new PpmState( + ((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | + ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); + } set { - Memory[Address + 4] = (byte)value.Address; - Memory[Address + 5] = (byte)(value.Address >> 8); - Memory[Address + 6] = (byte)(value.Address >> 16); - Memory[Address + 7] = (byte)(value.Address >> 24); + Memory[Address + 4] = (byte) value.Address; + Memory[Address + 5] = (byte) (value.Address >> 8); + Memory[Address + 6] = (byte) (value.Address >> 16); + Memory[Address + 7] = (byte) (value.Address >> 24); } } @@ -88,13 +92,19 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public PpmContext Suffix { - get { return new PpmContext(((uint)Memory[Address + 8]) | ((uint)Memory[Address + 9]) << 8 | ((uint)Memory[Address + 10]) << 16 | ((uint)Memory[Address + 11]) << 24, Memory); } + get + { + return + new PpmContext( + ((uint) Memory[Address + 8]) | ((uint) Memory[Address + 9]) << 8 | + ((uint) Memory[Address + 10]) << 16 | ((uint) Memory[Address + 11]) << 24, Memory); + } set { - Memory[Address + 8] = (byte)value.Address; - Memory[Address + 9] = (byte)(value.Address >> 8); - Memory[Address + 10] = (byte)(value.Address >> 16); - Memory[Address + 11] = (byte)(value.Address >> 24); + Memory[Address + 8] = (byte) value.Address; + Memory[Address + 9] = (byte) (value.Address >> 8); + Memory[Address + 10] = (byte) (value.Address >> 16); + Memory[Address + 11] = (byte) (value.Address >> 24); } } @@ -133,7 +143,8 @@ namespace SharpCompress.Compressor.PPMd.I1 /// information can be obtained using the Symbol property on the PPM state provided by the /// property. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The property getter is provided for completeness.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", + Justification = "The property getter is provided for completeness.")] public byte FirstStateSymbol { get { return Memory[Address + 2]; } @@ -155,16 +166,23 @@ namespace SharpCompress.Compressor.PPMd.I1 /// Gets or sets the successor of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Successor property on the PPM state provided by the /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "The property getter is provided for completeness.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", + Justification = "The property getter is provided for completeness.")] public PpmContext FirstStateSuccessor { - get { return new PpmContext(((uint)Memory[Address + 4]) | ((uint)Memory[Address + 5]) << 8 | ((uint)Memory[Address + 6]) << 16 | ((uint)Memory[Address + 7]) << 24, Memory); } + get + { + return + new PpmContext( + ((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | + ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); + } set { - Memory[Address + 4] = (byte)value.Address; - Memory[Address + 5] = (byte)(value.Address >> 8); - Memory[Address + 6] = (byte)(value.Address >> 16); - Memory[Address + 7] = (byte)(value.Address >> 24); + Memory[Address + 4] = (byte) value.Address; + Memory[Address + 5] = (byte) (value.Address >> 8); + Memory[Address + 6] = (byte) (value.Address >> 16); + Memory[Address + 7] = (byte) (value.Address >> 24); } } @@ -186,7 +204,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static PpmContext operator +(PpmContext context, int offset) { - context.Address = (uint)(context.Address + offset * Size); + context.Address = (uint) (context.Address + offset*Size); return context; } @@ -198,7 +216,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static PpmContext operator -(PpmContext context, int offset) { - context.Address = (uint)(context.Address - offset * Size); + context.Address = (uint) (context.Address - offset*Size); return context; } @@ -255,7 +273,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { if (obj is PpmContext) { - PpmContext context = (PpmContext)obj; + PpmContext context = (PpmContext) obj; return context.Address == Address; } return base.Equals(obj); @@ -275,22 +293,24 @@ namespace SharpCompress.Compressor.PPMd.I1 { PpmState state = context.FirstState; int index1 = probabilities[state.Frequency - 1]; - int index2 = numberStatisticsToBinarySummaryIndex[context.Suffix.NumberStatistics] + previousSuccess + context.Flags + ((runLength >> 26) & 0x20); + int index2 = numberStatisticsToBinarySummaryIndex[context.Suffix.NumberStatistics] + previousSuccess + + context.Flags + ((runLength >> 26) & 0x20); if (state.Symbol == symbol) { foundState = state; - state.Frequency += (byte)((state.Frequency < 196) ? 1 : 0); + state.Frequency += (byte) ((state.Frequency < 196) ? 1 : 0); Coder.LowCount = 0; Coder.HighCount = binarySummary[index1, index2]; - binarySummary[index1, index2] += (ushort)(Interval - Mean(binarySummary[index1, index2], PeriodBitCount, 2)); + binarySummary[index1, index2] += + (ushort) (Interval - Mean(binarySummary[index1, index2], PeriodBitCount, 2)); previousSuccess = 1; runLength++; } else { Coder.LowCount = binarySummary[index1, index2]; - binarySummary[index1, index2] -= (ushort)Mean(binarySummary[index1, index2], PeriodBitCount, 2); + binarySummary[index1, index2] -= (ushort) Mean(binarySummary[index1, index2], PeriodBitCount, 2); Coder.HighCount = BinaryScale; initialEscape = ExponentialEscapes[binarySummary[index1, index2] >> 10]; characterMask[state.Symbol] = escapeCount; @@ -309,7 +329,7 @@ namespace SharpCompress.Compressor.PPMd.I1 if (index == symbol) { Coder.HighCount = state.Frequency; - previousSuccess = (byte)((2 * Coder.HighCount >= Coder.Scale) ? 1 : 0); + previousSuccess = (byte) ((2*Coder.HighCount >= Coder.Scale) ? 1 : 0); foundState = state; foundState.Frequency += 4; context.SummaryFrequency += 4; @@ -350,7 +370,7 @@ namespace SharpCompress.Compressor.PPMd.I1 See2Context see2Context = MakeEscapeFrequency(context); uint currentSymbol; uint lowCount = 0; - uint index = (uint)(context.NumberStatistics - numberMasked); + uint index = (uint) (context.NumberStatistics - numberMasked); PpmState state = context.Statistics - 1; do @@ -369,15 +389,15 @@ namespace SharpCompress.Compressor.PPMd.I1 Coder.LowCount = lowCount; Coder.Scale += Coder.LowCount; Coder.HighCount = Coder.Scale; - see2Context.Summary += (ushort)Coder.Scale; + see2Context.Summary += (ushort) Coder.Scale; numberMasked = context.NumberStatistics; return; - SymbolFound: + SymbolFound: Coder.LowCount = lowCount; lowCount += state.Frequency; Coder.HighCount = lowCount; - for (PpmState p1 = state; --index != 0; ) + for (PpmState p1 = state; --index != 0;) { do { @@ -395,22 +415,24 @@ namespace SharpCompress.Compressor.PPMd.I1 { PpmState state = context.FirstState; int index1 = probabilities[state.Frequency - 1]; - int index2 = numberStatisticsToBinarySummaryIndex[context.Suffix.NumberStatistics] + previousSuccess + context.Flags + ((runLength >> 26) & 0x20); + int index2 = numberStatisticsToBinarySummaryIndex[context.Suffix.NumberStatistics] + previousSuccess + + context.Flags + ((runLength >> 26) & 0x20); if (Coder.RangeGetCurrentShiftCount(TotalBitCount) < binarySummary[index1, index2]) { foundState = state; - state.Frequency += (byte)((state.Frequency < 196) ? 1 : 0); + state.Frequency += (byte) ((state.Frequency < 196) ? 1 : 0); Coder.LowCount = 0; Coder.HighCount = binarySummary[index1, index2]; - binarySummary[index1, index2] += (ushort)(Interval - Mean(binarySummary[index1, index2], PeriodBitCount, 2)); + binarySummary[index1, index2] += + (ushort) (Interval - Mean(binarySummary[index1, index2], PeriodBitCount, 2)); previousSuccess = 1; runLength++; } else { Coder.LowCount = binarySummary[index1, index2]; - binarySummary[index1, index2] -= (ushort)Mean(binarySummary[index1, index2], PeriodBitCount, 2); + binarySummary[index1, index2] -= (ushort) Mean(binarySummary[index1, index2], PeriodBitCount, 2); Coder.HighCount = BinaryScale; initialEscape = ExponentialEscapes[binarySummary[index1, index2] >> 10]; characterMask[state.Symbol] = escapeCount; @@ -432,10 +454,10 @@ namespace SharpCompress.Compressor.PPMd.I1 if (count < highCount) { Coder.HighCount = highCount; - previousSuccess = (byte)((2 * Coder.HighCount >= Coder.Scale) ? 1 : 0); + previousSuccess = (byte) ((2*Coder.HighCount >= Coder.Scale) ? 1 : 0); foundState = state; highCount += 4; - foundState.Frequency = (byte)highCount; + foundState.Frequency = (byte) highCount; context.SummaryFrequency += 4; runLength += previousSuccess; if (highCount > MaximumFrequency) @@ -474,7 +496,7 @@ namespace SharpCompress.Compressor.PPMd.I1 uint currentSymbol; uint count; uint highCount = 0; - uint index = (uint)(context.NumberStatistics - numberMasked); + uint index = (uint) (context.NumberStatistics - numberMasked); uint stateIndex = 0; PpmState state = context.Statistics - 1; @@ -486,7 +508,8 @@ namespace SharpCompress.Compressor.PPMd.I1 state++; } while (characterMask[currentSymbol] == escapeCount); highCount += state.Frequency; - decodeStates[stateIndex++] = state; // note that decodeStates is a static array that is re-used on each call to this method (for performance reasons) + decodeStates[stateIndex++] = state; + // note that decodeStates is a static array that is re-used on each call to this method (for performance reasons) } while (--index != 0); Coder.Scale += highCount; @@ -507,14 +530,14 @@ namespace SharpCompress.Compressor.PPMd.I1 { Coder.LowCount = highCount; Coder.HighCount = Coder.Scale; - index = (uint)(context.NumberStatistics - numberMasked); + index = (uint) (context.NumberStatistics - numberMasked); numberMasked = context.NumberStatistics; do { characterMask[decodeStates[stateIndex].Symbol] = escapeCount; stateIndex++; } while (--index != 0); - see2Context.Summary += (ushort)Coder.Scale; + see2Context.Summary += (ushort) Coder.Scale; } } @@ -545,7 +568,7 @@ namespace SharpCompress.Compressor.PPMd.I1 private See2Context MakeEscapeFrequency(PpmContext context) { - uint numberStatistics = (uint)2 * context.NumberStatistics; + uint numberStatistics = (uint) 2*context.NumberStatistics; See2Context see2Context; if (context.NumberStatistics != 0xff) @@ -555,7 +578,8 @@ namespace SharpCompress.Compressor.PPMd.I1 numberStatistics = context.Suffix.NumberStatistics; int index1 = probabilities[context.NumberStatistics + 2] - 3; - int index2 = ((context.SummaryFrequency > 11 * (context.NumberStatistics + 1)) ? 1 : 0) + ((2 * context.NumberStatistics < numberStatistics + numberMasked) ? 2 : 0) + context.Flags; + int index2 = ((context.SummaryFrequency > 11*(context.NumberStatistics + 1)) ? 1 : 0) + + ((2*context.NumberStatistics < numberStatistics + numberMasked) ? 2 : 0) + context.Flags; see2Context = see2Contexts[index1, index2]; Coder.Scale = see2Context.Mean(); } @@ -586,15 +610,15 @@ namespace SharpCompress.Compressor.PPMd.I1 state.Frequency += 4; context.SummaryFrequency += 4; - escapeFrequency = (uint)(context.SummaryFrequency - state.Frequency); + escapeFrequency = (uint) (context.SummaryFrequency - state.Frequency); adder = (orderFall != 0 || method > ModelRestorationMethod.Freeze) ? 1 : 0; - state.Frequency = (byte)((state.Frequency + adder) >> 1); + state.Frequency = (byte) ((state.Frequency + adder) >> 1); context.SummaryFrequency = state.Frequency; do { escapeFrequency -= (++state).Frequency; - state.Frequency = (byte)((state.Frequency + adder) >> 1); + state.Frequency = (byte) ((state.Frequency + adder) >> 1); context.SummaryFrequency += state.Frequency; if (state[0].Frequency > state[-1].Frequency) { @@ -620,38 +644,39 @@ namespace SharpCompress.Compressor.PPMd.I1 } while ((--state).Frequency == 0); escapeFrequency += index; - oldUnitCount = (uint)((context.NumberStatistics + 2) >> 1); - context.NumberStatistics -= (byte)index; + oldUnitCount = (uint) ((context.NumberStatistics + 2) >> 1); + context.NumberStatistics -= (byte) index; if (context.NumberStatistics == 0) { localSymbol = context.Statistics.Symbol; localFrequency = context.Statistics.Frequency; localSuccessor = context.Statistics.Successor; - localFrequency = (byte)((2 * localFrequency + escapeFrequency - 1) / escapeFrequency); - if (localFrequency > MaximumFrequency / 3) - localFrequency = (byte)(MaximumFrequency / 3); + localFrequency = (byte) ((2*localFrequency + escapeFrequency - 1)/escapeFrequency); + if (localFrequency > MaximumFrequency/3) + localFrequency = (byte) (MaximumFrequency/3); Allocator.FreeUnits(context.Statistics, oldUnitCount); context.FirstStateSymbol = localSymbol; context.FirstStateFrequency = localFrequency; context.FirstStateSuccessor = localSuccessor; - context.Flags = (byte)((context.Flags & 0x10) + ((localSymbol >= 0x40) ? 0x08 : 0x00)); + context.Flags = (byte) ((context.Flags & 0x10) + ((localSymbol >= 0x40) ? 0x08 : 0x00)); foundState = context.FirstState; return; } - context.Statistics = Allocator.ShrinkUnits(context.Statistics, oldUnitCount, (uint)((context.NumberStatistics + 2) >> 1)); + context.Statistics = Allocator.ShrinkUnits(context.Statistics, oldUnitCount, + (uint) ((context.NumberStatistics + 2) >> 1)); context.Flags &= 0xf7; index = context.NumberStatistics; state = context.Statistics; - context.Flags |= (byte)((state.Symbol >= 0x40) ? 0x08 : 0x00); + context.Flags |= (byte) ((state.Symbol >= 0x40) ? 0x08 : 0x00); do { - context.Flags |= (byte)(((++state).Symbol >= 0x40) ? 0x08 : 0x00); + context.Flags |= (byte) (((++state).Symbol >= 0x40) ? 0x08 : 0x00); } while (--index != 0); } escapeFrequency -= (escapeFrequency >> 1); - context.SummaryFrequency += (ushort)escapeFrequency; + context.SummaryFrequency += (ushort) escapeFrequency; context.Flags |= 0x04; foundState = context.Statistics; } @@ -662,23 +687,24 @@ namespace SharpCompress.Compressor.PPMd.I1 int escapeFrequency; int scaleValue = (scale ? 1 : 0); - context.Statistics = Allocator.ShrinkUnits(context.Statistics, oldUnitCount, (uint)((index + 2) >> 1)); + context.Statistics = Allocator.ShrinkUnits(context.Statistics, oldUnitCount, (uint) ((index + 2) >> 1)); PpmState statistics = context.Statistics; - context.Flags = (byte)((context.Flags & (0x10 + (scale ? 0x04 : 0x00))) + ((statistics.Symbol >= 0x40) ? 0x08 : 0x00)); + context.Flags = + (byte) ((context.Flags & (0x10 + (scale ? 0x04 : 0x00))) + ((statistics.Symbol >= 0x40) ? 0x08 : 0x00)); escapeFrequency = context.SummaryFrequency - statistics.Frequency; - statistics.Frequency = (byte)((statistics.Frequency + scaleValue) >> scaleValue); + statistics.Frequency = (byte) ((statistics.Frequency + scaleValue) >> scaleValue); context.SummaryFrequency = statistics.Frequency; do { escapeFrequency -= (++statistics).Frequency; - statistics.Frequency = (byte)((statistics.Frequency + scaleValue) >> scaleValue); + statistics.Frequency = (byte) ((statistics.Frequency + scaleValue) >> scaleValue); context.SummaryFrequency += statistics.Frequency; - context.Flags |= (byte)((statistics.Symbol >= 0x40) ? 0x08 : 0x00); + context.Flags |= (byte) ((statistics.Symbol >= 0x40) ? 0x08 : 0x00); } while (--index != 0); escapeFrequency = (escapeFrequency + scaleValue) >> scaleValue; - context.SummaryFrequency += (ushort)escapeFrequency; + context.SummaryFrequency += (ushort) escapeFrequency; } private PpmContext CutOff(int order, PpmContext context) @@ -689,7 +715,7 @@ namespace SharpCompress.Compressor.PPMd.I1 if (context.NumberStatistics == 0) { state = context.FirstState; - if ((Pointer)state.Successor >= Allocator.BaseUnit) + if ((Pointer) state.Successor >= Allocator.BaseUnit) { if (order < modelOrder) state.Successor = CutOff(order + 1, state.Successor); @@ -711,7 +737,7 @@ namespace SharpCompress.Compressor.PPMd.I1 } } - uint unitCount = (uint)((context.NumberStatistics + 2) >> 1); + uint unitCount = (uint) ((context.NumberStatistics + 2) >> 1); context.Statistics = Allocator.MoveUnitsUp(context.Statistics, unitCount); index = context.NumberStatistics; for (state = context.Statistics + index; state >= context.Statistics; state--) @@ -729,7 +755,7 @@ namespace SharpCompress.Compressor.PPMd.I1 if (index != context.NumberStatistics && order != 0) { - context.NumberStatistics = (byte)index; + context.NumberStatistics = (byte) index; state = context.Statistics; if (index < 0) { @@ -739,14 +765,14 @@ namespace SharpCompress.Compressor.PPMd.I1 } else if (index == 0) { - context.Flags = (byte)((context.Flags & 0x10) + ((state.Symbol >= 0x40) ? 0x08 : 0x00)); + context.Flags = (byte) ((context.Flags & 0x10) + ((state.Symbol >= 0x40) ? 0x08 : 0x00)); Copy(context.FirstState, state); Allocator.FreeUnits(state, unitCount); - context.FirstStateFrequency = (byte)((context.FirstStateFrequency + 11) >> 3); + context.FirstStateFrequency = (byte) ((context.FirstStateFrequency + 11) >> 3); } else { - Refresh(unitCount, context.SummaryFrequency > 16 * index, context); + Refresh(unitCount, context.SummaryFrequency > 16*index, context); } } @@ -758,11 +784,12 @@ namespace SharpCompress.Compressor.PPMd.I1 if (context.NumberStatistics == 0) { PpmState state = context.FirstState; - if ((Pointer)state.Successor >= Allocator.BaseUnit && order < modelOrder) + if ((Pointer) state.Successor >= Allocator.BaseUnit && order < modelOrder) state.Successor = RemoveBinaryContexts(order + 1, state.Successor); else state.Successor = PpmContext.Zero; - if ((state.Successor == PpmContext.Zero) && (context.Suffix.NumberStatistics == 0 || context.Suffix.Flags == 0xff)) + if ((state.Successor == PpmContext.Zero) && + (context.Suffix.NumberStatistics == 0 || context.Suffix.Flags == 0xff)) { Allocator.FreeUnits(context, 1); return PpmContext.Zero; @@ -775,7 +802,7 @@ namespace SharpCompress.Compressor.PPMd.I1 for (PpmState state = context.Statistics + context.NumberStatistics; state >= context.Statistics; state--) { - if ((Pointer)state.Successor >= Allocator.BaseUnit && order < modelOrder) + if ((Pointer) state.Successor >= Allocator.BaseUnit && order < modelOrder) state.Successor = RemoveBinaryContexts(order + 1, state.Successor); else state.Successor = PpmContext.Zero; @@ -784,4 +811,4 @@ namespace SharpCompress.Compressor.PPMd.I1 return context; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/I1/PpmState.cs b/SharpCompress/Compressor/PPMd/I1/PpmState.cs index 24895751..3ba2a936 100644 --- a/SharpCompress/Compressor/PPMd/I1/PpmState.cs +++ b/SharpCompress/Compressor/PPMd/I1/PpmState.cs @@ -58,7 +58,13 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public Model.PpmContext Successor { - get { return new Model.PpmContext(((uint) Memory[Address + 2]) | ((uint) Memory[Address + 3]) << 8 | ((uint) Memory[Address + 4]) << 16 | ((uint) Memory[Address + 5]) << 24, Memory); } + get + { + return + new Model.PpmContext( + ((uint) Memory[Address + 2]) | ((uint) Memory[Address + 3]) << 8 | + ((uint) Memory[Address + 4]) << 16 | ((uint) Memory[Address + 5]) << 24, Memory); + } set { Memory[Address + 2] = (byte) value.Address; @@ -76,7 +82,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public PpmState this[int offset] { - get { return new PpmState((uint) (Address + offset * Size), Memory); } + get { return new PpmState((uint) (Address + offset*Size), Memory); } } /// @@ -97,7 +103,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static PpmState operator +(PpmState state, int offset) { - state.Address = (uint) (state.Address + offset * Size); + state.Address = (uint) (state.Address + offset*Size); return state; } @@ -120,7 +126,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static PpmState operator -(PpmState state, int offset) { - state.Address = (uint) (state.Address - offset * Size); + state.Address = (uint) (state.Address - offset*Size); return state; } @@ -203,4 +209,4 @@ namespace SharpCompress.Compressor.PPMd.I1 return Address.GetHashCode(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/I1/See2Context.cs b/SharpCompress/Compressor/PPMd/I1/See2Context.cs index 5082141e..17685edd 100644 --- a/SharpCompress/Compressor/PPMd/I1/See2Context.cs +++ b/SharpCompress/Compressor/PPMd/I1/See2Context.cs @@ -52,4 +52,4 @@ namespace SharpCompress.Compressor.PPMd.I1 } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/PpmdProperties.cs b/SharpCompress/Compressor/PPMd/PpmdProperties.cs index 6328e6ae..9527835b 100644 --- a/SharpCompress/Compressor/PPMd/PpmdProperties.cs +++ b/SharpCompress/Compressor/PPMd/PpmdProperties.cs @@ -42,7 +42,7 @@ namespace SharpCompress.Compressor.PPMd ushort props = BitConverter.ToUInt16(properties, 0); AllocatorSize = (((props >> 4) & 0xff) + 1) << 20; ModelOrder = (props & 0x0f) + 1; - ModelRestorationMethod = (I1.ModelRestorationMethod)(props >> 12); + ModelRestorationMethod = (I1.ModelRestorationMethod) (props >> 12); } else if (properties.Length == 5) { @@ -54,10 +54,7 @@ namespace SharpCompress.Compressor.PPMd public int AllocatorSize { - get - { - return allocatorSize; - } + get { return allocatorSize; } set { allocatorSize = value; @@ -74,8 +71,11 @@ namespace SharpCompress.Compressor.PPMd { get { - return BitConverter.GetBytes((ushort)((ModelOrder - 1) + (((AllocatorSize >> 20) - 1) << 4) + ((ushort)ModelRestorationMethod << 12))); + return + BitConverter.GetBytes( + (ushort) + ((ModelOrder - 1) + (((AllocatorSize >> 20) - 1) << 4) + ((ushort) ModelRestorationMethod << 12))); } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/PPMd/PpmdStream.cs b/SharpCompress/Compressor/PPMd/PpmdStream.cs index 4fbb87fc..b6d6efe9 100644 --- a/SharpCompress/Compressor/PPMd/PpmdStream.cs +++ b/SharpCompress/Compressor/PPMd/PpmdStream.cs @@ -84,14 +84,8 @@ namespace SharpCompress.Compressor.PPMd public override long Position { - get - { - return position; - } - set - { - throw new NotImplementedException(); - } + get { return position; } + set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) @@ -106,7 +100,7 @@ namespace SharpCompress.Compressor.PPMd int c; while (size < count && (c = modelH.decodeChar()) >= 0) { - buffer[offset++] = (byte)c; + buffer[offset++] = (byte) c; size++; } } @@ -115,7 +109,7 @@ namespace SharpCompress.Compressor.PPMd int c; while (size < count && (c = modelH.decodeChar(decoder)) >= 0) { - buffer[offset++] = (byte)c; + buffer[offset++] = (byte) c; size++; } } @@ -139,4 +133,4 @@ namespace SharpCompress.Compressor.PPMd model.EncodeBlock(stream, new MemoryStream(buffer, offset, count), false); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/Decode/AudioVariables.cs b/SharpCompress/Compressor/Rar/Decode/AudioVariables.cs index 28d95722..49a39aae 100644 --- a/SharpCompress/Compressor/Rar/Decode/AudioVariables.cs +++ b/SharpCompress/Compressor/Rar/Decode/AudioVariables.cs @@ -1,4 +1,3 @@ - namespace SharpCompress.Compressor.Rar.decode { internal class AudioVariables @@ -8,72 +7,20 @@ namespace SharpCompress.Compressor.Rar.decode Dif = new int[11]; } - internal int[] Dif - { - get; - private set; - } - internal int ByteCount - { - get; - set; - } - internal int D1 - { - get; - set; - } + internal int[] Dif { get; private set; } + internal int ByteCount { get; set; } + internal int D1 { get; set; } - internal int D2 - { - get; - set; - } - internal int D3 - { - get; - set; - } - internal int D4 - { - get; - set; - } + internal int D2 { get; set; } + internal int D3 { get; set; } + internal int D4 { get; set; } - internal int K1 - { - get; - set; - } - internal int K2 - { - get; - set; - } - internal int K3 - { - get; - set; - } - internal int K4 - { - get; - set; - } - internal int K5 - { - get; - set; - } - internal int LastChar - { - get; - set; - } - internal int LastDelta - { - get; - set; - } + internal int K1 { get; set; } + internal int K2 { get; set; } + internal int K3 { get; set; } + internal int K4 { get; set; } + internal int K5 { get; set; } + internal int LastChar { get; set; } + internal int LastDelta { get; set; } } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/Decode/Compress.cs b/SharpCompress/Compressor/Rar/Decode/Compress.cs index b6f0ef67..1388b350 100644 --- a/SharpCompress/Compressor/Rar/Decode/Compress.cs +++ b/SharpCompress/Compressor/Rar/Decode/Compress.cs @@ -1,4 +1,3 @@ - namespace SharpCompress.Compressor.Rar.decode { internal class Compress diff --git a/SharpCompress/Compressor/Rar/Decode/Decode.cs b/SharpCompress/Compressor/Rar/Decode/Decode.cs index ffeda7e8..e4feec74 100644 --- a/SharpCompress/Compressor/Rar/Decode/Decode.cs +++ b/SharpCompress/Compressor/Rar/Decode/Decode.cs @@ -1,6 +1,5 @@ namespace SharpCompress.Compressor.Rar.decode { - internal class Decode { internal Decode() @@ -18,33 +17,18 @@ namespace SharpCompress.Compressor.Rar.decode /// returns the decode Length array /// decodeLength /// - internal int[] DecodeLen - { - get; - private set; + internal int[] DecodeLen { get; private set; } - } /// returns the decode num array /// decodeNum /// - internal int[] DecodeNum - { - get; - private set; - } + internal int[] DecodeNum { get; private set; } + /// returns the decodePos array /// decodePos /// - internal int[] DecodePos - { - get; - private set; - } + internal int[] DecodePos { get; private set; } - internal int MaxNum - { - get; - set; - } + internal int MaxNum { get; set; } } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/Decode/LitDecode.cs b/SharpCompress/Compressor/Rar/Decode/LitDecode.cs index 57918d01..48c0de51 100644 --- a/SharpCompress/Compressor/Rar/Decode/LitDecode.cs +++ b/SharpCompress/Compressor/Rar/Decode/LitDecode.cs @@ -1,4 +1,3 @@ - namespace SharpCompress.Compressor.Rar.decode { internal class LitDecode : Decode diff --git a/SharpCompress/Compressor/Rar/Decode/RepDecode.cs b/SharpCompress/Compressor/Rar/Decode/RepDecode.cs index 2bfa1a7b..bc66361f 100644 --- a/SharpCompress/Compressor/Rar/Decode/RepDecode.cs +++ b/SharpCompress/Compressor/Rar/Decode/RepDecode.cs @@ -1,4 +1,3 @@ - namespace SharpCompress.Compressor.Rar.decode { internal class RepDecode : Decode diff --git a/SharpCompress/Compressor/Rar/MultiVolumeReadOnlyStream.cs b/SharpCompress/Compressor/Rar/MultiVolumeReadOnlyStream.cs index 28c0425e..9fdfdd6d 100644 --- a/SharpCompress/Compressor/Rar/MultiVolumeReadOnlyStream.cs +++ b/SharpCompress/Compressor/Rar/MultiVolumeReadOnlyStream.cs @@ -60,8 +60,8 @@ namespace SharpCompress.Compressor.Rar currentPartTotalReadBytes = 0; streamListener.FireFilePartExtractionBegin(filePartEnumerator.Current.FilePartName, - filePartEnumerator.Current.FileHeader.CompressedSize, - filePartEnumerator.Current.FileHeader.UncompressedSize); + filePartEnumerator.Current.FileHeader.CompressedSize, + filePartEnumerator.Current.FileHeader.UncompressedSize); } public override int Read(byte[] buffer, int offset, int count) @@ -72,7 +72,7 @@ namespace SharpCompress.Compressor.Rar int readSize = count; if (count > maxPosition - currentPosition) { - readSize = (int)(maxPosition - currentPosition); + readSize = (int) (maxPosition - currentPosition); } int read = currentStream.Read(buffer, offset, readSize); @@ -91,7 +91,8 @@ namespace SharpCompress.Compressor.Rar string fileName = filePartEnumerator.Current.FileHeader.FileName; if (!filePartEnumerator.MoveNext()) { - throw new InvalidFormatException("Multi-part rar file is incomplete. Entry expects a new volume: " + fileName); + throw new InvalidFormatException( + "Multi-part rar file is incomplete. Entry expects a new volume: " + fileName); } InitializeNextFilePart(); } @@ -108,26 +109,17 @@ namespace SharpCompress.Compressor.Rar public override bool CanRead { - get - { - return true; - } + get { return true; } } public override bool CanSeek { - get - { - return false; - } + get { return false; } } public override bool CanWrite { - get - { - return false; - } + get { return false; } } public override void Flush() @@ -137,22 +129,13 @@ namespace SharpCompress.Compressor.Rar public override long Length { - get - { - throw new NotImplementedException(); - } + get { throw new NotImplementedException(); } } public override long Position { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } } public override long Seek(long offset, SeekOrigin origin) @@ -170,4 +153,4 @@ namespace SharpCompress.Compressor.Rar throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/PPM/BlockTypes.cs b/SharpCompress/Compressor/Rar/PPM/BlockTypes.cs index 4e9c9541..29c9affd 100644 --- a/SharpCompress/Compressor/Rar/PPM/BlockTypes.cs +++ b/SharpCompress/Compressor/Rar/PPM/BlockTypes.cs @@ -1,4 +1,3 @@ - namespace SharpCompress.Compressor.Rar.PPM { internal enum BlockTypes diff --git a/SharpCompress/Compressor/Rar/RarCRC.cs b/SharpCompress/Compressor/Rar/RarCRC.cs index c2ff5514..b680434f 100644 --- a/SharpCompress/Compressor/Rar/RarCRC.cs +++ b/SharpCompress/Compressor/Rar/RarCRC.cs @@ -12,7 +12,7 @@ namespace SharpCompress.Compressor.Rar for (int i = 0; i < size; i++) { - startCrc = (crcTab[((int)((int)startCrc ^ (int)data[offset + i])) & 0xff] ^ (startCrc >> 8)); + startCrc = (crcTab[((int) ((int) startCrc ^ (int) data[offset + i])) & 0xff] ^ (startCrc >> 8)); } return (startCrc); } diff --git a/SharpCompress/Compressor/Rar/RarStream.cs b/SharpCompress/Compressor/Rar/RarStream.cs index afaebb93..1eb18cad 100644 --- a/SharpCompress/Compressor/Rar/RarStream.cs +++ b/SharpCompress/Compressor/Rar/RarStream.cs @@ -11,7 +11,7 @@ namespace SharpCompress.Compressor.Rar private Stream readStream; private bool fetch = false; - + private byte[] tmpBuffer = new byte[65536]; private int tmpOffset = 0; private int tmpCount = 0; @@ -53,22 +53,13 @@ namespace SharpCompress.Compressor.Rar public override long Length { - get - { - return fileHeader.UncompressedSize; - } + get { return fileHeader.UncompressedSize; } } public override long Position { - get - { - return fileHeader.UncompressedSize - unpack.DestSize; - } - set - { - throw new NotImplementedException(); - } + get { return fileHeader.UncompressedSize - unpack.DestSize; } + set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) @@ -124,7 +115,8 @@ namespace SharpCompress.Compressor.Rar { if (tmpBuffer.Length < tmpCount + count) { - byte[] newBuffer = new byte[tmpBuffer.Length*2 > tmpCount + count ? tmpBuffer.Length*2 : tmpCount + count]; + byte[] newBuffer = + new byte[tmpBuffer.Length*2 > tmpCount + count ? tmpBuffer.Length*2 : tmpCount + count]; Buffer.BlockCopy(tmpBuffer, 0, newBuffer, 0, tmpCount); tmpBuffer = newBuffer; } @@ -137,4 +129,4 @@ namespace SharpCompress.Compressor.Rar unpack.Suspended = false; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/Unpack.cs b/SharpCompress/Compressor/Rar/Unpack.cs index d084bd4d..c2e8ec60 100644 --- a/SharpCompress/Compressor/Rar/Unpack.cs +++ b/SharpCompress/Compressor/Rar/Unpack.cs @@ -30,35 +30,24 @@ namespace SharpCompress.Compressor.Rar // tablesRead = !NewTable; // return !(NewFile || NewTable && !readTables()); // } - - - get - { - return fileExtracted; - } - + get { return fileExtracted; } } + public long DestSize { - get - { - return destUnpSize; - } + get { return destUnpSize; } set { this.destUnpSize = value; this.fileExtracted = false; } - } + public bool Suspended { - set - { - this.suspended = value; - } - + set { this.suspended = value; } } + public int Char { get @@ -69,20 +58,13 @@ namespace SharpCompress.Compressor.Rar } return (InBuf[inAddr++] & 0xff); } - } + public int PpmEscChar { - get - { - return ppmEscChar; - } - - set - { - this.ppmEscChar = value; - } + get { return ppmEscChar; } + set { this.ppmEscChar = value; } } //UPGRADE_NOTE: Final was removed from the declaration of 'ppm '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" @@ -129,7 +111,7 @@ namespace SharpCompress.Compressor.Rar private int lowDistRepCount; - public static int[] DBitLengthCounts = new int[] { 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 14, 0, 12 }; + public static int[] DBitLengthCounts = new int[] {4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 14, 0, 12}; private FileHeader fileHeader; @@ -182,19 +164,19 @@ namespace SharpCompress.Compressor.Rar } switch (fileHeader.RarVersion) { - case 15: // rar 1.5 compression + case 15: // rar 1.5 compression unpack15(solid); break; case 20: - // rar 2.x compression - case 26: // files larger than 2GB + // rar 2.x compression + case 26: // files larger than 2GB unpack20(solid); break; case 29: - // rar 3.x compression - case 36: // alternative hash + // rar 3.x compression + case 36: // alternative hash unpack29(solid); break; } @@ -205,10 +187,10 @@ namespace SharpCompress.Compressor.Rar byte[] buffer = new byte[0x10000]; while (true) { - int code = readStream.Read(buffer, 0, (int)System.Math.Min(buffer.Length, destUnpSize)); + int code = readStream.Read(buffer, 0, (int) System.Math.Min(buffer.Length, destUnpSize)); if (code == 0 || code == -1) break; - code = code < destUnpSize ? code : (int)destUnpSize; + code = code < destUnpSize ? code : (int) destUnpSize; writeStream.Write(buffer, 0, code); if (destUnpSize >= 0) destUnpSize -= code; @@ -219,7 +201,6 @@ namespace SharpCompress.Compressor.Rar private void unpack29(bool solid) { - int[] DDecode = new int[Compress.DC]; byte[] DBits = new byte[Compress.DC]; @@ -234,7 +215,7 @@ namespace SharpCompress.Compressor.Rar for (int J = 0; J < count; J++, Slot++, Dist += (1 << BitLength)) { DDecode[Slot] = Dist; - DBits[Slot] = (byte)BitLength; + DBits[Slot] = (byte) BitLength; } } } @@ -274,7 +255,6 @@ namespace SharpCompress.Compressor.Rar // Compress.MAXWINMASK)+":"+wrPtr+":"+unpPtr); if (((wrPtr - unpPtr) & Compress.MAXWINMASK) < 260 && wrPtr != unpPtr) { - UnpWriteBuf(); if (destUnpSize <= 0) { @@ -360,14 +340,14 @@ namespace SharpCompress.Compressor.Rar continue; } } - window[unpPtr++] = (byte)Ch; + window[unpPtr++] = (byte) Ch; continue; } int Number = this.decodeNumber(LD); if (Number < 256) { - window[unpPtr++] = (byte)Number; + window[unpPtr++] = (byte) Number; continue; } if (Number >= 271) @@ -549,7 +529,8 @@ namespace SharpCompress.Compressor.Rar Prg.GlobalData.Clear(); for (int i = 0; i < ParentPrg.GlobalData.Count - RarVM.VM_FIXEDGLOBALSIZE; i++) { - Prg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = ParentPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; + Prg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = + ParentPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; } } @@ -566,7 +547,8 @@ namespace SharpCompress.Compressor.Rar // memcpy(&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],&Prg->GlobalData[VM_FIXEDGLOBALSIZE],Prg->GlobalData.Size()-VM_FIXEDGLOBALSIZE); for (int i = 0; i < Prg.GlobalData.Count - RarVM.VM_FIXEDGLOBALSIZE; i++) { - ParentPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = Prg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; + ParentPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = + Prg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; } } else @@ -580,7 +562,8 @@ namespace SharpCompress.Compressor.Rar for (int i = 0; i < FilteredDataSize; i++) { - FilteredData[i] = rarVM.Mem[FilteredDataOffset + i]; // Prg.GlobalData.get(FilteredDataOffset + FilteredData[i] = rarVM.Mem[FilteredDataOffset + i]; + // Prg.GlobalData.get(FilteredDataOffset // + // i); } @@ -589,13 +572,15 @@ namespace SharpCompress.Compressor.Rar while (I + 1 < prgStack.Count) { UnpackFilter NextFilter = prgStack[I + 1]; - if (NextFilter == null || NextFilter.BlockStart != BlockStart || NextFilter.BlockLength != FilteredDataSize || NextFilter.NextWindow) + if (NextFilter == null || NextFilter.BlockStart != BlockStart || + NextFilter.BlockLength != FilteredDataSize || NextFilter.NextWindow) { break; } // apply several filters to same data block - rarVM.setMemory(0, FilteredData, 0, FilteredDataSize); // .SetMemory(0,FilteredData,FilteredDataSize); + rarVM.setMemory(0, FilteredData, 0, FilteredDataSize); + // .SetMemory(0,FilteredData,FilteredDataSize); VMPreparedProgram pPrg = filters[NextFilter.ParentFilter].Program; VMPreparedProgram NextPrg = NextFilter.Program; @@ -609,7 +594,8 @@ namespace SharpCompress.Compressor.Rar // memcpy(&NextPrg->GlobalData[VM_FIXEDGLOBALSIZE],&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],ParentPrg->GlobalData.Size()-VM_FIXEDGLOBALSIZE); for (int i = 0; i < pPrg.GlobalData.Count - RarVM.VM_FIXEDGLOBALSIZE; i++) { - NextPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = pPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; + NextPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = + pPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; } } @@ -625,7 +611,8 @@ namespace SharpCompress.Compressor.Rar // memcpy(&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],&NextPrg->GlobalData[VM_FIXEDGLOBALSIZE],NextPrg->GlobalData.Size()-VM_FIXEDGLOBALSIZE); for (int i = 0; i < NextPrg.GlobalData.Count - RarVM.VM_FIXEDGLOBALSIZE; i++) { - pPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = NextPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; + pPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = + NextPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; } } else @@ -698,7 +685,7 @@ namespace SharpCompress.Compressor.Rar int writeSize = size; if (writeSize > destUnpSize) { - writeSize = (int)destUnpSize; + writeSize = (int) destUnpSize; } writeStream.Write(data, offset, writeSize); @@ -728,7 +715,6 @@ namespace SharpCompress.Compressor.Rar // System.out.println(unpPtr+":"+distance); if (destPtr >= 0 && destPtr < Compress.MAXWINSIZE - 260 && unpPtr < Compress.MAXWINSIZE - 260) { - window[unpPtr++] = window[destPtr++]; while (--length > 0) @@ -753,7 +739,7 @@ namespace SharpCompress.Compressor.Rar lastDist = 0; lastLength = 0; - Utility.Fill(unpOldTable, (byte)0); // memset(UnpOldTable,0,sizeof(UnpOldTable)); + Utility.Fill(unpOldTable, (byte) 0); // memset(UnpOldTable,0,sizeof(UnpOldTable)); unpPtr = 0; wrPtr = 0; @@ -811,7 +797,7 @@ namespace SharpCompress.Compressor.Rar } } AddBits((8 - inBit) & 7); - long bitField = GetBits() & unchecked((int)0xffFFffFF); + long bitField = GetBits() & unchecked((int) 0xffFFffFF); if ((bitField & 0x8000) != 0) { unpBlockType = BlockTypes.BLOCK_PPM; @@ -824,7 +810,7 @@ namespace SharpCompress.Compressor.Rar if ((bitField & 0x4000) == 0) { - Utility.Fill(unpOldTable, (byte)0); // memset(UnpOldTable,0,sizeof(UnpOldTable)); + Utility.Fill(unpOldTable, (byte) 0); // memset(UnpOldTable,0,sizeof(UnpOldTable)); } AddBits(2); @@ -852,7 +838,7 @@ namespace SharpCompress.Compressor.Rar } else { - bitLength[i] = (byte)length; + bitLength[i] = (byte) length; } } @@ -860,7 +846,7 @@ namespace SharpCompress.Compressor.Rar int TableSize = Compress.HUFF_TABLE_SIZE; - for (int i = 0; i < TableSize; ) + for (int i = 0; i < TableSize;) { if (inAddr > readTop - 5) { @@ -872,7 +858,7 @@ namespace SharpCompress.Compressor.Rar int Number = this.decodeNumber(BD); if (Number < 16) { - table[i] = (byte)((Number + unpOldTable[i]) & 0xf); + table[i] = (byte) ((Number + unpOldTable[i]) & 0xf); i++; } else if (Number < 18) @@ -955,7 +941,7 @@ namespace SharpCompress.Compressor.Rar { return (false); } - vmCode.Add((byte)(GetBits() >> 8)); + vmCode.Add((byte) (GetBits() >> 8)); AddBits(8); } return (addVMCode(FirstByte, vmCode, Length)); @@ -964,7 +950,7 @@ namespace SharpCompress.Compressor.Rar private bool readVMCodePPM() { int FirstByte = ppm.decodeChar(); - if ((int)FirstByte == -1) + if ((int) FirstByte == -1) { return (false); } @@ -990,7 +976,7 @@ namespace SharpCompress.Compressor.Rar { return (false); } - Length = B1 * 256 + B2; + Length = B1*256 + B2; } //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'" List vmCode = new List(); @@ -1001,7 +987,7 @@ namespace SharpCompress.Compressor.Rar { return (false); } - vmCode.Add((byte)Ch); // VMCode[I]=Ch; + vmCode.Add((byte) Ch); // VMCode[I]=Ch; } return (addVMCode(FirstByte, vmCode, Length)); } @@ -1045,7 +1031,7 @@ namespace SharpCompress.Compressor.Rar 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) @@ -1060,7 +1046,7 @@ namespace SharpCompress.Compressor.Rar oldFilterLengths.Add(0); Filter.ExecCount = 0; } - // filter was used in the past + // filter was used in the past else { Filter = filters[FiltPos]; @@ -1095,12 +1081,13 @@ namespace SharpCompress.Compressor.Rar // memset(StackFilter->Prg.InitR,0,sizeof(StackFilter->Prg.InitR)); Utility.Fill(StackFilter.Program.InitR, 0); StackFilter.Program.InitR[3] = RarVM.VM_GLOBALMEMADDR; // StackFilter->Prg.InitR[3]=VM_GLOBALMEMADDR; - StackFilter.Program.InitR[4] = StackFilter.BlockLength; // StackFilter->Prg.InitR[4]=StackFilter->BlockLength; + StackFilter.Program.InitR[4] = StackFilter.BlockLength; + // StackFilter->Prg.InitR[4]=StackFilter->BlockLength; StackFilter.Program.InitR[5] = StackFilter.ExecCount; // StackFilter->Prg.InitR[5]=StackFilter->ExecCount; 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); @@ -1128,14 +1115,15 @@ namespace SharpCompress.Compressor.Rar { return (false); } - VMCode[I] = (byte)(Inp.GetBits() >> 8); + VMCode[I] = (byte) (Inp.GetBits() >> 8); Inp.AddBits(8); } // VM.Prepare(&VMCode[0],VMCodeSize,&Filter->Prg); rarVM.prepare(VMCode, VMCodeSize, Filter.Program); } StackFilter.Program.AltCommands = Filter.Program.Commands; // StackFilter->Prg.AltCmd=&Filter->Prg.Cmd[0]; - StackFilter.Program.CommandCount = Filter.Program.CommandCount; // StackFilter->Prg.CmdCount=Filter->Prg.CmdCount; + StackFilter.Program.CommandCount = Filter.Program.CommandCount; + // StackFilter->Prg.CmdCount=Filter->Prg.CmdCount; int StaticDataSize = Filter.Program.StaticData.Count; if (StaticDataSize > 0 && StaticDataSize < RarVM.VM_GLOBALMEMSIZE) @@ -1159,7 +1147,7 @@ namespace SharpCompress.Compressor.Rar List globalData = StackFilter.Program.GlobalData; for (int I = 0; I < 7; I++) { - rarVM.SetLowEndianValue(globalData, I * 4, StackFilter.Program.InitR[I]); + rarVM.SetLowEndianValue(globalData, I*4, StackFilter.Program.InitR[I]); } // VM.SetLowEndianValue((uint @@ -1179,7 +1167,7 @@ namespace SharpCompress.Compressor.Rar globalData[0x30 + i] = 0x0; } if ((firstByte & 8) != 0) - // put data block passed as parameter if any + // put data block passed as parameter if any { if (Inp.Overflow(3)) { @@ -1204,7 +1192,7 @@ namespace SharpCompress.Compressor.Rar { return (false); } - globalData[offset + I] = (byte)(Utility.URShift(Inp.GetBits(), 8)); + globalData[offset + I] = (byte) (Utility.URShift(Inp.GetBits(), 8)); Inp.AddBits(8); } } @@ -1217,13 +1205,13 @@ namespace SharpCompress.Compressor.Rar if (Prg.GlobalData.Count > 0) { // Prg->InitR[6]=int64to32(WrittenFileSize); - Prg.InitR[6] = (int)(writtenFileSize); + Prg.InitR[6] = (int) (writtenFileSize); // rarVM.SetLowEndianValue((uint // *)&Prg->GlobalData[0x24],int64to32(WrittenFileSize)); - rarVM.SetLowEndianValue(Prg.GlobalData, 0x24, (int)writtenFileSize); + rarVM.SetLowEndianValue(Prg.GlobalData, 0x24, (int) writtenFileSize); // rarVM.SetLowEndianValue((uint // *)&Prg->GlobalData[0x28],int64to32(WrittenFileSize>>32)); - rarVM.SetLowEndianValue(Prg.GlobalData, 0x28, (int)(Utility.URShift(writtenFileSize, 32))); + rarVM.SetLowEndianValue(Prg.GlobalData, 0x28, (int) (Utility.URShift(writtenFileSize, 32))); rarVM.execute(Prg); } } diff --git a/SharpCompress/Compressor/Rar/Unpack15.cs b/SharpCompress/Compressor/Rar/Unpack15.cs index 61f23258..1c52980e 100644 --- a/SharpCompress/Compressor/Rar/Unpack15.cs +++ b/SharpCompress/Compressor/Rar/Unpack15.cs @@ -15,6 +15,7 @@ * ">": ">" or ">" * "@": "@" */ + using System; using System.IO; using SharpCompress.Compressor.Rar.decode; @@ -22,7 +23,6 @@ using SharpCompress.Compressor.Rar.VM; namespace SharpCompress.Compressor.Rar { - /// DOCUMENT ME /// /// @@ -32,7 +32,6 @@ namespace SharpCompress.Compressor.Rar /// internal abstract class Unpack15 : BitInput { - protected internal int readBorder; protected internal bool suspended; @@ -58,9 +57,15 @@ namespace SharpCompress.Compressor.Rar protected internal int oldDistPtr; - protected internal int[] ChSet = new int[256], ChSetA = new int[256], ChSetB = new int[256], ChSetC = new int[256]; + protected internal int[] ChSet = new int[256], + ChSetA = new int[256], + ChSetB = new int[256], + ChSetC = new int[256]; - protected internal int[] Place = new int[256], PlaceA = new int[256], PlaceB = new int[256], PlaceC = new int[256]; + protected internal int[] Place = new int[256], + PlaceA = new int[256], + PlaceB = new int[256], + PlaceC = new int[256]; protected internal int[] NToPl = new int[256], NToPlB = new int[256], NToPlC = new int[256]; @@ -74,53 +79,68 @@ namespace SharpCompress.Compressor.Rar private const int STARTL1 = 2; - private static int[] DecL1 = new int[] { 0x8000, 0xa000, 0xc000, 0xd000, 0xe000, 0xea00, 0xee00, 0xf000, 0xf200, 0xf200, 0xffff }; + private static int[] DecL1 = new int[] + { + 0x8000, 0xa000, 0xc000, 0xd000, 0xe000, 0xea00, 0xee00, 0xf000, 0xf200, 0xf200 + , 0xffff + }; - private static int[] PosL1 = new int[] { 0, 0, 0, 2, 3, 5, 7, 11, 16, 20, 24, 32, 32 }; + private static int[] PosL1 = new int[] {0, 0, 0, 2, 3, 5, 7, 11, 16, 20, 24, 32, 32}; private const int STARTL2 = 3; - private static int[] DecL2 = new int[] { 0xa000, 0xc000, 0xd000, 0xe000, 0xea00, 0xee00, 0xf000, 0xf200, 0xf240, 0xffff }; + private static int[] DecL2 = new int[] + { + 0xa000, 0xc000, 0xd000, 0xe000, 0xea00, 0xee00, 0xf000, 0xf200, 0xf240, 0xffff + }; - private static int[] PosL2 = new int[] { 0, 0, 0, 0, 5, 7, 9, 13, 18, 22, 26, 34, 36 }; + private static int[] PosL2 = new int[] {0, 0, 0, 0, 5, 7, 9, 13, 18, 22, 26, 34, 36}; private const int STARTHF0 = 4; - private static int[] DecHf0 = new int[] { 0x8000, 0xc000, 0xe000, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xffff }; + private static int[] DecHf0 = new int[] {0x8000, 0xc000, 0xe000, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xffff}; - private static int[] PosHf0 = new int[] { 0, 0, 0, 0, 0, 8, 16, 24, 33, 33, 33, 33, 33 }; + private static int[] PosHf0 = new int[] {0, 0, 0, 0, 0, 8, 16, 24, 33, 33, 33, 33, 33}; private const int STARTHF1 = 5; - private static int[] DecHf1 = new int[] { 0x2000, 0xc000, 0xe000, 0xf000, 0xf200, 0xf200, 0xf7e0, 0xffff }; + private static int[] DecHf1 = new int[] {0x2000, 0xc000, 0xe000, 0xf000, 0xf200, 0xf200, 0xf7e0, 0xffff}; - private static int[] PosHf1 = new int[] { 0, 0, 0, 0, 0, 0, 4, 44, 60, 76, 80, 80, 127 }; + private static int[] PosHf1 = new int[] {0, 0, 0, 0, 0, 0, 4, 44, 60, 76, 80, 80, 127}; private const int STARTHF2 = 5; - private static int[] DecHf2 = new int[] { 0x1000, 0x2400, 0x8000, 0xc000, 0xfa00, 0xffff, 0xffff, 0xffff }; + private static int[] DecHf2 = new int[] {0x1000, 0x2400, 0x8000, 0xc000, 0xfa00, 0xffff, 0xffff, 0xffff}; - private static int[] PosHf2 = new int[] { 0, 0, 0, 0, 0, 0, 2, 7, 53, 117, 233, 0, 0 }; + private static int[] PosHf2 = new int[] {0, 0, 0, 0, 0, 0, 2, 7, 53, 117, 233, 0, 0}; private const int STARTHF3 = 6; - private static int[] DecHf3 = new int[] { 0x800, 0x2400, 0xee00, 0xfe80, 0xffff, 0xffff, 0xffff }; + private static int[] DecHf3 = new int[] {0x800, 0x2400, 0xee00, 0xfe80, 0xffff, 0xffff, 0xffff}; - private static int[] PosHf3 = new int[] { 0, 0, 0, 0, 0, 0, 0, 2, 16, 218, 251, 0, 0 }; + private static int[] PosHf3 = new int[] {0, 0, 0, 0, 0, 0, 0, 2, 16, 218, 251, 0, 0}; private const int STARTHF4 = 8; - private static int[] DecHf4 = new int[] { 0xff00, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff }; + private static int[] DecHf4 = new int[] {0xff00, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; - private static int[] PosHf4 = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0 }; + private static int[] PosHf4 = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0}; - internal static int[] ShortLen1 = new int[] { 1, 3, 4, 4, 5, 6, 7, 8, 8, 4, 4, 5, 6, 6, 4, 0 }; + internal static int[] ShortLen1 = new int[] {1, 3, 4, 4, 5, 6, 7, 8, 8, 4, 4, 5, 6, 6, 4, 0}; - internal static int[] ShortXor1 = new int[] { 0, 0xa0, 0xd0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff, 0xc0, 0x80, 0x90, 0x98, 0x9c, 0xb0 }; + internal static int[] ShortXor1 = new int[] + { + 0, 0xa0, 0xd0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff, 0xc0, 0x80, 0x90, 0x98 + , 0x9c, 0xb0 + }; - internal static int[] ShortLen2 = new int[] { 2, 3, 3, 3, 4, 4, 5, 6, 6, 4, 4, 5, 6, 6, 4, 0 }; + internal static int[] ShortLen2 = new int[] {2, 3, 3, 3, 4, 4, 5, 6, 6, 4, 4, 5, 6, 6, 4, 0}; - internal static int[] ShortXor2 = new int[] { 0, 0x40, 0x60, 0xa0, 0xd0, 0xe0, 0xf0, 0xf8, 0xfc, 0xc0, 0x80, 0x90, 0x98, 0x9c, 0xb0 }; + internal static int[] ShortXor2 = new int[] + { + 0, 0x40, 0x60, 0xa0, 0xd0, 0xe0, 0xf0, 0xf8, 0xfc, 0xc0, 0x80, 0x90, 0x98 + , 0x9c, 0xb0 + }; protected internal abstract void unpInitData(bool solid); @@ -223,7 +243,6 @@ namespace SharpCompress.Compressor.Rar } - protected bool unpReadBuf() { int dataSize = readTop - inAddr; @@ -231,7 +250,7 @@ namespace SharpCompress.Compressor.Rar { return (false); } - if (inAddr > BitInput.MAX_SIZE / 2) + if (inAddr > BitInput.MAX_SIZE/2) { if (dataSize > 0) { @@ -291,7 +310,7 @@ namespace SharpCompress.Compressor.Rar 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) { @@ -302,7 +321,7 @@ namespace SharpCompress.Compressor.Rar } else { - for (Length = 0; ; Length++) + for (Length = 0;; Length++) { if (((BitField ^ ShortXor2[Length]) & (~(0xff >> getShortLen2(Length)))) == 0) { @@ -583,7 +602,7 @@ namespace SharpCompress.Compressor.Rar Nlzb = Utility.URShift(Nlzb, 1); } - window[unpPtr++] = (byte)(Utility.URShift(ChSet[BytePlace], 8)); + window[unpPtr++] = (byte) (Utility.URShift(ChSet[BytePlace], 8)); --destUnpSize; while (true) @@ -672,7 +691,7 @@ namespace SharpCompress.Compressor.Rar Utility.Fill(NumToPlace, 0); // memset(NumToPlace,0,sizeof(NToPl)); for (I = 6; I >= 0; I--) { - NumToPlace[I] = (7 - I) * 32; + NumToPlace[I] = (7 - I)*32; } } diff --git a/SharpCompress/Compressor/Rar/Unpack20.cs b/SharpCompress/Compressor/Rar/Unpack20.cs index 8fa750f7..fcd0ccca 100644 --- a/SharpCompress/Compressor/Rar/Unpack20.cs +++ b/SharpCompress/Compressor/Rar/Unpack20.cs @@ -20,7 +20,6 @@ using SharpCompress.Compressor.Rar.decode; namespace SharpCompress.Compressor.Rar { - /// DOCUMENT ME /// /// @@ -34,9 +33,10 @@ namespace SharpCompress.Compressor.Rar { InitBlock(); } + private void InitBlock() { - UnpOldTable20 = new byte[Compress.MC20 * 4]; + UnpOldTable20 = new byte[Compress.MC20*4]; } protected internal MultDecode[] MD = new MultDecode[4]; @@ -59,26 +59,45 @@ namespace SharpCompress.Compressor.Rar protected internal BitDecode BD = new BitDecode(); //UPGRADE_NOTE: Final was removed from the declaration of 'LDecode'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int[] LDecode = new int[] { 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 int[] LDecode = new int[] + { + 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 + }; //UPGRADE_NOTE: Final was removed from the declaration of 'LBits'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly byte[] LBits = new byte[] { 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 byte[] LBits = new byte[] + { + 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 + }; //UPGRADE_NOTE: Final was removed from the declaration of 'DDecode'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int[] DDecode = new int[] { 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, 32768, 49152, 65536, 98304, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 655360, 720896, 786432, 851968, 917504, 983040 }; + public static readonly int[] DDecode = new int[] + { + 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, 32768, 49152, 65536, 98304, 131072, 196608, 262144, 327680, + 393216, 458752, 524288, 589824, 655360, 720896, 786432, 851968, + 917504, 983040 + }; //UPGRADE_NOTE: Final was removed from the declaration of 'DBits'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int[] DBits = new int[] { 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 int[] DBits = new int[] + { + 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 + }; //UPGRADE_NOTE: Final was removed from the declaration of 'SDDecode'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int[] SDDecode = new int[] { 0, 4, 8, 16, 32, 64, 128, 192 }; + public static readonly int[] SDDecode = new int[] {0, 4, 8, 16, 32, 64, 128, 192}; //UPGRADE_NOTE: Final was removed from the declaration of 'SDBits'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly int[] SDBits = new int[] { 2, 2, 3, 4, 5, 6, 6, 6 }; + public static readonly int[] SDBits = new int[] {2, 2, 3, 4, 5, 6, 6, 6}; internal void unpack20(bool solid) { - int Bits; if (suspended) @@ -135,7 +154,7 @@ namespace SharpCompress.Compressor.Rar int Number = this.decodeNumber(LD); if (Number < 256) { - window[unpPtr++] = (byte)Number; + window[unpPtr++] = (byte) Number; --destUnpSize; continue; } @@ -244,12 +263,10 @@ namespace SharpCompress.Compressor.Rar } - - private bool ReadTables20() { byte[] BitLength = new byte[Compress.BC20]; - byte[] Table = new byte[Compress.MC20 * 4]; + byte[] Table = new byte[Compress.MC20*4]; int TableSize, N, I; if (inAddr > readTop - 25) { @@ -264,7 +281,7 @@ namespace SharpCompress.Compressor.Rar if (0 == (BitField & 0x4000)) { // memset(UnpOldTable20,0,sizeof(UnpOldTable20)); - Utility.Fill(UnpOldTable20, (byte)0); + Utility.Fill(UnpOldTable20, (byte) 0); } AddBits(2); @@ -276,7 +293,7 @@ namespace SharpCompress.Compressor.Rar UnpCurChannel = 0; } AddBits(2); - TableSize = Compress.MC20 * UnpChannels; + TableSize = Compress.MC20*UnpChannels; } else { @@ -284,7 +301,7 @@ namespace SharpCompress.Compressor.Rar } for (I = 0; I < Compress.BC20; I++) { - BitLength[I] = (byte)(Utility.URShift(GetBits(), 12)); + BitLength[I] = (byte) (Utility.URShift(GetBits(), 12)); AddBits(4); } UnpackUtility.makeDecodeTables(BitLength, 0, BD, Compress.BC20); @@ -301,7 +318,7 @@ namespace SharpCompress.Compressor.Rar int Number = this.decodeNumber(BD); if (Number < 16) { - Table[I] = (byte)((Number + UnpOldTable20[I]) & 0xf); + Table[I] = (byte) ((Number + UnpOldTable20[I]) & 0xf); I++; } else if (Number == 16) @@ -336,7 +353,7 @@ namespace SharpCompress.Compressor.Rar } if (UnpAudioBlock != 0) for (I = 0; I < UnpChannels; I++) - UnpackUtility.makeDecodeTables(Table, I * Compress.MC20, MD[I], Compress.MC20); + UnpackUtility.makeDecodeTables(Table, I*Compress.MC20, MD[I], Compress.MC20); else { UnpackUtility.makeDecodeTables(Table, 0, LD, Compress.NC20); @@ -363,7 +380,7 @@ namespace SharpCompress.Compressor.Rar AudV[2] = new AudioVariables(); AudV[3] = new AudioVariables(); // memset(UnpOldTable20,0,sizeof(UnpOldTable20)); - Utility.Fill(UnpOldTable20, (byte)0); + Utility.Fill(UnpOldTable20, (byte) 0); } } @@ -398,14 +415,14 @@ namespace SharpCompress.Compressor.Rar v.D1 = v.LastDelta; // 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; - int PCh = 8 * v.LastChar + v.K1 * v.D1; - PCh += v.K2 * v.D2 + v.K3 * v.D3; - PCh += v.K4 * v.D4 + v.K5 * UnpChannelDelta; + int PCh = 8*v.LastChar + v.K1*v.D1; + PCh += v.K2*v.D2 + v.K3*v.D3; + PCh += v.K4*v.D4 + v.K5*UnpChannelDelta; PCh = (Utility.URShift(PCh, 3)) & 0xFF; int Ch = PCh - Delta; - int D = ((byte)Delta) << 3; + int D = ((byte) Delta) << 3; v.Dif[0] += System.Math.Abs(D); // V->Dif[0]+=abs(D); v.Dif[1] += System.Math.Abs(D - v.D1); // V->Dif[1]+=abs(D-V->D1); @@ -419,7 +436,7 @@ namespace SharpCompress.Compressor.Rar v.Dif[9] += System.Math.Abs(D - UnpChannelDelta); // V->Dif[9]+=abs(D-UnpChannelDelta); v.Dif[10] += System.Math.Abs(D + UnpChannelDelta); // V->Dif[10]+=abs(D+UnpChannelDelta); - v.LastDelta = (byte)(Ch - v.LastChar); + v.LastDelta = (byte) (Ch - v.LastChar); UnpChannelDelta = v.LastDelta; v.LastChar = Ch; // V->LastChar=Ch; @@ -438,7 +455,6 @@ namespace SharpCompress.Compressor.Rar } switch (NumMinDif) { - case 1: if (v.K1 >= -16) { @@ -510,7 +526,7 @@ namespace SharpCompress.Compressor.Rar break; } } - return ((byte)Ch); + return ((byte) Ch); } } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/UnpackFilter.cs b/SharpCompress/Compressor/Rar/UnpackFilter.cs index d304ca84..dd878512 100644 --- a/SharpCompress/Compressor/Rar/UnpackFilter.cs +++ b/SharpCompress/Compressor/Rar/UnpackFilter.cs @@ -9,42 +9,18 @@ namespace SharpCompress.Compressor.Rar Program = new VMPreparedProgram(); } - internal int BlockStart - { - get; - set; - } + internal int BlockStart { get; set; } - internal int BlockLength - { - get; - set; - } + internal int BlockLength { get; set; } - internal int ExecCount - { - get; - set; - } + internal int ExecCount { get; set; } - internal bool NextWindow - { - get; - set; - } + internal bool NextWindow { get; set; } // position of parent filter in Filters array used as prototype for filter // in PrgStack array. Not defined for filters in Filters array. - internal int ParentFilter - { - get; - set; - } + internal int ParentFilter { get; set; } - internal VMPreparedProgram Program - { - get; - set; - } + internal VMPreparedProgram Program { get; set; } } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/UnpackUtility.cs b/SharpCompress/Compressor/Rar/UnpackUtility.cs index 2a7fc80b..53b83326 100644 --- a/SharpCompress/Compressor/Rar/UnpackUtility.cs +++ b/SharpCompress/Compressor/Rar/UnpackUtility.cs @@ -152,7 +152,7 @@ namespace SharpCompress.Compressor.Rar } } input.AddBits(bits); - int N = dec.DecodePos[bits] + (Utility.URShift(((int)bitField - decodeLen[bits - 1]), (16 - bits))); + int N = dec.DecodePos[bits] + (Utility.URShift(((int) bitField - decodeLen[bits - 1]), (16 - bits))); if (N >= dec.MaxNum) { N = 0; @@ -173,18 +173,18 @@ namespace SharpCompress.Compressor.Rar for (i = 0; i < size; i++) { - lenCount[(int)(lenTab[offset + i] & 0xF)]++; + lenCount[(int) (lenTab[offset + i] & 0xF)]++; } lenCount[0] = 0; for (tmpPos[0] = 0, dec.DecodePos[0] = 0, dec.DecodeLen[0] = 0, N = 0, i = 1; i < 16; i++) { - N = 2 * (N + lenCount[i]); + N = 2*(N + lenCount[i]); M = N << (15 - i); if (M > 0xFFFF) { M = 0xFFFF; } - dec.DecodeLen[i] = (int)M; + dec.DecodeLen[i] = (int) M; tmpPos[i] = dec.DecodePos[i] = dec.DecodePos[i - 1] + lenCount[i - 1]; } @@ -198,4 +198,4 @@ namespace SharpCompress.Compressor.Rar dec.MaxNum = size; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/VM/BitInput.cs b/SharpCompress/Compressor/Rar/VM/BitInput.cs index 10a5c270..b9d6b8c0 100644 --- a/SharpCompress/Compressor/Rar/VM/BitInput.cs +++ b/SharpCompress/Compressor/Rar/VM/BitInput.cs @@ -4,6 +4,7 @@ namespace SharpCompress.Compressor.Rar.VM { /// the max size of the input internal const int MAX_SIZE = 0x8000; + protected int inAddr; protected int inBit; @@ -13,11 +14,7 @@ namespace SharpCompress.Compressor.Rar.VM InBuf = new byte[MAX_SIZE]; } - internal byte[] InBuf - { - get; - private set; - } + internal byte[] InBuf { get; private set; } internal void InitBitInput() { @@ -51,8 +48,8 @@ namespace SharpCompress.Compressor.Rar.VM // BitField >>>= (8-inBit); // return (BitField & 0xffff); return ((Utility.URShift((((InBuf[inAddr] & 0xff) << 16) - + ((InBuf[inAddr + 1] & 0xff) << 8) - + ((InBuf[inAddr + 2] & 0xff))), (8 - inBit))) & 0xffff); + + ((InBuf[inAddr + 1] & 0xff) << 8) + + ((InBuf[inAddr + 2] & 0xff))), (8 - inBit))) & 0xffff); } /// Indicates an Overfow diff --git a/SharpCompress/Compressor/Rar/VM/RarVM.cs b/SharpCompress/Compressor/Rar/VM/RarVM.cs index 7dcaa393..f1f25d34 100644 --- a/SharpCompress/Compressor/Rar/VM/RarVM.cs +++ b/SharpCompress/Compressor/Rar/VM/RarVM.cs @@ -14,11 +14,7 @@ namespace SharpCompress.Compressor.Rar.VM //} - internal byte[] Mem - { - get; - private set; - } + internal byte[] Mem { get; private set; } public const int VM_MEMSIZE = 0x40000; @@ -96,11 +92,11 @@ namespace SharpCompress.Compressor.Rar.VM { if (IsVMMem(mem)) { - mem[offset] = (byte)value; + mem[offset] = (byte) value; } else { - mem[offset] = (byte)((mem[offset] & 0x00) | (byte)(value & 0xff)); + mem[offset] = (byte) ((mem[offset] & 0x00) | (byte) (value & 0xff)); } } else @@ -128,10 +124,10 @@ namespace SharpCompress.Compressor.Rar.VM internal void SetLowEndianValue(List mem, int offset, int value) { - mem[offset + 0] = (byte)(value & 0xff); - mem[offset + 1] = (byte)(Utility.URShift(value, 8) & 0xff); - mem[offset + 2] = (byte)(Utility.URShift(value, 16) & 0xff); - mem[offset + 3] = (byte)(Utility.URShift(value, 24) & 0xff); + mem[offset + 0] = (byte) (value & 0xff); + mem[offset + 1] = (byte) (Utility.URShift(value, 8) & 0xff); + mem[offset + 2] = (byte) (Utility.URShift(value, 16) & 0xff); + mem[offset + 3] = (byte) (Utility.URShift(value, 24) & 0xff); } private int GetOperand(VMPreparedOperand cmdOp) @@ -153,36 +149,37 @@ namespace SharpCompress.Compressor.Rar.VM public void execute(VMPreparedProgram prg) { 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]; } - long globalSize = (long)(Math.Min(prg.GlobalData.Count, VM_GLOBALMEMSIZE)) & 0xffFFffFF; + long globalSize = (long) (Math.Min(prg.GlobalData.Count, VM_GLOBALMEMSIZE)) & 0xffFFffFF; if (globalSize != 0) { 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]; } } - long staticSize = (long)(Math.Min(prg.StaticData.Count, VM_GLOBALMEMSIZE - globalSize)) & 0xffFFffFF; + long staticSize = (long) (Math.Min(prg.StaticData.Count, VM_GLOBALMEMSIZE - globalSize)) & 0xffFFffFF; if (staticSize != 0) { 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]; + Mem[VM_GLOBALMEMADDR + (int) globalSize + i] = prg.StaticData[i]; } } R[7] = VM_MEMSIZE; flags = 0; //UPGRADE_NOTE: There is an untranslated Statement. Please refer to original code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1153'" - List preparedCode = prg.AltCommands.Count != 0 ? prg - .AltCommands - : prg.Commands; + List preparedCode = prg.AltCommands.Count != 0 + ? prg + .AltCommands + : prg.Commands; if (!ExecuteCode(preparedCode, prg.CommandCount)) { @@ -208,7 +205,7 @@ namespace SharpCompress.Compressor.Rar.VM // ->GlobalData.Add(dataSize+VM_FIXEDGLOBALSIZE); prg.GlobalData.SetSize(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[i] = Mem[VM_GLOBALMEMADDR + i]; } @@ -232,7 +229,7 @@ namespace SharpCompress.Compressor.Rar.VM } private bool ExecuteCode(List preparedCode, - int cmdCount) + int cmdCount) { maxOpCount = 25000000; this.codeSize = cmdCount; @@ -245,9 +242,9 @@ namespace SharpCompress.Compressor.Rar.VM int op2 = GetOperand(cmd.Op2); switch (cmd.OpCode) { - case VMCommands.VM_MOV: - SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2)); // SET_VALUE(Cmd->ByteMode,Op1,GET_VALUE(Cmd->ByteMode,Op2)); + SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2)); + // SET_VALUE(Cmd->ByteMode,Op1,GET_VALUE(Cmd->ByteMode,Op2)); break; case VMCommands.VM_MOVB: @@ -261,7 +258,7 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_CMP: { - VMFlags value1 = (VMFlags)GetValue(cmd.IsByteMode, Mem, op1); + VMFlags value1 = (VMFlags) GetValue(cmd.IsByteMode, Mem, op1); VMFlags result = value1 - GetValue(cmd.IsByteMode, Mem, op2); if (result == 0) @@ -270,7 +267,7 @@ namespace SharpCompress.Compressor.Rar.VM } else { - flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS)); } } break; @@ -278,7 +275,7 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_CMPB: { - VMFlags value1 = (VMFlags)GetValue(true, Mem, op1); + VMFlags value1 = (VMFlags) GetValue(true, Mem, op1); VMFlags result = value1 - GetValue(true, Mem, op2); if (result == 0) { @@ -286,14 +283,14 @@ namespace SharpCompress.Compressor.Rar.VM } else { - flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS)); } } break; case VMCommands.VM_CMPD: { - VMFlags value1 = (VMFlags)GetValue(false, Mem, op1); + VMFlags value1 = (VMFlags) GetValue(false, Mem, op1); VMFlags result = value1 - GetValue(false, Mem, op2); if (result == 0) { @@ -301,7 +298,7 @@ namespace SharpCompress.Compressor.Rar.VM } else { - flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS)); } } break; @@ -310,46 +307,79 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_ADD: { int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int result = (int)((((long)value1 + (long)GetValue(cmd.IsByteMode, Mem, op2))) & unchecked((int)0xffffffff)); + int result = + (int) + ((((long) 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 = + (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))); + int result = + (int) + ((long) value1 & 0xffFFffFF - (long) 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: - SetValue(true, Mem, op1, (int)((long)GetValue(true, Mem, op1) & 0xFFffFFff - (long)GetValue(true, Mem, op2) & unchecked((int)0xFFffFFff))); + SetValue(true, Mem, op1, + (int) + ((long) GetValue(true, Mem, op1) & 0xFFffFFff - (long) GetValue(true, Mem, op2) & + unchecked((int) 0xFFffFFff))); break; case VMCommands.VM_SUBD: - SetValue(false, Mem, op1, (int)((long)GetValue(false, Mem, op1) & 0xFFffFFff - (long)GetValue(false, Mem, op2) & unchecked((int)0xFFffFFff))); + SetValue(false, Mem, op1, + (int) + ((long) GetValue(false, Mem, op1) & 0xFFffFFff - (long) GetValue(false, Mem, op2) & + unchecked((int) 0xFFffFFff))); break; @@ -371,42 +401,42 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_INC: { - int result = (int)((long)GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFffL + 1L); + int result = (int) ((long) 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); + flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); } break; case VMCommands.VM_INCB: - SetValue(true, Mem, op1, (int)((long)GetValue(true, Mem, op1) & 0xFFffFFffL + 1L)); + SetValue(true, Mem, op1, (int) ((long) GetValue(true, Mem, op1) & 0xFFffFFffL + 1L)); break; case VMCommands.VM_INCD: - SetValue(false, Mem, op1, (int)((long)GetValue(false, Mem, op1) & 0xFFffFFffL + 1L)); + SetValue(false, Mem, op1, (int) ((long) GetValue(false, Mem, op1) & 0xFFffFFffL + 1L)); break; case VMCommands.VM_DEC: { - int result = (int)((long)GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFff - 1); + int result = (int) ((long) 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); + flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); } break; case VMCommands.VM_DECB: - SetValue(true, Mem, op1, (int)((long)GetValue(true, Mem, op1) & 0xFFffFFff - 1)); + SetValue(true, Mem, op1, (int) ((long) GetValue(true, Mem, op1) & 0xFFffFFff - 1)); break; case VMCommands.VM_DECD: - SetValue(false, Mem, op1, (int)((long)GetValue(false, Mem, op1) & 0xFFffFFff - 1)); + SetValue(false, Mem, op1, (int) ((long) GetValue(false, Mem, op1) & 0xFFffFFff - 1)); break; @@ -417,7 +447,7 @@ namespace SharpCompress.Compressor.Rar.VM 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); + flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); SetValue(cmd.IsByteMode, Mem, op1, result); } break; @@ -425,7 +455,7 @@ namespace SharpCompress.Compressor.Rar.VM 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); + flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); SetValue(cmd.IsByteMode, Mem, op1, result); } break; @@ -433,7 +463,7 @@ namespace SharpCompress.Compressor.Rar.VM 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); + flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); SetValue(cmd.IsByteMode, Mem, op1, result); } break; @@ -441,7 +471,7 @@ namespace SharpCompress.Compressor.Rar.VM 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); + flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); } break; @@ -518,7 +548,12 @@ namespace SharpCompress.Compressor.Rar.VM 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)); + 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; @@ -528,7 +563,10 @@ namespace SharpCompress.Compressor.Rar.VM 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)); + 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; @@ -537,8 +575,11 @@ namespace SharpCompress.Compressor.Rar.VM { int value1 = GetValue(cmd.IsByteMode, Mem, op1); int value2 = GetValue(cmd.IsByteMode, Mem, op2); - int result = ((int)value1) >> value2; - flags = (VMFlags)((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | ((value1 >> (value2 - 1)) & (int)VMFlags.VM_FC)); + int result = ((int) 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; @@ -546,7 +587,11 @@ namespace SharpCompress.Compressor.Rar.VM 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)); + flags = + (VMFlags) + (result == 0 + ? (int) VMFlags.VM_FZ + : (int) VMFlags.VM_FC | (result & (int) VMFlags.VM_FS)); SetValue(cmd.IsByteMode, Mem, op1, result); } break; @@ -566,7 +611,7 @@ namespace SharpCompress.Compressor.Rar.VM { SetValue(false, Mem, SP & VM_MEMMASK, R[i]); } - R[7] -= regCount * 4; + R[7] -= regCount*4; } break; @@ -579,11 +624,11 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_PUSHF: R[7] -= 4; - SetValue(false, Mem, R[7] & VM_MEMMASK, (int)flags); + SetValue(false, Mem, R[7] & VM_MEMMASK, (int) flags); break; case VMCommands.VM_POPF: - flags = (VMFlags)GetValue(false, Mem, R[7] & VM_MEMMASK); + flags = (VMFlags) GetValue(false, Mem, R[7] & VM_MEMMASK); R[7] += 4; break; @@ -592,7 +637,7 @@ namespace SharpCompress.Compressor.Rar.VM break; case VMCommands.VM_MOVSX: - SetValue(false, Mem, op1, (byte)GetValue(true, Mem, op2)); + SetValue(false, Mem, op1, (byte) GetValue(true, Mem, op2)); break; case VMCommands.VM_XCHG: @@ -605,7 +650,11 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_MUL: { - int result = (int)(((long)GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFff * (long)GetValue(cmd.IsByteMode, Mem, op2) & unchecked((int)0xFFffFFff)) & unchecked((int)0xFFffFFff)); + int result = + (int) + (((long) GetValue(cmd.IsByteMode, Mem, op1) & + 0xFFffFFff*(long) GetValue(cmd.IsByteMode, Mem, op2) & unchecked((int) 0xFFffFFff)) & + unchecked((int) 0xFFffFFff)); SetValue(cmd.IsByteMode, Mem, op1, result); } break; @@ -615,7 +664,7 @@ namespace SharpCompress.Compressor.Rar.VM int divider = GetValue(cmd.IsByteMode, Mem, op2); if (divider != 0) { - int result = GetValue(cmd.IsByteMode, Mem, op1) / divider; + int result = GetValue(cmd.IsByteMode, Mem, op1)/divider; SetValue(cmd.IsByteMode, Mem, op1, result); } } @@ -624,14 +673,21 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_ADC: { int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int FC = (int)(flags & VMFlags.VM_FC); - int result = (int)((long)value1 & 0xFFffFFff + (long)GetValue(cmd.IsByteMode, Mem, op2) & 0xFFffFFff + (long)FC & unchecked((int)0xFFffFFff)); + int FC = (int) (flags & VMFlags.VM_FC); + int result = + (int) + ((long) value1 & 0xFFffFFff + (long) GetValue(cmd.IsByteMode, Mem, op2) & + 0xFFffFFff + (long) 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))); + 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; @@ -639,13 +695,20 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_SBB: { int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int FC = (int)(flags & VMFlags.VM_FC); - int result = (int)((long)value1 & 0xFFffFFff - (long)GetValue(cmd.IsByteMode, Mem, op2) & 0xFFffFFff - (long)FC & unchecked((int)0xFFffFFff)); + int FC = (int) (flags & VMFlags.VM_FC); + int result = + (int) + ((long) value1 & 0xFFffFFff - (long) GetValue(cmd.IsByteMode, Mem, op2) & + 0xFFffFFff - (long) 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))); + 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; @@ -662,7 +725,7 @@ namespace SharpCompress.Compressor.Rar.VM case VMCommands.VM_STANDARD: - ExecuteStandardFilter((VMStandardFilters)(cmd.Op1.Data)); + ExecuteStandardFilter((VMStandardFilters) (cmd.Op1.Data)); break; case VMCommands.VM_PRINT: @@ -697,10 +760,9 @@ namespace SharpCompress.Compressor.Rar.VM VMStandardFilters filterType = IsStandardFilter(code, codeSize); if (filterType != VMStandardFilters.VMSF_NONE) { - VMPreparedCommand curCmd = new VMPreparedCommand(); curCmd.OpCode = VMCommands.VM_STANDARD; - curCmd.Op1.Data = (int)filterType; + curCmd.Op1.Data = (int) filterType; curCmd.Op1.Type = VMOpType.VM_OPNONE; curCmd.Op2.Type = VMOpType.VM_OPNONE; codeSize = 0; @@ -723,10 +785,10 @@ namespace SharpCompress.Compressor.Rar.VM if ((dataFlag & 0x8000) != 0) { - long dataSize = (long)((long)ReadData(this) & 0xffFFffFFL + 1L); + long dataSize = (long) ((long) ReadData(this) & 0xffFFffFFL + 1L); for (int i = 0; inAddr < codeSize && i < dataSize; i++) { - prg.StaticData.Add((byte)(GetBits() >> 8)); + prg.StaticData.Add((byte) (GetBits() >> 8)); AddBits(8); } } @@ -737,15 +799,15 @@ namespace SharpCompress.Compressor.Rar.VM int data = GetBits(); if ((data & 0x8000) == 0) { - curCmd.OpCode = (VMCommands)((data >> 12)); + curCmd.OpCode = (VMCommands) ((data >> 12)); AddBits(4); } else { - curCmd.OpCode = (VMCommands)((data >> 10) - 24); + curCmd.OpCode = (VMCommands) ((data >> 10) - 24); AddBits(6); } - if ((VMCmdFlags.VM_CmdFlags[(int)curCmd.OpCode] & VMCmdFlags.VMCF_BYTEMODE) != 0) + if ((VMCmdFlags.VM_CmdFlags[(int) curCmd.OpCode] & VMCmdFlags.VMCF_BYTEMODE) != 0) { curCmd.IsByteMode = (GetBits() >> 15) == 1 ? true : false; AddBits(1); @@ -757,7 +819,7 @@ namespace SharpCompress.Compressor.Rar.VM curCmd.Op1.Type = VMOpType.VM_OPNONE; curCmd.Op2.Type = VMOpType.VM_OPNONE; - int opNum = (VMCmdFlags.VM_CmdFlags[(int)curCmd.OpCode] & VMCmdFlags.VMCF_OPMASK); + int opNum = (VMCmdFlags.VM_CmdFlags[(int) curCmd.OpCode] & VMCmdFlags.VMCF_OPMASK); // TODO >>> CurCmd->Op1.Addr=CurCmd->Op2.Addr=NULL; << 0) { @@ -766,7 +828,9 @@ namespace SharpCompress.Compressor.Rar.VM decodeArg(curCmd.Op2, curCmd.IsByteMode); else { - if (curCmd.Op1.Type == VMOpType.VM_OPINT && (VMCmdFlags.VM_CmdFlags[(int)curCmd.OpCode] & (VMCmdFlags.VMCF_JUMP | VMCmdFlags.VMCF_PROC)) != 0) + if (curCmd.Op1.Type == VMOpType.VM_OPINT && + (VMCmdFlags.VM_CmdFlags[(int) curCmd.OpCode] & + (VMCmdFlags.VMCF_JUMP | VMCmdFlags.VMCF_PROC)) != 0) { int distance = curCmd.Op1.Data; if (distance >= 256) @@ -891,7 +955,6 @@ namespace SharpCompress.Compressor.Rar.VM { switch (cmd.OpCode) { - case VMCommands.VM_MOV: cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_MOVB : VMCommands.VM_MOVD; continue; @@ -900,7 +963,7 @@ namespace SharpCompress.Compressor.Rar.VM cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_CMPB : VMCommands.VM_CMPD; continue; } - if ((VMCmdFlags.VM_CmdFlags[(int)cmd.OpCode] & VMCmdFlags.VMCF_CHFLAGS) == 0) + if ((VMCmdFlags.VM_CmdFlags[(int) cmd.OpCode] & VMCmdFlags.VMCF_CHFLAGS) == 0) { continue; } @@ -908,7 +971,7 @@ namespace SharpCompress.Compressor.Rar.VM for (int i = commands.IndexOf(cmd) + 1; i < commands.Count; i++) { - int flags = VMCmdFlags.VM_CmdFlags[(int)commands[i].OpCode]; + int flags = VMCmdFlags.VM_CmdFlags[(int) commands[i].OpCode]; if ((flags & (VMCmdFlags.VMCF_JUMP | VMCmdFlags.VMCF_PROC | VMCmdFlags.VMCF_USEFLAGS)) != 0) { flagsRequired = true; @@ -925,7 +988,6 @@ namespace SharpCompress.Compressor.Rar.VM } switch (cmd.OpCode) { - case VMCommands.VM_ADD: cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_ADDB : VMCommands.VM_ADDD; continue; @@ -954,7 +1016,6 @@ namespace SharpCompress.Compressor.Rar.VM int data = rarVM.GetBits(); switch (data & 0xc000) { - case 0: rarVM.AddBits(6); return ((data >> 10) & 0xf); @@ -962,7 +1023,7 @@ namespace SharpCompress.Compressor.Rar.VM case 0x4000: if ((data & 0x3c00) == 0) { - data = unchecked((int)0xffffff00) | ((data >> 2) & 0xff); + data = unchecked((int) 0xffffff00) | ((data >> 2) & 0xff); rarVM.AddBits(14); } else @@ -985,20 +1046,28 @@ namespace SharpCompress.Compressor.Rar.VM data |= rarVM.GetBits(); rarVM.AddBits(16); return (data); - } } private VMStandardFilters IsStandardFilter(byte[] code, int codeSize) { - VMStandardFilterSignature[] stdList = new VMStandardFilterSignature[]{ - new VMStandardFilterSignature(53, 0xad576887, VMStandardFilters.VMSF_E8), - new VMStandardFilterSignature(57, 0x3cd7e57e, VMStandardFilters.VMSF_E8E9), - new VMStandardFilterSignature(120, 0x3769893f, VMStandardFilters.VMSF_ITANIUM), - new VMStandardFilterSignature(29, 0x0e06077d, VMStandardFilters.VMSF_DELTA), - new VMStandardFilterSignature(149, 0x1c2c5dc8, VMStandardFilters.VMSF_RGB), - new VMStandardFilterSignature(216, 0xbc85e701, VMStandardFilters.VMSF_AUDIO), - new VMStandardFilterSignature(40, 0x46b9c560, VMStandardFilters.VMSF_UPCASE)}; + VMStandardFilterSignature[] stdList = new VMStandardFilterSignature[] + { + new VMStandardFilterSignature(53, 0xad576887, + VMStandardFilters.VMSF_E8), + new VMStandardFilterSignature(57, 0x3cd7e57e, + VMStandardFilters.VMSF_E8E9), + new VMStandardFilterSignature(120, 0x3769893f, + VMStandardFilters.VMSF_ITANIUM), + new VMStandardFilterSignature(29, 0x0e06077d, + VMStandardFilters.VMSF_DELTA), + new VMStandardFilterSignature(149, 0x1c2c5dc8, + VMStandardFilters.VMSF_RGB), + new VMStandardFilterSignature(216, 0xbc85e701, + VMStandardFilters.VMSF_AUDIO), + new VMStandardFilterSignature(40, 0x46b9c560, + VMStandardFilters.VMSF_UPCASE) + }; uint CodeCRC = RarCRC.CheckCrc(0xffffffff, code, 0, code.Length) ^ 0xffffffff; for (int i = 0; i < stdList.Length; i++) { @@ -1014,20 +1083,19 @@ namespace SharpCompress.Compressor.Rar.VM { switch (filterType) { - case VMStandardFilters.VMSF_E8: case VMStandardFilters.VMSF_E8E9: { int dataSize = R[4]; - long fileOffset = R[6] & unchecked((int)0xFFffFFff); + 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 cmpByte2 = (byte) ((filterType == VMStandardFilters.VMSF_E8E9) ? 0xe9 : 0xe8); + for (int curPos = 0; curPos < dataSize - 4;) { byte curByte = Mem[curPos++]; if (curByte == 0xe8 || curByte == cmpByte2) @@ -1046,16 +1114,16 @@ namespace SharpCompress.Compressor.Rar.VM // #else long offset = curPos + fileOffset; long Addr = GetValue(false, Mem, curPos); - if ((Addr & unchecked((int)0x80000000)) != 0) + if ((Addr & unchecked((int) 0x80000000)) != 0) { - if (((Addr + offset) & unchecked((int)0x80000000)) == 0) - SetValue(false, Mem, curPos, (int)Addr + fileSize); + if (((Addr + offset) & unchecked((int) 0x80000000)) == 0) + SetValue(false, Mem, curPos, (int) Addr + fileSize); } else { - if (((Addr - fileSize) & unchecked((int)0x80000000)) != 0) + if (((Addr - fileSize) & unchecked((int) 0x80000000)) != 0) { - SetValue(false, Mem, curPos, (int)(Addr - offset)); + SetValue(false, Mem, curPos, (int) (Addr - offset)); } } // #endif @@ -1067,9 +1135,8 @@ namespace SharpCompress.Compressor.Rar.VM case VMStandardFilters.VMSF_ITANIUM: { - int dataSize = R[4]; - long fileOffset = R[6] & unchecked((int)0xFFffFFff); + long fileOffset = R[6] & unchecked((int) 0xFFffFFff); if (dataSize >= VM_GLOBALMEMADDR) { @@ -1077,7 +1144,7 @@ namespace SharpCompress.Compressor.Rar.VM } 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 = new byte[] { 4, 4, 6, 6, 0, 0, 7, 7, 4, 4, 0, 0, 4, 4, 0, 0 }; + byte[] Masks = new byte[] {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) @@ -1085,18 +1152,18 @@ namespace SharpCompress.Compressor.Rar.VM 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 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); + filterItanium_SetBits(curPos, (int) (offset - fileOffset) & 0xfffff, + startPos + 13, 20); } } } @@ -1108,12 +1175,12 @@ namespace SharpCompress.Compressor.Rar.VM case VMStandardFilters.VMSF_DELTA: { - int dataSize = R[4] & unchecked((int)0xFFffFFff); - int channels = R[0] & unchecked((int)0xFFffFFff); + 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, (int)dataSize); - if (dataSize >= VM_GLOBALMEMADDR / 2) + int border = (dataSize*2) & unchecked((int) 0xFFffFFff); + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, (int) dataSize); + if (dataSize >= VM_GLOBALMEMADDR/2) { break; } @@ -1125,7 +1192,7 @@ namespace SharpCompress.Compressor.Rar.VM byte PrevByte = 0; for (int destPos = dataSize + curChannel; destPos < border; destPos += channels) { - Mem[destPos] = (PrevByte = (byte)(PrevByte - Mem[srcPos++])); + Mem[destPos] = (PrevByte = (byte) (PrevByte - Mem[srcPos++])); } } } @@ -1139,7 +1206,7 @@ namespace SharpCompress.Compressor.Rar.VM int srcPos = 0; int destDataPos = dataSize; SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); - if (dataSize >= VM_GLOBALMEMADDR / 2 || posR < 0) + if (dataSize >= VM_GLOBALMEMADDR/2 || posR < 0) { break; } @@ -1154,12 +1221,12 @@ namespace SharpCompress.Compressor.Rar.VM if (upperPos >= 3) { int upperDataPos = destDataPos + upperPos; - int upperByte = Mem[(int)upperDataPos] & 0xff; + int upperByte = Mem[(int) upperDataPos] & 0xff; int upperLeftByte = Mem[upperDataPos - 3] & 0xff; predicted = prevByte + upperByte - upperLeftByte; - int pa = System.Math.Abs((int)(predicted - prevByte)); - int pb = System.Math.Abs((int)(predicted - upperByte)); - int pc = System.Math.Abs((int)(predicted - upperLeftByte)); + int pa = System.Math.Abs((int) (predicted - prevByte)); + int pb = System.Math.Abs((int) (predicted - upperByte)); + int pc = System.Math.Abs((int) (predicted - upperLeftByte)); if (pa <= pb && pa <= pc) { predicted = prevByte; @@ -1182,14 +1249,14 @@ namespace SharpCompress.Compressor.Rar.VM } prevByte = (predicted - Mem[srcPos++] & 0xff) & 0xff; - Mem[destDataPos + i] = (byte)(prevByte & 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); + Mem[destDataPos + i] = (byte) (Mem[destDataPos + i] + G); + Mem[destDataPos + i + 2] = (byte) (Mem[destDataPos + i + 2] + G); } } break; @@ -1201,7 +1268,7 @@ namespace SharpCompress.Compressor.Rar.VM int destDataPos = dataSize; //byte *SrcData=Mem,*DestData=SrcData+DataSize; SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); - if (dataSize >= VM_GLOBALMEMADDR / 2) + if (dataSize >= VM_GLOBALMEMADDR/2) { break; } @@ -1216,17 +1283,17 @@ namespace SharpCompress.Compressor.Rar.VM for (int i = curChannel, byteCount = 0; i < dataSize; i += channels, byteCount++) { D3 = D2; - D2 = (int)(prevDelta - D1); - D1 = (int)prevDelta; + D2 = (int) (prevDelta - D1); + D1 = (int) prevDelta; - long predicted = 8 * prevByte + K1 * D1 + K2 * D2 + K3 * D3; + long predicted = 8*prevByte + K1*D1 + K2*D2 + K3*D3; predicted = Utility.URShift(predicted, 3) & 0xff; - long curByte = (long)(Mem[srcPos++]); + long curByte = (long) (Mem[srcPos++]); predicted -= curByte; - Mem[destDataPos + i] = (byte)predicted; - prevDelta = (byte)(predicted - prevByte); + Mem[destDataPos + i] = (byte) predicted; + prevDelta = (byte) (predicted - prevByte); //fix java byte if (prevDelta >= 128) { @@ -1238,7 +1305,7 @@ namespace SharpCompress.Compressor.Rar.VM { curByte = 0 - (256 - curByte); } - int D = ((int)curByte) << 3; + int D = ((int) curByte) << 3; Dif[0] += System.Math.Abs(D); Dif[1] += System.Math.Abs(D - D1); @@ -1261,9 +1328,8 @@ namespace SharpCompress.Compressor.Rar.VM } Dif[j] = 0; } - switch ((int)numMinDif) + switch ((int) numMinDif) { - case 1: if (K1 >= -16) K1--; @@ -1303,7 +1369,7 @@ namespace SharpCompress.Compressor.Rar.VM case VMStandardFilters.VMSF_UPCASE: { int dataSize = R[4], srcPos = 0, destPos = dataSize; - if (dataSize >= VM_GLOBALMEMADDR / 2) + if (dataSize >= VM_GLOBALMEMADDR/2) { break; } @@ -1312,7 +1378,7 @@ namespace SharpCompress.Compressor.Rar.VM byte curByte = Mem[srcPos++]; if (curByte == 2 && (curByte = Mem[srcPos++]) != 2) { - curByte = (byte)(curByte - 32); + curByte = (byte) (curByte - 32); } Mem[destPos++] = curByte; } @@ -1325,32 +1391,32 @@ namespace SharpCompress.Compressor.Rar.VM private void filterItanium_SetBits(int curPos, int bitField, int bitPos, int bitCount) { - int inAddr = bitPos / 8; + int inAddr = bitPos/8; int inBit = bitPos & 7; - int andMask = Utility.URShift(unchecked((int)0xffffffff), (32 - bitCount)); + int andMask = Utility.URShift(unchecked((int) 0xffffffff), (32 - bitCount)); andMask = ~(andMask << inBit); bitField <<= inBit; for (int i = 0; i < 4; i++) { - Mem[curPos + inAddr + i] &= (byte)(andMask); - Mem[curPos + inAddr + i] |= (byte)(bitField); - andMask = (Utility.URShift(andMask, 8)) | unchecked((int)0xff000000); + Mem[curPos + inAddr + i] &= (byte) (andMask); + Mem[curPos + inAddr + i] |= (byte) (bitField); + andMask = (Utility.URShift(andMask, 8)) | unchecked((int) 0xff000000); bitField = Utility.URShift(bitField, 8); } } private int filterItanium_GetBits(int curPos, int bitPos, int bitCount) { - int inAddr = bitPos / 8; + int inAddr = bitPos/8; int inBit = bitPos & 7; - int bitField = (int)(Mem[curPos + inAddr++] & 0xff); - bitField |= (int)((Mem[curPos + inAddr++] & 0xff) << 8); - bitField |= (int)((Mem[curPos + inAddr++] & 0xff) << 16); - bitField |= (int)((Mem[curPos + inAddr] & 0xff) << 24); + int bitField = (int) (Mem[curPos + inAddr++] & 0xff); + bitField |= (int) ((Mem[curPos + inAddr++] & 0xff) << 8); + bitField |= (int) ((Mem[curPos + inAddr++] & 0xff) << 16); + bitField |= (int) ((Mem[curPos + inAddr] & 0xff) << 24); bitField = Utility.URShift(bitField, inBit); - return (bitField & (Utility.URShift(unchecked((int)0xffffffff), (32 - bitCount)))); + return (bitField & (Utility.URShift(unchecked((int) 0xffffffff), (32 - bitCount)))); } diff --git a/SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs b/SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs index b7f25dd7..d22785a2 100644 --- a/SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs +++ b/SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs @@ -12,6 +12,35 @@ namespace SharpCompress.Compressor.Rar.VM public const byte VMCF_USEFLAGS = 32; public const byte VMCF_CHFLAGS = 64; - public static byte[] VM_CmdFlags = new byte[] { VMCF_OP2 | VMCF_BYTEMODE, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP1 | VMCF_JUMP, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1, VMCF_OP1, VMCF_OP1 | VMCF_PROC, VMCF_OP0 | VMCF_PROC, VMCF_OP1 | VMCF_BYTEMODE, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP0, VMCF_OP0, VMCF_OP0 | VMCF_USEFLAGS, VMCF_OP0 | VMCF_CHFLAGS, VMCF_OP2, VMCF_OP2, VMCF_OP2 | VMCF_BYTEMODE, VMCF_OP2 | VMCF_BYTEMODE, VMCF_OP2 | VMCF_BYTEMODE, VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS, VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS, VMCF_OP0 }; + public static byte[] VM_CmdFlags = new byte[] + { + VMCF_OP2 | VMCF_BYTEMODE, VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, + VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, + VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP1 | VMCF_JUMP, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, + VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, + VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, + VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, + VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, + VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS, VMCF_OP1, VMCF_OP1, + VMCF_OP1 | VMCF_PROC, VMCF_OP0 | VMCF_PROC, VMCF_OP1 | VMCF_BYTEMODE, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS, + VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS, VMCF_OP0, VMCF_OP0, + VMCF_OP0 | VMCF_USEFLAGS, VMCF_OP0 | VMCF_CHFLAGS, VMCF_OP2, VMCF_OP2, + VMCF_OP2 | VMCF_BYTEMODE, VMCF_OP2 | VMCF_BYTEMODE, + VMCF_OP2 | VMCF_BYTEMODE, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS, + VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS, VMCF_OP0 + }; } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/VM/VMCommands.cs b/SharpCompress/Compressor/Rar/VM/VMCommands.cs index 95e554ba..7daeba86 100644 --- a/SharpCompress/Compressor/Rar/VM/VMCommands.cs +++ b/SharpCompress/Compressor/Rar/VM/VMCommands.cs @@ -9,6 +9,7 @@ namespace SharpCompress.Compressor.Rar.VM VM_JZ = 4, VM_JNZ = 5, VM_INC = 6, + VM_DEC = 7, VM_JMP = 8, @@ -16,6 +17,7 @@ namespace SharpCompress.Compressor.Rar.VM VM_AND = 10, VM_OR = 11, VM_TEST = 12, + VM_JS = 13, VM_JNS = 14, @@ -23,6 +25,7 @@ namespace SharpCompress.Compressor.Rar.VM VM_JBE = 16, VM_JA = 17, VM_JAE = 18, + VM_PUSH = 19, VM_POP = 20, @@ -30,6 +33,7 @@ namespace SharpCompress.Compressor.Rar.VM VM_RET = 22, VM_NOT = 23, VM_SHL = 24, + VM_SHR = 25, VM_SAR = 26, @@ -37,6 +41,7 @@ namespace SharpCompress.Compressor.Rar.VM VM_PUSHA = 28, VM_POPA = 29, VM_PUSHF = 30, + VM_POPF = 31, VM_MOVZX = 32, @@ -44,6 +49,7 @@ namespace SharpCompress.Compressor.Rar.VM VM_XCHG = 34, VM_MUL = 35, VM_DIV = 36, + VM_ADC = 37, VM_SBB = 38, @@ -60,6 +66,7 @@ namespace SharpCompress.Compressor.Rar.VM VM_SUBD = 47, VM_INCB = 48, VM_INCD = 49, + VM_DECB = 50, VM_DECD = 51, diff --git a/SharpCompress/Compressor/Rar/VM/VMPreparedCommand.cs b/SharpCompress/Compressor/Rar/VM/VMPreparedCommand.cs index 584b4fec..8b8f313c 100644 --- a/SharpCompress/Compressor/Rar/VM/VMPreparedCommand.cs +++ b/SharpCompress/Compressor/Rar/VM/VMPreparedCommand.cs @@ -1,4 +1,3 @@ - namespace SharpCompress.Compressor.Rar.VM { internal class VMPreparedCommand @@ -9,26 +8,10 @@ namespace SharpCompress.Compressor.Rar.VM Op2 = new VMPreparedOperand(); } - internal VMCommands OpCode - { - get; - set; - } - internal bool IsByteMode - { - get; - set; - } - internal VMPreparedOperand Op1 - { - get; - private set; - } + internal VMCommands OpCode { get; set; } + internal bool IsByteMode { get; set; } + internal VMPreparedOperand Op1 { get; private set; } - internal VMPreparedOperand Op2 - { - get; - private set; - } + internal VMPreparedOperand Op2 { get; private set; } } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/VM/VMPreparedOperand.cs b/SharpCompress/Compressor/Rar/VM/VMPreparedOperand.cs index ed88015a..35ad9eb2 100644 --- a/SharpCompress/Compressor/Rar/VM/VMPreparedOperand.cs +++ b/SharpCompress/Compressor/Rar/VM/VMPreparedOperand.cs @@ -1,27 +1,10 @@ - namespace SharpCompress.Compressor.Rar.VM { internal class VMPreparedOperand { - internal VMOpType Type - { - get; - set; - } - internal int Data - { - get; - set; - } - internal int Base - { - get; - set; - } - internal int Offset - { - get; - set; - } + internal VMOpType Type { get; set; } + internal int Data { get; set; } + internal int Base { get; set; } + internal int Offset { get; set; } } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/VM/VMPreparedProgram.cs b/SharpCompress/Compressor/Rar/VM/VMPreparedProgram.cs index da419052..6ea209f6 100644 --- a/SharpCompress/Compressor/Rar/VM/VMPreparedProgram.cs +++ b/SharpCompress/Compressor/Rar/VM/VMPreparedProgram.cs @@ -7,11 +7,7 @@ namespace SharpCompress.Compressor.Rar.VM internal List Commands = new List(); internal List AltCommands = new List(); - public int CommandCount - { - get; - set; - } + public int CommandCount { get; set; } internal List GlobalData = new List(); internal List StaticData = new List(); @@ -19,15 +15,7 @@ namespace SharpCompress.Compressor.Rar.VM // static data contained in DB operators internal int[] InitR = new int[7]; - internal int FilteredDataOffset - { - get; - set; - } - internal int FilteredDataSize - { - get; - set; - } + internal int FilteredDataOffset { get; set; } + internal int FilteredDataSize { get; set; } } } \ No newline at end of file diff --git a/SharpCompress/Compressor/Rar/VM/VMStandardFilterSignature.cs b/SharpCompress/Compressor/Rar/VM/VMStandardFilterSignature.cs index 7f4e3c39..e514c1d2 100644 --- a/SharpCompress/Compressor/Rar/VM/VMStandardFilterSignature.cs +++ b/SharpCompress/Compressor/Rar/VM/VMStandardFilterSignature.cs @@ -9,22 +9,10 @@ namespace SharpCompress.Compressor.Rar.VM this.Type = type; } - internal int Length - { - get; - private set; - } + internal int Length { get; private set; } - internal uint CRC - { - get; - private set; - } + internal uint CRC { get; private set; } - internal VMStandardFilters Type - { - get; - private set; - } + internal VMStandardFilters Type { get; private set; } } } \ No newline at end of file diff --git a/SharpCompress/IO/CountingWritableSubStream.cs b/SharpCompress/IO/CountingWritableSubStream.cs index f4e8f6ee..3ba15008 100644 --- a/SharpCompress/IO/CountingWritableSubStream.cs +++ b/SharpCompress/IO/CountingWritableSubStream.cs @@ -40,14 +40,8 @@ namespace SharpCompress.IO public override long Position { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) @@ -68,7 +62,7 @@ namespace SharpCompress.IO public override void Write(byte[] buffer, int offset, int count) { writableStream.Write(buffer, offset, count); - Count += (uint)count; + Count += (uint) count; } } -} +} \ No newline at end of file diff --git a/SharpCompress/IO/ListeningStream.cs b/SharpCompress/IO/ListeningStream.cs index 0b71b9e0..01a07f6f 100644 --- a/SharpCompress/IO/ListeningStream.cs +++ b/SharpCompress/IO/ListeningStream.cs @@ -22,34 +22,21 @@ namespace SharpCompress.IO } } - public Stream Stream - { - get; - private set; - } + public Stream Stream { get; private set; } public override bool CanRead { - get - { - return Stream.CanRead; - } + get { return Stream.CanRead; } } public override bool CanSeek { - get - { - return Stream.CanSeek; - } + get { return Stream.CanSeek; } } public override bool CanWrite { - get - { - return Stream.CanWrite; - } + get { return Stream.CanWrite; } } public override void Flush() @@ -59,22 +46,13 @@ namespace SharpCompress.IO public override long Length { - get - { - return Stream.Length; - } + get { return Stream.Length; } } public override long Position { - get - { - return Stream.Position; - } - set - { - Stream.Position = value; - } + get { return Stream.Position; } + set { Stream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) @@ -100,4 +78,4 @@ namespace SharpCompress.IO Stream.Write(buffer, offset, count); } } -} +} \ No newline at end of file diff --git a/SharpCompress/IO/MarkingBinaryReader.cs b/SharpCompress/IO/MarkingBinaryReader.cs index 3e5a0159..db8ead28 100644 --- a/SharpCompress/IO/MarkingBinaryReader.cs +++ b/SharpCompress/IO/MarkingBinaryReader.cs @@ -10,11 +10,7 @@ namespace SharpCompress.IO { } - public long CurrentReadByteCount - { - get; - private set; - } + public long CurrentReadByteCount { get; private set; } public void Mark() { @@ -63,7 +59,6 @@ namespace SharpCompress.IO public override char[] ReadChars(int count) { - throw new NotImplementedException(); } @@ -134,4 +129,4 @@ namespace SharpCompress.IO return base.ReadUInt64(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/IO/NonDisposingStream.cs b/SharpCompress/IO/NonDisposingStream.cs index 48d3e603..d7eb7db9 100644 --- a/SharpCompress/IO/NonDisposingStream.cs +++ b/SharpCompress/IO/NonDisposingStream.cs @@ -17,34 +17,21 @@ namespace SharpCompress.IO } } - public Stream Stream - { - get; - private set; - } + public Stream Stream { get; private set; } public override bool CanRead { - get - { - return Stream.CanRead; - } + get { return Stream.CanRead; } } public override bool CanSeek { - get - { - return Stream.CanSeek; - } + get { return Stream.CanSeek; } } public override bool CanWrite { - get - { - return Stream.CanWrite; - } + get { return Stream.CanWrite; } } public override void Flush() @@ -54,22 +41,13 @@ namespace SharpCompress.IO public override long Length { - get - { - return Stream.Length; - } + get { return Stream.Length; } } public override long Position { - get - { - return Stream.Position; - } - set - { - Stream.Position = value; - } + get { return Stream.Position; } + set { Stream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) @@ -92,4 +70,4 @@ namespace SharpCompress.IO Stream.Write(buffer, offset, count); } } -} +} \ No newline at end of file diff --git a/SharpCompress/IO/ReadOnlySubStream.cs b/SharpCompress/IO/ReadOnlySubStream.cs index bb67bb11..5309d756 100644 --- a/SharpCompress/IO/ReadOnlySubStream.cs +++ b/SharpCompress/IO/ReadOnlySubStream.cs @@ -18,40 +18,23 @@ namespace SharpCompress.IO } } - private long BytesLeftToRead - { - get; - set; - } + private long BytesLeftToRead { get; set; } - public Stream Stream - { - get; - private set; - } + public Stream Stream { get; private set; } public override bool CanRead { - get - { - return true; - } + get { return true; } } public override bool CanSeek { - get - { - return false; - } + get { return false; } } public override bool CanWrite { - get - { - return false; - } + get { return false; } } public override void Flush() @@ -61,29 +44,20 @@ namespace SharpCompress.IO public override long Length { - get - { - throw new System.NotImplementedException(); - } + get { throw new System.NotImplementedException(); } } public override long Position { - get - { - throw new System.NotImplementedException(); - } - set - { - throw new System.NotImplementedException(); - } + get { throw new System.NotImplementedException(); } + set { throw new System.NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) { if (BytesLeftToRead < count) { - count = (int)BytesLeftToRead; + count = (int) BytesLeftToRead; } int read = Stream.Read(buffer, offset, count); if (read > 0) @@ -108,4 +82,4 @@ namespace SharpCompress.IO throw new System.NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/IO/RewindableStream.cs b/SharpCompress/IO/RewindableStream.cs index 6e6d5e10..f86c75b9 100644 --- a/SharpCompress/IO/RewindableStream.cs +++ b/SharpCompress/IO/RewindableStream.cs @@ -55,7 +55,7 @@ namespace SharpCompress.IO byte[] data = bufferStream.ToArray(); long position = bufferStream.Position; bufferStream.SetLength(0); - bufferStream.Write(data, (int)position, data.Length - (int)position); + bufferStream.Write(data, (int) position, data.Length - (int) position); bufferStream.Position = 0; } IsRecording = true; @@ -88,10 +88,7 @@ namespace SharpCompress.IO public override long Position { - get - { - return stream.Position + bufferStream.Position - bufferStream.Length; - } + get { return stream.Position + bufferStream.Position - bufferStream.Length; } set { if (!isRewound) @@ -157,4 +154,4 @@ namespace SharpCompress.IO throw new System.NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/IO/StreamingMode.cs b/SharpCompress/IO/StreamingMode.cs index bdbd5fc8..95ca3d8c 100644 --- a/SharpCompress/IO/StreamingMode.cs +++ b/SharpCompress/IO/StreamingMode.cs @@ -1,9 +1,8 @@ - -namespace SharpCompress.IO +namespace SharpCompress.IO { internal enum StreamingMode { Streaming, Seekable, } -} +} \ No newline at end of file diff --git a/SharpCompress/LazyReadOnlyCollection.cs b/SharpCompress/LazyReadOnlyCollection.cs index dca31db8..5d4af66b 100644 --- a/SharpCompress/LazyReadOnlyCollection.cs +++ b/SharpCompress/LazyReadOnlyCollection.cs @@ -89,7 +89,7 @@ namespace SharpCompress internal IEnumerable GetLoaded() { - return backing; + return backing; } #region ICollection Members @@ -112,7 +112,6 @@ namespace SharpCompress public void CopyTo(T[] array, int arrayIndex) { - EnsureFullyLoaded(); backing.CopyTo(array, arrayIndex); } @@ -157,4 +156,4 @@ namespace SharpCompress #endregion } -} +} \ No newline at end of file diff --git a/SharpCompress/ReadOnlyCollection.cs b/SharpCompress/ReadOnlyCollection.cs index 9d127b38..aa8d1dbb 100644 --- a/SharpCompress/ReadOnlyCollection.cs +++ b/SharpCompress/ReadOnlyCollection.cs @@ -57,4 +57,4 @@ namespace SharpCompress throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/AbstractReader.cs b/SharpCompress/Reader/AbstractReader.cs index 62880144..d8c124bf 100644 --- a/SharpCompress/Reader/AbstractReader.cs +++ b/SharpCompress/Reader/AbstractReader.cs @@ -33,29 +33,19 @@ namespace SharpCompress.Reader internal Options Options { get; private set; } - public ArchiveType ArchiveType - { - get; - private set; - } + public ArchiveType ArchiveType { get; private set; } /// /// Current volume that the current entry resides in /// - public abstract TVolume Volume - { - get; - } + public abstract TVolume Volume { get; } /// /// Current file entry /// public TEntry Entry { - get - { - return entriesForCurrentReadStream.Current; - } + get { return entriesForCurrentReadStream.Current; } } #region IDisposable Members @@ -136,7 +126,7 @@ namespace SharpCompress.Reader } } - readonly byte[] skipBuffer = new byte[4096]; + private readonly byte[] skipBuffer = new byte[4096]; private void Skip() { @@ -147,11 +137,11 @@ namespace SharpCompress.Reader if (rawStream != null) { var bytesToAdvance = Entry.CompressedSize; - for (var i = 0; i < bytesToAdvance / skipBuffer.Length; i++) + for (var i = 0; i < bytesToAdvance/skipBuffer.Length; i++) { rawStream.Read(skipBuffer, 0, skipBuffer.Length); } - rawStream.Read(skipBuffer, 0, (int)(bytesToAdvance % skipBuffer.Length)); + rawStream.Read(skipBuffer, 0, (int) (bytesToAdvance%skipBuffer.Length)); return; } } @@ -206,10 +196,7 @@ namespace SharpCompress.Reader IEntry IReader.Entry { - get - { - return Entry; - } + get { return Entry; } } void IStreamListener.FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes) @@ -217,10 +204,10 @@ namespace SharpCompress.Reader if (CompressedBytesRead != null) { CompressedBytesRead(this, new CompressedBytesReadEventArgs() - { - CurrentFilePartCompressedBytesRead = currentPartCompressedBytes, - CompressedBytesRead = compressedReadBytes - }); + { + CurrentFilePartCompressedBytesRead = currentPartCompressedBytes, + CompressedBytesRead = compressedReadBytes + }); } } @@ -229,11 +216,11 @@ namespace SharpCompress.Reader if (FilePartExtractionBegin != null) { FilePartExtractionBegin(this, new FilePartExtractionBeginEventArgs() - { - CompressedSize = compressedSize, - Size = size, - Name = name, - }); + { + CompressedSize = compressedSize, + Size = size, + Name = name, + }); } } } diff --git a/SharpCompress/Reader/GZip/GZipReader.cs b/SharpCompress/Reader/GZip/GZipReader.cs index fbee0caa..d97bd552 100644 --- a/SharpCompress/Reader/GZip/GZipReader.cs +++ b/SharpCompress/Reader/GZip/GZipReader.cs @@ -29,7 +29,7 @@ namespace SharpCompress.Reader.GZip /// /// public static GZipReader Open(Stream stream, - Options options = Options.KeepStreamsOpen) + Options options = Options.KeepStreamsOpen) { stream.CheckNotNull("stream"); return new GZipReader(stream, options); @@ -42,4 +42,4 @@ namespace SharpCompress.Reader.GZip return GZipEntry.GetEntries(stream); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/IReader.Extensions.cs b/SharpCompress/Reader/IReader.Extensions.cs index cdbf7f13..53788af8 100644 --- a/SharpCompress/Reader/IReader.Extensions.cs +++ b/SharpCompress/Reader/IReader.Extensions.cs @@ -1,5 +1,6 @@ using System.IO; using SharpCompress.Common; + #if THREEFIVE using SharpCompress.Common.Rar.Headers; #endif @@ -16,6 +17,7 @@ namespace SharpCompress.Reader reader.WriteEntryTo(stream); } } + public static void WriteEntryTo(this IReader reader, FileInfo filePath) { using (Stream stream = filePath.Open(FileMode.Create)) @@ -28,7 +30,7 @@ namespace SharpCompress.Reader /// Extract all remaining unread entries to specific directory, retaining filename /// public static void WriteAllToDirectory(this IReader reader, string destinationDirectory, - ExtractOptions options = ExtractOptions.Overwrite) + ExtractOptions options = ExtractOptions.Overwrite) { while (reader.MoveToNextEntry()) { @@ -40,7 +42,7 @@ namespace SharpCompress.Reader /// Extract to specific directory, retaining filename /// public static void WriteEntryToDirectory(this IReader reader, string destinationDirectory, - ExtractOptions options = ExtractOptions.Overwrite) + ExtractOptions options = ExtractOptions.Overwrite) { string destinationFileName = string.Empty; string file = Path.GetFileName(reader.Entry.FilePath); @@ -75,7 +77,7 @@ namespace SharpCompress.Reader /// Extract to specific file /// public static void WriteEntryToFile(this IReader reader, string destinationFileName, - ExtractOptions options = ExtractOptions.Overwrite) + ExtractOptions options = ExtractOptions.Overwrite) { FileMode fm = FileMode.Create; @@ -94,4 +96,4 @@ namespace SharpCompress.Reader } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/IReader.cs b/SharpCompress/Reader/IReader.cs index f739f3ab..6fc2f5c5 100644 --- a/SharpCompress/Reader/IReader.cs +++ b/SharpCompress/Reader/IReader.cs @@ -9,15 +9,9 @@ namespace SharpCompress.Reader event EventHandler CompressedBytesRead; event EventHandler FilePartExtractionBegin; - ArchiveType ArchiveType - { - get; - } + ArchiveType ArchiveType { get; } - IEntry Entry - { - get; - } + IEntry Entry { get; } /// /// Decompresses the current entry to the stream. This cannot be called twice for the current entry. @@ -37,4 +31,4 @@ namespace SharpCompress.Reader /// EntryStream OpenEntryStream(); } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/Rar/MultiVolumeRarReader.cs b/SharpCompress/Reader/Rar/MultiVolumeRarReader.cs index 02edd169..68c77779 100644 --- a/SharpCompress/Reader/Rar/MultiVolumeRarReader.cs +++ b/SharpCompress/Reader/Rar/MultiVolumeRarReader.cs @@ -58,7 +58,8 @@ namespace SharpCompress.Reader.Rar private Stream tempStream; private bool isFirst = true; - internal MultiVolumeStreamEnumerator(MultiVolumeRarReader r, IEnumerator nextReadableStreams, Stream tempStream) + internal MultiVolumeStreamEnumerator(MultiVolumeRarReader r, IEnumerator nextReadableStreams, + Stream tempStream) { reader = r; this.nextReadableStreams = nextReadableStreams; @@ -75,11 +76,7 @@ namespace SharpCompress.Reader.Rar return this; } - public FilePart Current - { - get; - private set; - } + public FilePart Current { get; private set; } public void Dispose() { @@ -87,10 +84,7 @@ namespace SharpCompress.Reader.Rar object System.Collections.IEnumerator.Current { - get - { - return Current; - } + get { return Current; } } public bool MoveNext() @@ -129,4 +123,4 @@ namespace SharpCompress.Reader.Rar } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/Rar/NonSeekableStreamFilePart.cs b/SharpCompress/Reader/Rar/NonSeekableStreamFilePart.cs index c2c43977..ba9f3691 100644 --- a/SharpCompress/Reader/Rar/NonSeekableStreamFilePart.cs +++ b/SharpCompress/Reader/Rar/NonSeekableStreamFilePart.cs @@ -18,10 +18,7 @@ namespace SharpCompress.Reader.Rar internal override string FilePartName { - get - { - return "Unknown Stream - File Entry: " + base.FileHeader.FileName; - } + get { return "Unknown Stream - File Entry: " + base.FileHeader.FileName; } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/Rar/RarReader.cs b/SharpCompress/Reader/Rar/RarReader.cs index 0e5b2e85..cf26e06d 100644 --- a/SharpCompress/Reader/Rar/RarReader.cs +++ b/SharpCompress/Reader/Rar/RarReader.cs @@ -24,13 +24,11 @@ namespace SharpCompress.Reader.Rar public override RarVolume Volume { - get - { - return volume; - } + get { return volume; } } #region Open + /// /// Opens a RarReader for Non-seeking usage with a single volume /// @@ -54,6 +52,7 @@ namespace SharpCompress.Reader.Rar streams.CheckNotNull("streams"); return new MultiVolumeRarReader(streams, options); } + #endregion internal override IEnumerable GetEntries(Stream stream) @@ -74,7 +73,8 @@ namespace SharpCompress.Reader.Rar protected override EntryStream GetEntryStream() { return new EntryStream(new RarStream(pack, Entry.FileHeader, - new MultiVolumeReadOnlyStream(CreateFilePartEnumerableForCurrentEntry().Cast(), this))); + new MultiVolumeReadOnlyStream( + CreateFilePartEnumerableForCurrentEntry().Cast(), this))); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/Rar/RarReaderVolume.cs b/SharpCompress/Reader/Rar/RarReaderVolume.cs index 09f65f94..057c45d6 100644 --- a/SharpCompress/Reader/Rar/RarReaderVolume.cs +++ b/SharpCompress/Reader/Rar/RarReaderVolume.cs @@ -13,6 +13,7 @@ namespace SharpCompress.Reader.Rar : base(StreamingMode.Streaming, stream, options) { } + internal override RarFilePart CreateFilePart(FileHeader fileHeader, MarkHeader markHeader) { return new NonSeekableStreamFilePart(markHeader, fileHeader); @@ -27,11 +28,8 @@ namespace SharpCompress.Reader.Rar #if !PORTABLE public override FileInfo VolumeFile { - get - { - return null; - } + get { return null; } } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/Rar/SingleVolumeRarReader.cs b/SharpCompress/Reader/Rar/SingleVolumeRarReader.cs index 1388551a..028e628e 100644 --- a/SharpCompress/Reader/Rar/SingleVolumeRarReader.cs +++ b/SharpCompress/Reader/Rar/SingleVolumeRarReader.cs @@ -19,7 +19,8 @@ namespace SharpCompress.Reader.Rar { if (archive.IsMultiVolume) { - throw new MultiVolumeExtractionException("Streamed archive is a Multi-volume archive. Use different RarReader method to extract."); + throw new MultiVolumeExtractionException( + "Streamed archive is a Multi-volume archive. Use different RarReader method to extract."); } } @@ -28,4 +29,4 @@ namespace SharpCompress.Reader.Rar return stream; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/ReaderFactory.cs b/SharpCompress/Reader/ReaderFactory.cs index 7436eab6..52dbfeab 100644 --- a/SharpCompress/Reader/ReaderFactory.cs +++ b/SharpCompress/Reader/ReaderFactory.cs @@ -77,4 +77,4 @@ namespace SharpCompress.Reader throw new InvalidOperationException("Cannot determine compressed stream type."); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/Tar/TarReader.cs b/SharpCompress/Reader/Tar/TarReader.cs index de58a68a..80ff407e 100644 --- a/SharpCompress/Reader/Tar/TarReader.cs +++ b/SharpCompress/Reader/Tar/TarReader.cs @@ -18,7 +18,7 @@ namespace SharpCompress.Reader.Tar private readonly CompressionType compressionType; internal TarReader(Stream stream, CompressionType compressionType, - Options options) + Options options) : base(options, ArchiveType.Tar) { this.compressionType = compressionType; @@ -98,10 +98,9 @@ namespace SharpCompress.Reader.Tar #endregion - internal override IEnumerable GetEntries(Stream stream) { return TarEntry.GetEntries(StreamingMode.Streaming, stream, compressionType); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Reader/Zip/ZipReader.cs b/SharpCompress/Reader/Zip/ZipReader.cs index 9d1e448f..8bbc16b0 100644 --- a/SharpCompress/Reader/Zip/ZipReader.cs +++ b/SharpCompress/Reader/Zip/ZipReader.cs @@ -52,7 +52,7 @@ namespace SharpCompress.Reader.Zip case ZipHeaderType.LocalEntry: { yield return new ZipEntry(new StreamingZipFilePart(h as LocalEntryHeader, - stream)); + stream)); } break; case ZipHeaderType.DirectoryEnd: diff --git a/SharpCompress/Utility.cs b/SharpCompress/Utility.cs index dfbfb6c6..c3693482 100644 --- a/SharpCompress/Utility.cs +++ b/SharpCompress/Utility.cs @@ -37,7 +37,7 @@ namespace SharpCompress /// The resulting number from the shift operation public static int URShift(int number, long bits) { - return URShift(number, (int)bits); + return URShift(number, (int) bits); } /// @@ -62,7 +62,7 @@ namespace SharpCompress /// The resulting number from the shift operation public static long URShift(long number, long bits) { - return URShift(number, (int)bits); + return URShift(number, (int) bits); } /// @@ -82,7 +82,7 @@ namespace SharpCompress { throw new ArgumentException(); } - if ((fromindex < 0) || ((System.Array)array).Length < toindex) + if ((fromindex < 0) || ((System.Array) array).Length < toindex) { throw new IndexOutOfRangeException(); } @@ -183,10 +183,10 @@ namespace SharpCompress /// public static void writeIntBigEndian(byte[] array, int pos, int value) { - array[pos] = (byte)((Utility.URShift(value, 24)) & 0xff); - array[pos + 1] = (byte)((Utility.URShift(value, 16)) & 0xff); - array[pos + 2] = (byte)((Utility.URShift(value, 8)) & 0xff); - array[pos + 3] = (byte)((value) & 0xff); + array[pos] = (byte) ((Utility.URShift(value, 24)) & 0xff); + array[pos + 1] = (byte) ((Utility.URShift(value, 16)) & 0xff); + array[pos + 2] = (byte) ((Utility.URShift(value, 8)) & 0xff); + array[pos + 3] = (byte) ((value) & 0xff); } /// Write a short value into the byte array at the given position (little @@ -206,11 +206,11 @@ namespace SharpCompress Array.Copy(newBytes, 0, array, pos, newBytes.Length); } #else - unsafe public static void WriteLittleEndian(byte[] array, int pos, short value) + public static unsafe void WriteLittleEndian(byte[] array, int pos, short value) { fixed (byte* numRef = &(array[pos])) { - *((short*)numRef) = value; + *((short*) numRef) = value; } } #endif @@ -248,11 +248,11 @@ namespace SharpCompress Array.Copy(newBytes, 0, array, pos, newBytes.Length); } #else - unsafe public static void WriteLittleEndian(byte[] array, int pos, int value) + public static unsafe void WriteLittleEndian(byte[] array, int pos, int value) { fixed (byte* numRef = &(array[pos])) { - *((int*)numRef) = value; + *((int*) numRef) = value; } } #endif @@ -305,7 +305,7 @@ namespace SharpCompress public static void Skip(this Stream source, long advanceAmount) { - byte[] buffer = new byte[32 * 1024]; + byte[] buffer = new byte[32*1024]; int read = 0; int readCount = 0; do @@ -313,7 +313,7 @@ namespace SharpCompress readCount = buffer.Length; if (readCount > advanceAmount) { - readCount = (int)advanceAmount; + readCount = (int) advanceAmount; } read = source.Read(buffer, 0, readCount); if (read < 0) @@ -330,7 +330,7 @@ namespace SharpCompress public static void SkipAll(this Stream source) { - byte[] buffer = new byte[32 * 1024]; + byte[] buffer = new byte[32*1024]; do { } while (source.Read(buffer, 0, buffer.Length) == buffer.Length); @@ -339,21 +339,23 @@ namespace SharpCompress public static byte[] UInt32ToBigEndianBytes(uint x) { - return new byte[] { - (byte)((x >> 24) & 0xff), - (byte)((x >> 16) & 0xff), - (byte)((x >> 8) & 0xff), - (byte)(x & 0xff) }; + return new byte[] + { + (byte) ((x >> 24) & 0xff), + (byte) ((x >> 16) & 0xff), + (byte) ((x >> 8) & 0xff), + (byte) (x & 0xff) + }; } public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime) { - int year = iDate / 512 + 1980; - int month = iDate % 512 / 32; - int day = iDate % 512 % 32; - int hour = iTime / 2048; - int minute = iTime % 2048 / 32; - int second = iTime % 2048 % 32 * 2; + int year = iDate/512 + 1980; + int month = iDate%512/32; + int day = iDate%512%32; + int hour = iTime/2048; + int minute = iTime%2048/32; + int second = iTime%2048%32*2; if (iDate == UInt16.MaxValue || month == 0 || day == 0) { @@ -385,21 +387,22 @@ namespace SharpCompress { return 0; } - return (uint)( - (dateTime.Value.Second / 2) | (dateTime.Value.Minute << 5) | (dateTime.Value.Hour << 11) | - (dateTime.Value.Day << 16) | (dateTime.Value.Month << 21) | ((dateTime.Value.Year - 1980) << 25)); + return (uint) ( + (dateTime.Value.Second/2) | (dateTime.Value.Minute << 5) | (dateTime.Value.Hour << 11) | + (dateTime.Value.Day << 16) | (dateTime.Value.Month << 21) | + ((dateTime.Value.Year - 1980) << 25)); } public static DateTime DosDateToDateTime(UInt32 iTime) { - return DosDateToDateTime((UInt16)(iTime / 65536), - (UInt16)(iTime % 65536)); + return DosDateToDateTime((UInt16) (iTime/65536), + (UInt16) (iTime%65536)); } public static DateTime DosDateToDateTime(Int32 iTime) { - return DosDateToDateTime((UInt32)iTime); + return DosDateToDateTime((UInt32) iTime); } public static long TransferTo(this Stream source, Stream destination) @@ -453,7 +456,7 @@ namespace SharpCompress internal static void Extract(this TEntry entry, - AbstractArchive archive, Stream streamToWriteTo) + AbstractArchive archive, Stream streamToWriteTo) where TEntry : IArchiveEntry where TVolume : IVolume { @@ -464,7 +467,7 @@ namespace SharpCompress archive.EnsureEntriesLoaded(); archive.FireEntryExtractionBegin(entry); - ((IStreamListener)archive).FireFilePartExtractionBegin(entry.FilePath, entry.Size, entry.CompressedSize); + ((IStreamListener) archive).FireFilePartExtractionBegin(entry.FilePath, entry.Size, entry.CompressedSize); using (Stream s = new ListeningStream(archive, entry.OpenEntryStream())) { s.TransferTo(streamToWriteTo); @@ -506,4 +509,4 @@ namespace SharpCompress } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/VersionInfo.cs b/SharpCompress/VersionInfo.cs index c0a7877f..9cc28676 100644 --- a/SharpCompress/VersionInfo.cs +++ b/SharpCompress/VersionInfo.cs @@ -4,6 +4,7 @@ using System.Runtime.InteropServices; [assembly: ComVisible(false)] #endif + [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] @@ -11,4 +12,4 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.8.2.0")] -[assembly: AssemblyFileVersion("0.8.2.0")] +[assembly: AssemblyFileVersion("0.8.2.0")] \ No newline at end of file diff --git a/SharpCompress/Writer/AbstractWriter.cs b/SharpCompress/Writer/AbstractWriter.cs index 902c26ee..8ace64b3 100644 --- a/SharpCompress/Writer/AbstractWriter.cs +++ b/SharpCompress/Writer/AbstractWriter.cs @@ -53,4 +53,4 @@ namespace SharpCompress.Writer } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Writer/GZip/GZipWriter.cs b/SharpCompress/Writer/GZip/GZipWriter.cs index d8beaeea..a718aad1 100644 --- a/SharpCompress/Writer/GZip/GZipWriter.cs +++ b/SharpCompress/Writer/GZip/GZipWriter.cs @@ -19,12 +19,12 @@ namespace SharpCompress.Writer.GZip protected override void Dispose(bool isDisposing) { - if (isDisposing) - { - //dispose here to finish the GZip, GZip won't close the underlying stream - OutputStream.Dispose(); - } - base.Dispose(isDisposing); + if (isDisposing) + { + //dispose here to finish the GZip, GZip won't close the underlying stream + OutputStream.Dispose(); + } + base.Dispose(isDisposing); } public override void Write(string filename, Stream source, DateTime? modificationTime) @@ -40,4 +40,4 @@ namespace SharpCompress.Writer.GZip wroteToStream = true; } } -} +} \ No newline at end of file diff --git a/SharpCompress/Writer/IWriter.Extensions.cs b/SharpCompress/Writer/IWriter.Extensions.cs index 04bceb4d..4e5a7808 100644 --- a/SharpCompress/Writer/IWriter.Extensions.cs +++ b/SharpCompress/Writer/IWriter.Extensions.cs @@ -1,5 +1,6 @@ using System; using System.IO; + namespace SharpCompress.Writer { public static class IWriterExtensions @@ -16,10 +17,10 @@ namespace SharpCompress.Writer { throw new ArgumentException("Source does not exist: " + source.FullName); } - using (var stream = source.OpenRead()) - { - writer.Write(entryPath, stream, source.LastWriteTime); - } + using (var stream = source.OpenRead()) + { + writer.Write(entryPath, stream, source.LastWriteTime); + } } public static void Write(this IWriter writer, string entryPath, string source) @@ -27,7 +28,8 @@ namespace SharpCompress.Writer writer.Write(entryPath, new FileInfo(source)); } - public static void WriteAll(this IWriter writer, string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly) + public static void WriteAll(this IWriter writer, string directory, string searchPattern = "*", + SearchOption option = SearchOption.TopDirectoryOnly) { if (!Directory.Exists(directory)) { @@ -44,4 +46,4 @@ namespace SharpCompress.Writer } #endif } -} +} \ No newline at end of file diff --git a/SharpCompress/Writer/IWriter.cs b/SharpCompress/Writer/IWriter.cs index 9e277c45..2a94ceba 100644 --- a/SharpCompress/Writer/IWriter.cs +++ b/SharpCompress/Writer/IWriter.cs @@ -6,10 +6,7 @@ namespace SharpCompress.Writer { public interface IWriter : IDisposable { - ArchiveType WriterType - { - get; - } + ArchiveType WriterType { get; } void Write(string filename, Stream source, DateTime? modificationTime); } -} +} \ No newline at end of file diff --git a/SharpCompress/Writer/Tar/TarWriter.cs b/SharpCompress/Writer/Tar/TarWriter.cs index 5db5acab..a4afdc05 100644 --- a/SharpCompress/Writer/Tar/TarWriter.cs +++ b/SharpCompress/Writer/Tar/TarWriter.cs @@ -38,10 +38,12 @@ namespace SharpCompress.Writer.Tar } InitalizeStream(destination, false); } + public override void Write(string filename, Stream source, DateTime? modificationTime) { Write(filename, source, modificationTime, null); } + private string NormalizeFilename(string filename) { filename = filename.Replace('\\', '/'); @@ -52,6 +54,7 @@ namespace SharpCompress.Writer.Tar return filename.Trim('/'); } + public void Write(string filename, Stream source, DateTime? modificationTime, long? size) { if (!source.CanSeek && size == null) @@ -73,7 +76,7 @@ namespace SharpCompress.Writer.Tar private void PadTo512(long size, bool forceZeros) { - int zeros = (int)size % 512; + int zeros = (int) size%512; if (zeros == 0 && !forceZeros) { return; @@ -93,4 +96,4 @@ namespace SharpCompress.Writer.Tar base.Dispose(isDisposing); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Writer/WriterFactory.cs b/SharpCompress/Writer/WriterFactory.cs index 806e81da..7a17ec1c 100644 --- a/SharpCompress/Writer/WriterFactory.cs +++ b/SharpCompress/Writer/WriterFactory.cs @@ -9,21 +9,21 @@ namespace SharpCompress.Writer { public static class WriterFactory { - public static IWriter Open(Stream stream, ArchiveType archiveType, CompressionType compressionType) - { - return Open(stream, archiveType, new CompressionInfo - { - Type = compressionType - }); - } + public static IWriter Open(Stream stream, ArchiveType archiveType, CompressionType compressionType) + { + return Open(stream, archiveType, new CompressionInfo + { + Type = compressionType + }); + } - public static IWriter Open(Stream stream, ArchiveType archiveType, CompressionInfo compressionInfo) + public static IWriter Open(Stream stream, ArchiveType archiveType, CompressionInfo compressionInfo) { switch (archiveType) { case ArchiveType.GZip: { - if (compressionInfo.Type != CompressionType.GZip) + if (compressionInfo.Type != CompressionType.GZip) { throw new InvalidFormatException("GZip archives only support GZip compression type."); } @@ -44,4 +44,4 @@ namespace SharpCompress.Writer } } } -} +} \ No newline at end of file diff --git a/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs b/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs index 0633ae13..c1a4c1e8 100644 --- a/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs +++ b/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs @@ -22,7 +22,7 @@ namespace SharpCompress.Writer.Zip byte[] encodedFilename = Encoding.UTF8.GetBytes(FileName); byte[] encodedComment = Encoding.UTF8.GetBytes(Comment); - outputStream.Write(new byte[] { 80, 75, 1, 2, 0x3F, 0, 0x0A, 0 }, 0, 8); + outputStream.Write(new byte[] {80, 75, 1, 2, 0x3F, 0, 0x0A, 0}, 0, 8); HeaderFlags flags = HeaderFlags.UTF8; if (!outputStream.CanSeek) { @@ -32,28 +32,29 @@ namespace SharpCompress.Writer.Zip flags |= HeaderFlags.Bit1; // eos marker } } - outputStream.Write(BitConverter.GetBytes((ushort)flags), 0, 2); - outputStream.Write(BitConverter.GetBytes((ushort)compression), 0, 2); // zipping method - outputStream.Write(BitConverter.GetBytes(ModificationTime.DateTimeToDosTime()), 0, 4); // zipping date and time + outputStream.Write(BitConverter.GetBytes((ushort) flags), 0, 2); + outputStream.Write(BitConverter.GetBytes((ushort) compression), 0, 2); // zipping method + outputStream.Write(BitConverter.GetBytes(ModificationTime.DateTimeToDosTime()), 0, 4); + // zipping date and time outputStream.Write(BitConverter.GetBytes(Crc), 0, 4); // file CRC outputStream.Write(BitConverter.GetBytes(Compressed), 0, 4); // compressed file size outputStream.Write(BitConverter.GetBytes(Decompressed), 0, 4); // uncompressed file size - outputStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip - outputStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length - outputStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2); + outputStream.Write(BitConverter.GetBytes((ushort) encodedFilename.Length), 0, 2); // Filename in zip + outputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // extra length + outputStream.Write(BitConverter.GetBytes((ushort) encodedComment.Length), 0, 2); - outputStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // disk=0 - outputStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // file type: binary - outputStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // Internal file attributes - outputStream.Write(BitConverter.GetBytes((ushort)0x8100), 0, 2); // External file attributes (normal/readable) - outputStream.Write(BitConverter.GetBytes(HeaderOffset), 0, 4); // Offset of header + outputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // disk=0 + outputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // file type: binary + outputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // Internal file attributes + outputStream.Write(BitConverter.GetBytes((ushort) 0x8100), 0, 2); + // External file attributes (normal/readable) + outputStream.Write(BitConverter.GetBytes(HeaderOffset), 0, 4); // Offset of header outputStream.Write(encodedFilename, 0, encodedFilename.Length); outputStream.Write(encodedComment, 0, encodedComment.Length); - return (uint)(8 + 2 + 2 + 4 + 4 + 4 + 4 + 2 + 2 + 2 - + 2 + 2 + 2 + 2 + 4 + encodedFilename.Length + encodedComment.Length); - + return (uint) (8 + 2 + 2 + 4 + 4 + 4 + 4 + 2 + 2 + 2 + + 2 + 2 + 2 + 2 + 4 + encodedFilename.Length + encodedComment.Length); } } -} +} \ No newline at end of file diff --git a/SharpCompress/Writer/Zip/ZipWriter.cs b/SharpCompress/Writer/Zip/ZipWriter.cs index 96761ac5..4bbac268 100644 --- a/SharpCompress/Writer/Zip/ZipWriter.cs +++ b/SharpCompress/Writer/Zip/ZipWriter.cs @@ -103,9 +103,9 @@ namespace SharpCompress.Writer.Zip Comment = comment, FileName = entryPath, ModificationTime = modificationTime, - HeaderOffset = (uint)streamPosition, + HeaderOffset = (uint) streamPosition, }; - var headersize = (uint)WriteHeader(entryPath, modificationTime); + var headersize = (uint) WriteHeader(entryPath, modificationTime); streamPosition += headersize; return new ZipWritingStream(this, OutputStream, entry); } @@ -126,7 +126,7 @@ namespace SharpCompress.Writer.Zip byte[] encodedFilename = Encoding.UTF8.GetBytes(filename); OutputStream.Write(BitConverter.GetBytes(ZipHeaderFactory.ENTRY_HEADER_BYTES), 0, 4); - OutputStream.Write(new byte[] { 63, 0 }, 0, 2); //version + OutputStream.Write(new byte[] {63, 0}, 0, 2); //version HeaderFlags flags = HeaderFlags.UTF8; if (!OutputStream.CanSeek) { @@ -136,14 +136,14 @@ namespace SharpCompress.Writer.Zip flags |= HeaderFlags.Bit1; // eos marker } } - OutputStream.Write(BitConverter.GetBytes((ushort)flags), 0, 2); - OutputStream.Write(BitConverter.GetBytes((ushort)compression), 0, 2); // zipping method + OutputStream.Write(BitConverter.GetBytes((ushort) flags), 0, 2); + OutputStream.Write(BitConverter.GetBytes((ushort) compression), 0, 2); // zipping method OutputStream.Write(BitConverter.GetBytes(modificationTime.DateTimeToDosTime()), 0, 4); // zipping date and time - OutputStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12); + OutputStream.Write(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 12); // unused CRC, un/compressed size, updated later - OutputStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length - OutputStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length + OutputStream.Write(BitConverter.GetBytes((ushort) encodedFilename.Length), 0, 2); // filename length + OutputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // extra length OutputStream.Write(encodedFilename, 0, encodedFilename.Length); return 6 + 2 + 2 + 4 + 12 + 2 + 2 + encodedFilename.Length; @@ -160,12 +160,12 @@ namespace SharpCompress.Writer.Zip { byte[] encodedComment = Encoding.UTF8.GetBytes(zipComment); - OutputStream.Write(new byte[] { 80, 75, 5, 6, 0, 0, 0, 0 }, 0, 8); - OutputStream.Write(BitConverter.GetBytes((ushort)entries.Count), 0, 2); - OutputStream.Write(BitConverter.GetBytes((ushort)entries.Count), 0, 2); + OutputStream.Write(new byte[] {80, 75, 5, 6, 0, 0, 0, 0}, 0, 8); + OutputStream.Write(BitConverter.GetBytes((ushort) entries.Count), 0, 2); + OutputStream.Write(BitConverter.GetBytes((ushort) entries.Count), 0, 2); OutputStream.Write(BitConverter.GetBytes(size), 0, 4); - OutputStream.Write(BitConverter.GetBytes((uint)streamPosition), 0, 4); - OutputStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2); + OutputStream.Write(BitConverter.GetBytes((uint) streamPosition), 0, 4); + OutputStream.Write(BitConverter.GetBytes((ushort) encodedComment.Length), 0, 2); OutputStream.Write(encodedComment, 0, encodedComment.Length); } @@ -228,7 +228,8 @@ namespace SharpCompress.Writer.Zip } case ZipCompressionMethod.Deflate: { - return new DeflateStream(counting, CompressionMode.Compress, writer.deflateCompressionLevel, true); + return new DeflateStream(counting, CompressionMode.Compress, writer.deflateCompressionLevel, + true); } case ZipCompressionMethod.BZip2: { @@ -241,7 +242,8 @@ namespace SharpCompress.Writer.Zip counting.WriteByte(5); counting.WriteByte(0); - LzmaStream lzmaStream = new LzmaStream(new LzmaEncoderProperties(!originalStream.CanSeek), false, counting); + LzmaStream lzmaStream = new LzmaStream(new LzmaEncoderProperties(!originalStream.CanSeek), + false, counting); counting.Write(lzmaStream.Properties, 0, lzmaStream.Properties.Length); return lzmaStream; } @@ -263,7 +265,7 @@ namespace SharpCompress.Writer.Zip if (disposing) { writeStream.Dispose(); - entry.Crc = (uint)crc.Crc32Result; + entry.Crc = (uint) crc.Crc32Result; entry.Compressed = counting.Count; entry.Decompressed = decompressed; if (originalStream.CanSeek) @@ -307,7 +309,7 @@ namespace SharpCompress.Writer.Zip public override void Write(byte[] buffer, int offset, int count) { - decompressed += (uint)count; + decompressed += (uint) count; crc.SlurpBlock(buffer, offset, count); writeStream.Write(buffer, offset, count); }