diff --git a/SharpCompress.sln.DotSettings b/SharpCompress.sln.DotSettings index 17e39c24..d6a99be9 100644 --- a/SharpCompress.sln.DotSettings +++ b/SharpCompress.sln.DotSettings @@ -1,6 +1,119 @@  - D:\Git\sharpcompress\SharpCompress\sharpcompress.DotSettings - ..\SharpCompress\sharpcompress.DotSettings - True - True - 1 \ No newline at end of file + DO_NOT_SHOW + ERROR + ERROR + ERROR + ERROR + ERROR + ERROR + ERROR + ERROR + ERROR + DO_NOT_SHOW + + <?xml version="1.0" encoding="utf-16"?><Profile name="Basic Clean"><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSRemoveCodeRedundancies>True</CSRemoveCodeRedundancies><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSCodeStyleAttributes ArrangeTypeAccessModifier="False" ArrangeTypeMemberAccessModifier="False" SortModifiers="False" RemoveRedundantParentheses="False" AddMissingParentheses="False" ArrangeBraces="True" ArrangeAttributes="False" ArrangeArgumentsStyle="False" /><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CSReformatCode>True</CSReformatCode></Profile> + + Basic Clean + True + Named + Required + Required + Required + Required + True + True + True + True + True + True + True + True + True + True + True + True + 0 + 1 + + SEPARATE + ALWAYS_ADD + ALWAYS_ADD + ALWAYS_ADD + ALWAYS_ADD + ALWAYS_ADD + ALWAYS_ADD + True + 1 + 1 + False + False + True + False + True + + True + + LINE_BREAK + False + True + True + + + False + False + False + CHOP_IF_LONG + CHOP_IF_LONG + CHOP_IF_LONG + False + CHOP_IF_LONG + UseVarWhenEvident + UseVarWhenEvident + UseVarWhenEvident + + <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="I" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="T" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + True + True + True diff --git a/src/SharpCompress/Archive/AbstractArchive.cs b/src/SharpCompress/Archive/AbstractArchive.cs index 4d1e9d30..0d728fb3 100644 --- a/src/SharpCompress/Archive/AbstractArchive.cs +++ b/src/SharpCompress/Archive/AbstractArchive.cs @@ -54,7 +54,8 @@ namespace SharpCompress.Archive lazyVolumes = new LazyReadOnlyCollection(Enumerable.Empty()); lazyEntries = new LazyReadOnlyCollection(Enumerable.Empty()); } - public ArchiveType Type { get; private set; } + + public ArchiveType Type { get; } void IArchiveExtractionListener.FireEntryExtractionBegin(IArchiveEntry entry) { @@ -84,47 +85,29 @@ namespace SharpCompress.Archive /// /// Returns an ReadOnlyCollection of all the RarArchiveEntries across the one or many parts of the RarArchive. /// - public virtual ICollection Entries - { - get { return lazyEntries; } - } + public virtual ICollection Entries { get { return lazyEntries; } } /// /// Returns an ReadOnlyCollection of all the RarArchiveVolumes across the one or many parts of the RarArchive. /// - public ICollection Volumes - { - get { return lazyVolumes; } - } + public ICollection Volumes { get { return lazyVolumes; } } /// /// The total size of the files compressed in the archive. /// - public virtual long TotalSize - { - get { return Entries.Aggregate(0L, (total, cf) => total + cf.CompressedSize); } - } + public virtual long TotalSize { get { return Entries.Aggregate(0L, (total, cf) => total + cf.CompressedSize); } } /// /// The total size of the files as uncompressed in the archive. /// - public virtual long TotalUncompressSize - { - get { return Entries.Aggregate(0L, (total, cf) => total + cf.Size); } - } + public virtual long TotalUncompressSize { get { return Entries.Aggregate(0L, (total, cf) => total + cf.Size); } } protected abstract IEnumerable LoadVolumes(IEnumerable streams, Options options); protected abstract IEnumerable LoadEntries(IEnumerable volumes); - IEnumerable IArchive.Entries - { - get { return Entries.Cast(); } - } + IEnumerable IArchive.Entries { get { return Entries.Cast(); } } - IEnumerable IArchive.Volumes - { - get { return lazyVolumes.Cast(); } - } + IEnumerable IArchive.Volumes { get { return lazyVolumes.Cast(); } } private bool disposed; @@ -148,11 +131,11 @@ namespace SharpCompress.Archive { if (CompressedBytesRead != null) { - CompressedBytesRead(this, new CompressedBytesReadEventArgs() - { - CurrentFilePartCompressedBytesRead = currentPartCompressedBytes, - CompressedBytesRead = compressedReadBytes - }); + CompressedBytesRead(this, new CompressedBytesReadEventArgs + { + CurrentFilePartCompressedBytesRead = currentPartCompressedBytes, + CompressedBytesRead = compressedReadBytes + }); } } @@ -160,12 +143,12 @@ namespace SharpCompress.Archive { if (FilePartExtractionBegin != null) { - FilePartExtractionBegin(this, new FilePartExtractionBeginEventArgs() - { - CompressedSize = compressedSize, - Size = size, - Name = name, - }); + FilePartExtractionBegin(this, new FilePartExtractionBeginEventArgs + { + CompressedSize = compressedSize, + Size = size, + Name = name + }); } } @@ -191,11 +174,7 @@ namespace SharpCompress.Archive /// /// Archive is SOLID (this means the Archive saved bytes by reusing information which helps for archives containing many small files). /// - public virtual bool IsSolid - { - get { return false; } - } - + public virtual bool IsSolid { get { return false; } } /// /// The archive can find all the parts of the archive needed to fully extract the archive. This forces the parsing of the entire archive. diff --git a/src/SharpCompress/Archive/AbstractWritableArchive.cs b/src/SharpCompress/Archive/AbstractWritableArchive.cs index 8b0410aa..395c0ebe 100644 --- a/src/SharpCompress/Archive/AbstractWritableArchive.cs +++ b/src/SharpCompress/Archive/AbstractWritableArchive.cs @@ -53,10 +53,7 @@ namespace SharpCompress.Archive modifiedEntries.AddRange(OldEntries.Concat(newEntries)); } - private IEnumerable OldEntries - { - get { return base.Entries.Where(x => !removedEntries.Contains(x)); } - } + private IEnumerable OldEntries { get { return base.Entries.Where(x => !removedEntries.Contains(x)); } } public void RemoveEntry(TEntry entry) { @@ -66,25 +63,25 @@ namespace SharpCompress.Archive RebuildModifiedCollection(); } } + void IWritableArchive.RemoveEntry(IArchiveEntry entry) { RemoveEntry((TEntry)entry); } public TEntry AddEntry(string key, Stream source, - long size = 0, DateTime? modified = null) + long size = 0, DateTime? modified = null) { return AddEntry(key, source, false, size, modified); } - IArchiveEntry IWritableArchive.AddEntry(string key, Stream source, bool closeStream, long size, DateTime? modified) { return AddEntry(key, source, closeStream, size, modified); } public TEntry AddEntry(string key, Stream source, bool closeStream, - long size = 0, DateTime? modified = null) + long size = 0, DateTime? modified = null) { if (key.StartsWith("/") || key.StartsWith("\\")) @@ -105,7 +102,7 @@ namespace SharpCompress.Archive { foreach (var path in Entries.Select(x => x.Key)) { - var p = path.Replace('/','\\'); + var p = path.Replace('/', '\\'); if (p.StartsWith("\\")) { p = p.Substring(1); @@ -123,7 +120,7 @@ namespace SharpCompress.Archive } protected TEntry CreateEntry(string key, Stream source, long size, DateTime? modified, - bool closeStream) + bool closeStream) { if (!source.CanRead || !source.CanSeek) { @@ -133,7 +130,7 @@ namespace SharpCompress.Archive } protected abstract TEntry CreateEntryInternal(string key, Stream source, long size, DateTime? modified, - bool closeStream); + bool closeStream); protected abstract void SaveTo(Stream stream, CompressionInfo compressionType, IEnumerable oldEntries, IEnumerable newEntries); diff --git a/src/SharpCompress/Archive/ArchiveFactory.cs b/src/SharpCompress/Archive/ArchiveFactory.cs index 60b42fcb..4a6b5615 100644 --- a/src/SharpCompress/Archive/ArchiveFactory.cs +++ b/src/SharpCompress/Archive/ArchiveFactory.cs @@ -45,8 +45,8 @@ namespace SharpCompress.Archive stream.Seek(0, SeekOrigin.Begin); if (RarArchive.IsRarFile(stream, options)) { - stream.Seek(0, SeekOrigin.Begin); - return RarArchive.Open(stream, options); + stream.Seek(0, SeekOrigin.Begin); + return RarArchive.Open(stream, options); } stream.Seek(0, SeekOrigin.Begin); if (TarArchive.IsTarFile(stream)) @@ -62,29 +62,30 @@ namespace SharpCompress.Archive switch (type) { case ArchiveType.Zip: - { - return ZipArchive.Create(); - } + { + return ZipArchive.Create(); + } case ArchiveType.Tar: - { - return TarArchive.Create(); - } + { + return TarArchive.Create(); + } case ArchiveType.GZip: - { - return GZipArchive.Create(); - } + { + return GZipArchive.Create(); + } default: - { - throw new NotSupportedException("Cannot create Archives of type: " + type); - } + { + throw new NotSupportedException("Cannot create Archives of type: " + type); + } } } #if !NO_FILE - /// - /// Constructor expects a filepath to an existing file. - /// - /// + +/// +/// Constructor expects a filepath to an existing file. +/// +/// public static IArchive Open(string filePath) { return Open(filePath, Options.None); diff --git a/src/SharpCompress/Archive/GZip/GZipArchive.cs b/src/SharpCompress/Archive/GZip/GZipArchive.cs index 2de0a2bd..62065c17 100644 --- a/src/SharpCompress/Archive/GZip/GZipArchive.cs +++ b/src/SharpCompress/Archive/GZip/GZipArchive.cs @@ -13,10 +13,11 @@ namespace SharpCompress.Archive.GZip public class GZipArchive : AbstractWritableArchive { #if !NO_FILE - /// - /// Constructor expects a filepath to an existing file. - /// - /// + +/// +/// Constructor expects a filepath to an existing file. +/// +/// public static GZipArchive Open(string filePath) { return Open(filePath, Options.None); @@ -81,11 +82,12 @@ namespace SharpCompress.Archive.GZip } #if !NO_FILE - /// - /// Constructor with a FileInfo object to an existing file. - /// - /// - /// + +/// +/// Constructor with a FileInfo object to an existing file. +/// +/// +/// internal GZipArchive(FileInfo fileInfo, Options options) : base(ArchiveType.GZip, fileInfo, options) { @@ -135,13 +137,19 @@ namespace SharpCompress.Archive.GZip // workitem 8501: handle edge case (decompress empty stream) if (n == 0) + { return false; + } if (n != 10) + { return false; + } if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) + { return false; + } return true; } @@ -167,7 +175,7 @@ namespace SharpCompress.Archive.GZip } protected override GZipArchiveEntry CreateEntryInternal(string filePath, Stream source, long size, DateTime? modified, - bool closeStream) + bool closeStream) { if (Entries.Any()) { diff --git a/src/SharpCompress/Archive/GZip/GZipArchiveEntry.cs b/src/SharpCompress/Archive/GZip/GZipArchiveEntry.cs index 6c46f7a1..1b90ea32 100644 --- a/src/SharpCompress/Archive/GZip/GZipArchiveEntry.cs +++ b/src/SharpCompress/Archive/GZip/GZipArchiveEntry.cs @@ -6,7 +6,6 @@ namespace SharpCompress.Archive.GZip { public class GZipArchiveEntry : GZipEntry, IArchiveEntry { - internal GZipArchiveEntry(GZipArchive archive, GZipFilePart part) : base(part) { @@ -19,12 +18,10 @@ namespace SharpCompress.Archive.GZip } #region IArchiveEntry Members - public IArchive Archive { get; private set; } - public bool IsComplete - { - get { return true; } - } + public IArchive Archive { get; } + + public bool IsComplete { get { return true; } } #endregion } diff --git a/src/SharpCompress/Archive/GZip/GZipWritableArchiveEntry.cs b/src/SharpCompress/Archive/GZip/GZipWritableArchiveEntry.cs index 0c5067b5..9c05ca3c 100644 --- a/src/SharpCompress/Archive/GZip/GZipWritableArchiveEntry.cs +++ b/src/SharpCompress/Archive/GZip/GZipWritableArchiveEntry.cs @@ -8,9 +8,6 @@ namespace SharpCompress.Archive.GZip { internal class GZipWritableArchiveEntry : GZipArchiveEntry, IWritableArchiveEntry { - private readonly string path; - private readonly long size; - private readonly DateTime? lastModified; private readonly bool closeStream; private readonly Stream stream; @@ -19,79 +16,37 @@ namespace SharpCompress.Archive.GZip : base(archive, null) { this.stream = stream; - this.path = path; - this.size = size; - this.lastModified = lastModified; + Key = path; + Size = size; + LastModifiedTime = lastModified; this.closeStream = closeStream; } - public override long Crc - { - get { return 0; } - } + public override long Crc { get { return 0; } } - public override string Key - { - get { return path; } - } + public override string Key { get; } - public override long CompressedSize - { - get { return 0; } - } + public override long CompressedSize { get { return 0; } } - public override long Size - { - get { return size; } - } + public override long Size { get; } - public override DateTime? LastModifiedTime - { - get { return lastModified; } - } + public override DateTime? LastModifiedTime { get; } - public override DateTime? CreatedTime - { - get { return null; } - } + public override DateTime? CreatedTime { get { return null; } } - public override DateTime? LastAccessedTime - { - get { return null; } - } + public override DateTime? LastAccessedTime { get { return null; } } - public override DateTime? ArchivedTime - { - get { return null; } - } + public override DateTime? ArchivedTime { get { return null; } } - public override bool IsEncrypted - { - get { return false; } - } + public override bool IsEncrypted { get { return false; } } - public override bool IsDirectory - { - get { return false; } - } + public override bool IsDirectory { get { return false; } } - public override bool IsSplit - { - get { return false; } - } + public override bool IsSplit { get { return false; } } - internal override IEnumerable Parts - { - get { throw new NotImplementedException(); } - } + internal override IEnumerable Parts { get { throw new NotImplementedException(); } } - Stream IWritableArchiveEntry.Stream - { - get - { - return stream; - } - } + Stream IWritableArchiveEntry.Stream { get { return stream; } } public override Stream OpenEntryStream() { diff --git a/src/SharpCompress/Archive/IArchive.Extensions.cs b/src/SharpCompress/Archive/IArchive.Extensions.cs index d5823d75..60390dcd 100644 --- a/src/SharpCompress/Archive/IArchive.Extensions.cs +++ b/src/SharpCompress/Archive/IArchive.Extensions.cs @@ -1,14 +1,12 @@ -using System.Linq; -using SharpCompress.Common; - -namespace SharpCompress.Archive +namespace SharpCompress.Archive { public static class IArchiveExtensions { #if !NO_FILE - /// - /// Extract to specific directory, retaining filename - /// + +/// +/// Extract to specific directory, retaining filename +/// public static void WriteToDirectory(this IArchive archive, string destinationDirectory, ExtractOptions options = ExtractOptions.Overwrite) { diff --git a/src/SharpCompress/Archive/IArchiveEntry.Extensions.cs b/src/SharpCompress/Archive/IArchiveEntry.Extensions.cs index b84741fc..54160f38 100644 --- a/src/SharpCompress/Archive/IArchiveEntry.Extensions.cs +++ b/src/SharpCompress/Archive/IArchiveEntry.Extensions.cs @@ -28,17 +28,20 @@ namespace SharpCompress.Archive return; } using (entryStream) - using (Stream s = new ListeningStream(streamListener, entryStream)) { - s.TransferTo(streamToWriteTo); + using (Stream s = new ListeningStream(streamListener, entryStream)) + { + s.TransferTo(streamToWriteTo); + } } streamListener.FireEntryExtractionEnd(archiveEntry); } #if !NO_FILE - /// - /// Extract to specific directory, retaining filename - /// + +/// +/// Extract to specific directory, retaining filename +/// public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory, ExtractOptions options = ExtractOptions.Overwrite) { diff --git a/src/SharpCompress/Archive/IWritableArchive.Extensions.cs b/src/SharpCompress/Archive/IWritableArchive.Extensions.cs index d4ec0f8d..c1684696 100644 --- a/src/SharpCompress/Archive/IWritableArchive.Extensions.cs +++ b/src/SharpCompress/Archive/IWritableArchive.Extensions.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; using SharpCompress.Common; namespace SharpCompress.Archive @@ -7,7 +6,7 @@ namespace SharpCompress.Archive public static class IWritableArchiveExtensions { public static void SaveTo(this IWritableArchive writableArchive, - Stream stream, CompressionType compressionType) + Stream stream, CompressionType compressionType) { writableArchive.SaveTo(stream, new CompressionInfo {Type = compressionType}); } diff --git a/src/SharpCompress/Archive/Rar/FileInfoRarArchiveVolume.cs b/src/SharpCompress/Archive/Rar/FileInfoRarArchiveVolume.cs index 2404bff3..039c48db 100644 --- a/src/SharpCompress/Archive/Rar/FileInfoRarArchiveVolume.cs +++ b/src/SharpCompress/Archive/Rar/FileInfoRarArchiveVolume.cs @@ -1,4 +1,5 @@ -#if !NO_FILE + +#if !NO_FILE using System.Collections.Generic; using System.IO; using SharpCompress.Common; diff --git a/src/SharpCompress/Archive/Rar/FileInfoRarFilePart.cs b/src/SharpCompress/Archive/Rar/FileInfoRarFilePart.cs index f018d873..8f67834b 100644 --- a/src/SharpCompress/Archive/Rar/FileInfoRarFilePart.cs +++ b/src/SharpCompress/Archive/Rar/FileInfoRarFilePart.cs @@ -1,4 +1,5 @@ -#if !NO_FILE + +#if !NO_FILE using System.IO; using SharpCompress.Common.Rar; using SharpCompress.Common.Rar.Headers; diff --git a/src/SharpCompress/Archive/Rar/RarArchive.cs b/src/SharpCompress/Archive/Rar/RarArchive.cs index a66d5dca..e0fcccc8 100644 --- a/src/SharpCompress/Archive/Rar/RarArchive.cs +++ b/src/SharpCompress/Archive/Rar/RarArchive.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -14,20 +13,16 @@ namespace SharpCompress.Archive.Rar { public class RarArchive : AbstractArchive { - private readonly Unpack unpack = new Unpack(); - - internal Unpack Unpack - { - get { return unpack; } - } + internal Unpack Unpack { get; } = new Unpack(); #if !NO_FILE - /// - /// Constructor with a FileInfo object to an existing file. - /// - /// - /// - /// + +/// +/// Constructor with a FileInfo object to an existing file. +/// +/// +/// +/// internal RarArchive(FileInfo fileInfo, Options options, string password) : base(ArchiveType.Rar, fileInfo, options, password) { @@ -67,20 +62,18 @@ namespace SharpCompress.Archive.Rar return RarReader.Open(stream, Password); } - public override bool IsSolid - { - get { return Volumes.First().IsSolidArchive; } - } + public override bool IsSolid { get { return Volumes.First().IsSolidArchive; } } #region Creation #if !NO_FILE - /// - /// Constructor expects a filepath to an existing file. - /// - /// - /// - /// + +/// +/// Constructor expects a filepath to an existing file. +/// +/// +/// +/// public static RarArchive Open(string filePath, Options options = Options.None, string password = null) { filePath.CheckNotNullOrEmpty("filePath"); @@ -99,6 +92,7 @@ namespace SharpCompress.Archive.Rar return new RarArchive(fileInfo, options, password); } #endif + /// /// Takes a seekable Stream as a source /// diff --git a/src/SharpCompress/Archive/Rar/RarArchiveEntry.cs b/src/SharpCompress/Archive/Rar/RarArchiveEntry.cs index c655604b..fcf6292c 100644 --- a/src/SharpCompress/Archive/Rar/RarArchiveEntry.cs +++ b/src/SharpCompress/Archive/Rar/RarArchiveEntry.cs @@ -20,28 +20,13 @@ namespace SharpCompress.Archive.Rar this.archive = archive; } - public override CompressionType CompressionType - { - get { return CompressionType.Rar; } - } + public override CompressionType CompressionType { get { return CompressionType.Rar; } } - public IArchive Archive - { - get - { - return archive; - } - } + public IArchive Archive { get { return archive; } } - internal override IEnumerable Parts - { - get { return parts.Cast(); } - } + internal override IEnumerable Parts { get { return parts.Cast(); } } - internal override FileHeader FileHeader - { - get { return parts.First().FileHeader; } - } + internal override FileHeader FileHeader { get { return parts.First().FileHeader; } } public override long Crc { @@ -49,11 +34,10 @@ namespace SharpCompress.Archive.Rar { CheckIncomplete(); return parts.Select(fp => fp.FileHeader) - .Single(fh => !fh.FileFlags.HasFlag(FileFlags.SPLIT_AFTER)).FileCRC; + .Single(fh => !fh.FileFlags.HasFlag(FileFlags.SPLIT_AFTER)).FileCRC; } } - public override long Size { get @@ -81,10 +65,7 @@ namespace SharpCompress.Archive.Rar return new RarStream(archive.Unpack, FileHeader, new MultiVolumeReadOnlyStream(Parts.Cast(), archive)); } - public bool IsComplete - { - get { return parts.Select(fp => fp.FileHeader).Any(fh => !fh.FileFlags.HasFlag(FileFlags.SPLIT_AFTER)); } - } + public bool IsComplete { get { return parts.Select(fp => fp.FileHeader).Any(fh => !fh.FileFlags.HasFlag(FileFlags.SPLIT_AFTER)); } } private void CheckIncomplete() { diff --git a/src/SharpCompress/Archive/Rar/RarArchiveEntryFactory.cs b/src/SharpCompress/Archive/Rar/RarArchiveEntryFactory.cs index ec55c28d..4e10b97f 100644 --- a/src/SharpCompress/Archive/Rar/RarArchiveEntryFactory.cs +++ b/src/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(); diff --git a/src/SharpCompress/Archive/Rar/RarArchiveVolumeFactory.cs b/src/SharpCompress/Archive/Rar/RarArchiveVolumeFactory.cs index e9ef9a6c..15e4ffd1 100644 --- a/src/SharpCompress/Archive/Rar/RarArchiveVolumeFactory.cs +++ b/src/SharpCompress/Archive/Rar/RarArchiveVolumeFactory.cs @@ -1,9 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using SharpCompress.Common.Rar.Headers; using SharpCompress.Common; using SharpCompress.Common.Rar; diff --git a/src/SharpCompress/Archive/Rar/SeekableFilePart.cs b/src/SharpCompress/Archive/Rar/SeekableFilePart.cs index f052f22a..888f97d2 100644 --- a/src/SharpCompress/Archive/Rar/SeekableFilePart.cs +++ b/src/SharpCompress/Archive/Rar/SeekableFilePart.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; using SharpCompress.Common.Rar; using SharpCompress.Common.Rar.Headers; @@ -29,9 +28,6 @@ namespace SharpCompress.Archive.Rar return stream; } - internal override string FilePartName - { - get { return "Unknown Stream - File Entry: " + FileHeader.FileName; } - } + internal override string FilePartName { get { return "Unknown Stream - File Entry: " + FileHeader.FileName; } } } } \ No newline at end of file diff --git a/src/SharpCompress/Archive/SevenZip/SevenZipArchive.cs b/src/SharpCompress/Archive/SevenZip/SevenZipArchive.cs index 73711721..c1a9e44b 100644 --- a/src/SharpCompress/Archive/SevenZip/SevenZipArchive.cs +++ b/src/SharpCompress/Archive/SevenZip/SevenZipArchive.cs @@ -13,10 +13,11 @@ namespace SharpCompress.Archive.SevenZip { private ArchiveDatabase database; #if !NO_FILE - /// - /// Constructor expects a filepath to an existing file. - /// - /// + +/// +/// Constructor expects a filepath to an existing file. +/// +/// public static SevenZipArchive Open(string filePath) { return Open(filePath, Options.None); @@ -156,7 +157,6 @@ namespace SharpCompress.Archive.SevenZip } } - public static bool IsSevenZipFile(Stream stream) { try @@ -169,7 +169,7 @@ namespace SharpCompress.Archive.SevenZip } } - private static readonly byte[] SIGNATURE = new byte[] {(byte) '7', (byte) 'z', 0xBC, 0xAF, 0x27, 0x1C}; + private static readonly byte[] SIGNATURE = {(byte)'7', (byte)'z', 0xBC, 0xAF, 0x27, 0x1C}; private static bool SignatureMatch(Stream stream) { @@ -183,10 +183,7 @@ namespace SharpCompress.Archive.SevenZip return new SevenZipReader(this); } - public override bool IsSolid - { - get { return Entries.Where(x => !x.IsDirectory).GroupBy(x => x.FilePart.Folder).Count() > 1; } - } + public override bool IsSolid { get { return Entries.Where(x => !x.IsDirectory).GroupBy(x => x.FilePart.Folder).Count() > 1; } } public override long TotalSize { @@ -210,11 +207,7 @@ namespace SharpCompress.Archive.SevenZip this.archive = archive; } - - public override SevenZipVolume Volume - { - get { return archive.Volumes.Single(); } - } + public override SevenZipVolume Volume { get { return archive.Volumes.Single(); } } internal override IEnumerable GetEntries(Stream stream) { diff --git a/src/SharpCompress/Archive/SevenZip/SevenZipArchiveEntry.cs b/src/SharpCompress/Archive/SevenZip/SevenZipArchiveEntry.cs index 24eb07d6..dd3595ec 100644 --- a/src/SharpCompress/Archive/SevenZip/SevenZipArchiveEntry.cs +++ b/src/SharpCompress/Archive/SevenZip/SevenZipArchiveEntry.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; using SharpCompress.Common.SevenZip; namespace SharpCompress.Archive.SevenZip @@ -16,19 +15,14 @@ namespace SharpCompress.Archive.SevenZip { return FilePart.GetCompressedStream(); } - public IArchive Archive { get; private set; } - public bool IsComplete - { - get { return true; } - } + public IArchive Archive { get; } + + public bool IsComplete { get { return true; } } /// /// This is a 7Zip Anti item /// - public bool IsAnti - { - get { return FilePart.Header.IsAnti; } - } + public bool IsAnti { get { return FilePart.Header.IsAnti; } } } } \ No newline at end of file diff --git a/src/SharpCompress/Archive/Tar/TarArchive.cs b/src/SharpCompress/Archive/Tar/TarArchive.cs index 57b2a0b7..6cffec99 100644 --- a/src/SharpCompress/Archive/Tar/TarArchive.cs +++ b/src/SharpCompress/Archive/Tar/TarArchive.cs @@ -15,10 +15,11 @@ namespace SharpCompress.Archive.Tar public class TarArchive : AbstractWritableArchive { #if !NO_FILE - /// - /// Constructor expects a filepath to an existing file. - /// - /// + +/// +/// Constructor expects a filepath to an existing file. +/// +/// public static TarArchive Open(string filePath) { return Open(filePath, Options.None); @@ -102,7 +103,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 { @@ -111,11 +112,12 @@ namespace SharpCompress.Archive.Tar } #if !NO_FILE - /// - /// Constructor with a FileInfo object to an existing file. - /// - /// - /// + +/// +/// Constructor with a FileInfo object to an existing file. +/// +/// +/// internal TarArchive(FileInfo fileInfo, Options options) : base(ArchiveType.Tar, fileInfo, options) { @@ -172,14 +174,16 @@ namespace SharpCompress.Archive.Tar var oldStreamPos = stream.Position; - using(var entryStream = entry.OpenEntryStream()) - using(var memoryStream = new MemoryStream()) + using (var entryStream = entry.OpenEntryStream()) { - entryStream.TransferTo(memoryStream); - memoryStream.Position = 0; - var bytes = memoryStream.ToArray(); + using (var memoryStream = new MemoryStream()) + { + entryStream.TransferTo(memoryStream); + memoryStream.Position = 0; + var bytes = memoryStream.ToArray(); - header.Name = ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length).TrimNulls(); + header.Name = ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length).TrimNulls(); + } } stream.Position = oldStreamPos; @@ -198,7 +202,7 @@ namespace SharpCompress.Archive.Tar } protected override TarArchiveEntry CreateEntryInternal(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); diff --git a/src/SharpCompress/Archive/Tar/TarArchiveEntry.cs b/src/SharpCompress/Archive/Tar/TarArchiveEntry.cs index 16585964..be794b49 100644 --- a/src/SharpCompress/Archive/Tar/TarArchiveEntry.cs +++ b/src/SharpCompress/Archive/Tar/TarArchiveEntry.cs @@ -19,12 +19,10 @@ namespace SharpCompress.Archive.Tar } #region IArchiveEntry Members - public IArchive Archive { get; private set; } - public bool IsComplete - { - get { return true; } - } + public IArchive Archive { get; } + + public bool IsComplete { get { return true; } } #endregion } diff --git a/src/SharpCompress/Archive/Tar/TarWritableArchiveEntry.cs b/src/SharpCompress/Archive/Tar/TarWritableArchiveEntry.cs index 5830fb68..08fd0436 100644 --- a/src/SharpCompress/Archive/Tar/TarWritableArchiveEntry.cs +++ b/src/SharpCompress/Archive/Tar/TarWritableArchiveEntry.cs @@ -8,9 +8,6 @@ namespace SharpCompress.Archive.Tar { internal class TarWritableArchiveEntry : TarArchiveEntry, IWritableArchiveEntry { - private readonly string path; - private readonly long size; - private readonly DateTime? lastModified; private readonly bool closeStream; private readonly Stream stream; @@ -19,78 +16,36 @@ namespace SharpCompress.Archive.Tar : base(archive, null, compressionType) { this.stream = stream; - this.path = path; - this.size = size; - this.lastModified = lastModified; + Key = path; + Size = size; + LastModifiedTime = lastModified; this.closeStream = closeStream; } - public override long Crc - { - get { return 0; } - } + public override long Crc { get { return 0; } } - public override string Key - { - get { return path; } - } + public override string Key { get; } - public override long CompressedSize - { - get { return 0; } - } + public override long CompressedSize { get { return 0; } } - public override long Size - { - get { return size; } - } + public override long Size { get; } - public override DateTime? LastModifiedTime - { - get { return lastModified; } - } + public override DateTime? LastModifiedTime { get; } - public override DateTime? CreatedTime - { - get { return null; } - } + public override DateTime? CreatedTime { get { return null; } } - public override DateTime? LastAccessedTime - { - get { return null; } - } + public override DateTime? LastAccessedTime { get { return null; } } - public override DateTime? ArchivedTime - { - get { return null; } - } + public override DateTime? ArchivedTime { get { return null; } } - public override bool IsEncrypted - { - get { return false; } - } + public override bool IsEncrypted { get { return false; } } - public override bool IsDirectory - { - get { return false; } - } + public override bool IsDirectory { get { return false; } } - public override bool IsSplit - { - get { return false; } - } + public override bool IsSplit { get { return false; } } - internal override IEnumerable Parts - { - get { throw new NotImplementedException(); } - } - Stream IWritableArchiveEntry.Stream - { - get - { - return stream; - } - } + internal override IEnumerable Parts { get { throw new NotImplementedException(); } } + Stream IWritableArchiveEntry.Stream { get { return stream; } } public override Stream OpenEntryStream() { diff --git a/src/SharpCompress/Archive/Zip/ZipArchive.cs b/src/SharpCompress/Archive/Zip/ZipArchive.cs index a9ae08f5..24f2f07e 100644 --- a/src/SharpCompress/Archive/Zip/ZipArchive.cs +++ b/src/SharpCompress/Archive/Zip/ZipArchive.cs @@ -23,11 +23,12 @@ namespace SharpCompress.Archive.Zip public CompressionLevel DeflateCompressionLevel { get; set; } #if !NO_FILE - /// - /// Constructor expects a filepath to an existing file. - /// - /// - /// + +/// +/// Constructor expects a filepath to an existing file. +/// +/// +/// public static ZipArchive Open(string filePath, string password = null) { return Open(filePath, Options.None, password); @@ -121,7 +122,7 @@ namespace SharpCompress.Archive.Zip { return false; } - return Enum.IsDefined(typeof (ZipHeaderType), header.ZipHeaderType); + return Enum.IsDefined(typeof(ZipHeaderType), header.ZipHeaderType); } catch (CryptographicException) { @@ -134,12 +135,13 @@ namespace SharpCompress.Archive.Zip } #if !NO_FILE - /// - /// Constructor with a FileInfo object to an existing file. - /// - /// - /// - /// + +/// +/// Constructor with a FileInfo object to an existing file. +/// +/// +/// +/// internal ZipArchive(FileInfo fileInfo, Options options, string password = null) : base(ArchiveType.Zip, fileInfo, options) { @@ -189,19 +191,19 @@ namespace SharpCompress.Archive.Zip switch (h.ZipHeaderType) { case ZipHeaderType.DirectoryEntry: - { - yield return new ZipArchiveEntry(this, - new SeekableZipFilePart(headerFactory, - h as DirectoryEntryHeader, - stream)); - } + { + yield return new ZipArchiveEntry(this, + new SeekableZipFilePart(headerFactory, + h as DirectoryEntryHeader, + stream)); + } break; case ZipHeaderType.DirectoryEnd: - { - byte[] bytes = (h as DirectoryEndHeader).Comment; - volume.Comment = ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length); - yield break; - } + { + byte[] bytes = (h as DirectoryEndHeader).Comment; + volume.Comment = ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length); + yield break; + } } } } @@ -225,7 +227,7 @@ namespace SharpCompress.Archive.Zip } protected override ZipArchiveEntry CreateEntryInternal(string filePath, Stream source, long size, DateTime? modified, - bool closeStream) + bool closeStream) { return new ZipWritableArchiveEntry(this, source, filePath, size, modified, closeStream); } diff --git a/src/SharpCompress/Archive/Zip/ZipArchiveEntry.cs b/src/SharpCompress/Archive/Zip/ZipArchiveEntry.cs index 607f7a58..cff6e4e9 100644 --- a/src/SharpCompress/Archive/Zip/ZipArchiveEntry.cs +++ b/src/SharpCompress/Archive/Zip/ZipArchiveEntry.cs @@ -19,18 +19,12 @@ namespace SharpCompress.Archive.Zip #region IArchiveEntry Members - public IArchive Archive { get; private set; } + public IArchive Archive { get; } - public bool IsComplete - { - get { return true; } - } + public bool IsComplete { get { return true; } } #endregion - public string Comment - { - get { return (Parts.Single() as SeekableZipFilePart).Comment; } - } + public string Comment { get { return (Parts.Single() as SeekableZipFilePart).Comment; } } } } \ No newline at end of file diff --git a/src/SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs b/src/SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs index f1946e7a..0cc428d4 100644 --- a/src/SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs +++ b/src/SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs @@ -8,9 +8,6 @@ namespace SharpCompress.Archive.Zip { internal class ZipWritableArchiveEntry : ZipArchiveEntry, IWritableArchiveEntry { - private readonly string path; - private readonly long size; - private readonly DateTime? lastModified; private readonly bool closeStream; private readonly Stream stream; private bool isDisposed; @@ -20,79 +17,37 @@ namespace SharpCompress.Archive.Zip : base(archive, null) { this.stream = stream; - this.path = path; - this.size = size; - this.lastModified = lastModified; + Key = path; + Size = size; + LastModifiedTime = lastModified; this.closeStream = closeStream; } - public override long Crc - { - get { return 0; } - } + public override long Crc { get { return 0; } } - public override string Key - { - get { return path; } - } + public override string Key { get; } - public override long CompressedSize - { - get { return 0; } - } + public override long CompressedSize { get { return 0; } } - public override long Size - { - get { return size; } - } + public override long Size { get; } - public override DateTime? LastModifiedTime - { - get { return lastModified; } - } + public override DateTime? LastModifiedTime { get; } - public override DateTime? CreatedTime - { - get { return null; } - } + public override DateTime? CreatedTime { get { return null; } } - public override DateTime? LastAccessedTime - { - get { return null; } - } + public override DateTime? LastAccessedTime { get { return null; } } - public override DateTime? ArchivedTime - { - get { return null; } - } + public override DateTime? ArchivedTime { get { return null; } } - public override bool IsEncrypted - { - get { return false; } - } + public override bool IsEncrypted { get { return false; } } - public override bool IsDirectory - { - get { return false; } - } + public override bool IsDirectory { get { return false; } } - public override bool IsSplit - { - get { return false; } - } + public override bool IsSplit { get { return false; } } - internal override IEnumerable Parts - { - get { throw new NotImplementedException(); } - } + internal override IEnumerable Parts { get { throw new NotImplementedException(); } } - Stream IWritableArchiveEntry.Stream - { - get - { - return stream; - } - } + Stream IWritableArchiveEntry.Stream { get { return stream; } } public override Stream OpenEntryStream() { diff --git a/src/SharpCompress/AssemblyInfo.cs b/src/SharpCompress/AssemblyInfo.cs index 8978eeba..4c64dfac 100644 --- a/src/SharpCompress/AssemblyInfo.cs +++ b/src/SharpCompress/AssemblyInfo.cs @@ -2,12 +2,8 @@ using System.Reflection; using System.Runtime.CompilerServices; - [assembly: AssemblyTitle("SharpCompress")] [assembly: AssemblyProduct("SharpCompress")] - - [assembly: InternalsVisibleTo("SharpCompress.Test")] [assembly: InternalsVisibleTo("SharpCompress.Test.Portable")] - -[assembly: CLSCompliant(true)] +[assembly: CLSCompliant(true)] \ No newline at end of file diff --git a/src/SharpCompress/Common/ArchiveType.cs b/src/SharpCompress/Common/ArchiveType.cs index ca905f42..a0d3097a 100644 --- a/src/SharpCompress/Common/ArchiveType.cs +++ b/src/SharpCompress/Common/ArchiveType.cs @@ -6,6 +6,6 @@ Zip, Tar, SevenZip, - GZip, + GZip } } \ No newline at end of file diff --git a/src/SharpCompress/Common/CompressionInfo.cs b/src/SharpCompress/Common/CompressionInfo.cs index 2ad5703b..032f88bc 100644 --- a/src/SharpCompress/Common/CompressionInfo.cs +++ b/src/SharpCompress/Common/CompressionInfo.cs @@ -24,7 +24,7 @@ namespace SharpCompress.Common public static implicit operator CompressionInfo(CompressionType compressionType) { - return new CompressionInfo() {Type = compressionType}; + return new CompressionInfo {Type = compressionType}; } } } \ No newline at end of file diff --git a/src/SharpCompress/Common/CompressionType.cs b/src/SharpCompress/Common/CompressionType.cs index 20d59a2b..b43d4b49 100644 --- a/src/SharpCompress/Common/CompressionType.cs +++ b/src/SharpCompress/Common/CompressionType.cs @@ -11,6 +11,6 @@ LZMA, BCJ, BCJ2, - Unknown, + Unknown } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Entry.cs b/src/SharpCompress/Common/Entry.cs index 3f1aac1b..d546aad5 100644 --- a/src/SharpCompress/Common/Entry.cs +++ b/src/SharpCompress/Common/Entry.cs @@ -70,16 +70,11 @@ namespace SharpCompress.Common internal virtual void Close() { - } /// /// Entry file attribute. /// - public virtual int? Attrib - { - get { throw new NotImplementedException(); } - } - + public virtual int? Attrib { get { throw new NotImplementedException(); } } } } \ No newline at end of file diff --git a/src/SharpCompress/Common/EntryStream.cs b/src/SharpCompress/Common/EntryStream.cs index f3fd99ac..c25e04fe 100644 --- a/src/SharpCompress/Common/EntryStream.cs +++ b/src/SharpCompress/Common/EntryStream.cs @@ -6,14 +6,14 @@ namespace SharpCompress.Common { public class EntryStream : Stream { - public IReader Reader { get; private set; } - private Stream stream; + public IReader Reader { get; } + private readonly Stream stream; private bool completed; private bool isDisposed; internal EntryStream(IReader reader, Stream stream) { - this.Reader = reader; + Reader = reader; this.stream = stream; } @@ -44,36 +44,20 @@ namespace SharpCompress.Common stream.Dispose(); } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { throw new NotSupportedException(); } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { diff --git a/src/SharpCompress/Common/ExtractOptions.cs b/src/SharpCompress/Common/ExtractOptions.cs index 85c92668..5fa347a2 100644 --- a/src/SharpCompress/Common/ExtractOptions.cs +++ b/src/SharpCompress/Common/ExtractOptions.cs @@ -25,6 +25,6 @@ namespace SharpCompress.Common /// /// preserve windows file attributes /// - PreserveAttributes = 1 << 3, + PreserveAttributes = 1 << 3 } } \ No newline at end of file diff --git a/src/SharpCompress/Common/FlagUtility.cs b/src/SharpCompress/Common/FlagUtility.cs index b6fc8664..8a3aaee1 100644 --- a/src/SharpCompress/Common/FlagUtility.cs +++ b/src/SharpCompress/Common/FlagUtility.cs @@ -48,7 +48,7 @@ namespace SharpCompress.Common { return ((bitField & flag) == flag); } - + /// /// Returns true if the flag is set on the specified bit field. /// Currently only works with 32-bit bitfields. @@ -75,7 +75,6 @@ namespace SharpCompress.Common return ((bitField & flag) == flag); } - /// /// Sets a bit-field to either on or off for the specified flag. /// @@ -83,9 +82,9 @@ namespace SharpCompress.Common /// Flag to change /// bool /// The flagged variable with the flag changed - public static long SetFlag(long bitField, long flag, bool @on) + public static long SetFlag(long bitField, long flag, bool on) { - if (@on) + if (on) { return bitField | flag; } @@ -100,10 +99,10 @@ namespace SharpCompress.Common /// Flag to change /// bool /// The flagged variable with the flag changed - public static long SetFlag(T bitField, T flag, bool @on) + public static long SetFlag(T bitField, T flag, bool on) where T : struct { - return SetFlag(Convert.ToInt64(bitField), Convert.ToInt64(flag), @on); + return SetFlag(Convert.ToInt64(bitField), Convert.ToInt64(flag), on); } } } \ No newline at end of file diff --git a/src/SharpCompress/Common/GZip/GZipEntry.cs b/src/SharpCompress/Common/GZip/GZipEntry.cs index 3d3a23e6..c347e32a 100644 --- a/src/SharpCompress/Common/GZip/GZipEntry.cs +++ b/src/SharpCompress/Common/GZip/GZipEntry.cs @@ -13,70 +13,31 @@ namespace SharpCompress.Common.GZip this.filePart = filePart; } - public override CompressionType CompressionType - { - get { return CompressionType.GZip; } - } + public override CompressionType CompressionType { get { return CompressionType.GZip; } } - public override long Crc - { - get { return 0; } - } + public override long Crc { get { return 0; } } - public override string Key - { - get { return filePart.FilePartName; } - } + public override string Key { get { return filePart.FilePartName; } } - public override long CompressedSize - { - get { return 0; } - } + public override long CompressedSize { get { return 0; } } - public override long Size - { - get { return 0; } - } + public override long Size { get { return 0; } } - public override DateTime? LastModifiedTime - { - get { return filePart.DateModified; } - } + public override DateTime? LastModifiedTime { get { return filePart.DateModified; } } - public override DateTime? CreatedTime - { - get { return null; } - } + public override DateTime? CreatedTime { get { return null; } } - public override DateTime? LastAccessedTime - { - get { return null; } - } + public override DateTime? LastAccessedTime { get { return null; } } - public override DateTime? ArchivedTime - { - get { return null; } - } + public override DateTime? ArchivedTime { get { return null; } } - public override bool IsEncrypted - { - get { return false; } - } + public override bool IsEncrypted { get { return false; } } - public override bool IsDirectory - { - get { return false; } - } + public override bool IsDirectory { get { return false; } } - public override bool IsSplit - { - get { return false; } - } + public override bool IsSplit { get { return false; } } - internal override IEnumerable Parts - { - get { return filePart.AsEnumerable(); } - } + internal override IEnumerable Parts { get { return filePart.AsEnumerable(); } } internal static IEnumerable GetEntries(Stream stream) { diff --git a/src/SharpCompress/Common/GZip/GZipFilePart.cs b/src/SharpCompress/Common/GZip/GZipFilePart.cs index 2ef0679c..6a9f9125 100644 --- a/src/SharpCompress/Common/GZip/GZipFilePart.cs +++ b/src/SharpCompress/Common/GZip/GZipFilePart.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using SharpCompress.Common.Tar.Headers; using SharpCompress.Compressor; @@ -20,10 +21,7 @@ namespace SharpCompress.Common.GZip internal DateTime? DateModified { get; private set; } - internal override string FilePartName - { - get { return name; } - } + internal override string FilePartName { get { return name; } } internal override Stream GetCompressedStream() { @@ -43,13 +41,19 @@ namespace SharpCompress.Common.GZip // workitem 8501: handle edge case (decompress empty stream) if (n == 0) + { return; + } if (n != 10) + { throw new ZlibException("Not a valid GZIP stream."); + } if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) + { throw new ZlibException("Bad GZIP header."); + } Int32 timet = DataConverter.LittleEndian.GetInt32(header, 4); DateModified = TarHeader.Epoch.AddSeconds(timet); @@ -58,7 +62,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) @@ -67,18 +71,23 @@ namespace SharpCompress.Common.GZip } } if ((header[3] & 0x08) == 0x08) + { name = ReadZeroTerminatedString(stream); + } if ((header[3] & 0x10) == 0x010) + { ReadZeroTerminatedString(stream); + } if ((header[3] & 0x02) == 0x02) + { stream.ReadByte(); // CRC16, ignore + } } - private static string ReadZeroTerminatedString(Stream stream) { byte[] buf1 = new byte[1]; - var list = new System.Collections.Generic.List(); + var list = new List(); bool done = false; do { @@ -96,7 +105,8 @@ namespace SharpCompress.Common.GZip { list.Add(buf1[0]); } - } while (!done); + } + while (!done); byte[] a = list.ToArray(); return ArchiveEncoding.Default.GetString(a, 0, a.Length); } diff --git a/src/SharpCompress/Common/GZip/GZipVolume.cs b/src/SharpCompress/Common/GZip/GZipVolume.cs index 639edaf5..1965838f 100644 --- a/src/SharpCompress/Common/GZip/GZipVolume.cs +++ b/src/SharpCompress/Common/GZip/GZipVolume.cs @@ -16,14 +16,8 @@ namespace SharpCompress.Common.GZip } #endif - public override bool IsFirstVolume - { - get { return true; } - } + public override bool IsFirstVolume { get { return true; } } - public override bool IsMultiVolume - { - get { return true; } - } + public override bool IsMultiVolume { get { return true; } } } } \ No newline at end of file diff --git a/src/SharpCompress/Common/IEntry.Extensions.cs b/src/SharpCompress/Common/IEntry.Extensions.cs index f39b4dde..12a97213 100644 --- a/src/SharpCompress/Common/IEntry.Extensions.cs +++ b/src/SharpCompress/Common/IEntry.Extensions.cs @@ -1,4 +1,5 @@ -#if !NO_FILE + +#if !NO_FILE using System.IO; namespace SharpCompress.Common @@ -46,4 +47,4 @@ namespace SharpCompress.Common } } } -#endif +#endif \ No newline at end of file diff --git a/src/SharpCompress/Common/IVolume.cs b/src/SharpCompress/Common/IVolume.cs index a8d02252..d5dac255 100644 --- a/src/SharpCompress/Common/IVolume.cs +++ b/src/SharpCompress/Common/IVolume.cs @@ -1,4 +1,5 @@ using System; + #if !NO_FILE using System.IO; #endif diff --git a/src/SharpCompress/Common/Options.cs b/src/SharpCompress/Common/Options.cs index 32ec2d0c..25286013 100644 --- a/src/SharpCompress/Common/Options.cs +++ b/src/SharpCompress/Common/Options.cs @@ -18,6 +18,6 @@ namespace SharpCompress.Common /// /// Look for RarArchive (Check for self-extracting archives or cases where RarArchive isn't at the start of the file) /// - LookForHeader = 2, + LookForHeader = 2 } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs b/src/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs index 2de02de0..2f982946 100644 --- a/src/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/ArchiveHeader.cs @@ -17,10 +17,7 @@ namespace SharpCompress.Common.Rar.Headers } } - internal ArchiveFlags ArchiveHeaderFlags - { - get { return (ArchiveFlags) base.Flags; } - } + internal ArchiveFlags ArchiveHeaderFlags { get { return (ArchiveFlags)Flags; } } internal short HighPosAv { get; private set; } @@ -28,9 +25,6 @@ namespace SharpCompress.Common.Rar.Headers internal byte EncryptionVersion { get; private set; } - public bool HasPassword - { - get { return ArchiveHeaderFlags.HasFlag(ArchiveFlags.PASSWORD); } - } + public bool HasPassword { get { return ArchiveHeaderFlags.HasFlag(ArchiveFlags.PASSWORD); } } } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs b/src/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs index 95bc6f07..30e5acea 100644 --- a/src/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/EndArchiveHeader.cs @@ -16,10 +16,7 @@ namespace SharpCompress.Common.Rar.Headers } } - internal EndArchiveFlags EndArchiveFlags - { - get { return (EndArchiveFlags) base.Flags; } - } + internal EndArchiveFlags EndArchiveFlags { get { return (EndArchiveFlags)Flags; } } internal int? ArchiveCRC { get; private set; } diff --git a/src/SharpCompress/Common/Rar/Headers/FileHeader.cs b/src/SharpCompress/Common/Rar/Headers/FileHeader.cs index 99e135f0..8cdd7135 100644 --- a/src/SharpCompress/Common/Rar/Headers/FileHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/FileHeader.cs @@ -52,50 +52,50 @@ namespace SharpCompress.Common.Rar.Headers switch (HeaderType) { case HeaderType.FileHeader: + { + if (FileFlags.HasFlag(FileFlags.UNICODE)) { - if (FileFlags.HasFlag(FileFlags.UNICODE)) + int length = 0; + while (length < fileNameBytes.Length + && fileNameBytes[length] != 0) { - int length = 0; - while (length < fileNameBytes.Length - && fileNameBytes[length] != 0) - { - length++; - } - if (length != nameSize) - { - length++; - FileName = FileNameDecoder.Decode(fileNameBytes, length); - } - else - { - FileName = DecodeDefault(fileNameBytes); - } + length++; + } + if (length != nameSize) + { + length++; + FileName = FileNameDecoder.Decode(fileNameBytes, length); } else { FileName = DecodeDefault(fileNameBytes); } - FileName = ConvertPath(FileName, HostOS); } + else + { + FileName = DecodeDefault(fileNameBytes); + } + FileName = ConvertPath(FileName, HostOS); + } break; case HeaderType.NewSubHeader: + { + int datasize = HeaderSize - NEWLHD_SIZE - nameSize; + if (FileFlags.HasFlag(FileFlags.SALT)) { - int datasize = HeaderSize - NEWLHD_SIZE - nameSize; - if (FileFlags.HasFlag(FileFlags.SALT)) - { - datasize -= SALT_SIZE; - } - if (datasize > 0) - { - SubData = reader.ReadBytes(datasize); - } - - if (NewSubHeaderType.SUBHEAD_TYPE_RR.Equals(fileNameBytes)) - { - RecoverySectors = SubData[8] + (SubData[9] << 8) - + (SubData[10] << 16) + (SubData[11] << 24); - } + datasize -= SALT_SIZE; } + if (datasize > 0) + { + SubData = reader.ReadBytes(datasize); + } + + if (NewSubHeaderType.SUBHEAD_TYPE_RR.Equals(fileNameBytes)) + { + RecoverySectors = SubData[8] + (SubData[9] << 8) + + (SubData[10] << 16) + (SubData[11] << 24); + } + } break; } @@ -155,6 +155,7 @@ namespace SharpCompress.Common.Rar.Headers byte b = reader.ReadByte(); nanosecondHundreds |= (((uint)b) << ((j + 3 - count) * 8)); } + //10^-7 to 10^-3 return time.Value.AddMilliseconds(nanosecondHundreds * Math.Pow(10, -4)); } @@ -207,10 +208,7 @@ namespace SharpCompress.Common.Rar.Headers internal int FileAttributes { get; private set; } - internal FileFlags FileFlags - { - get { return (FileFlags)base.Flags; } - } + internal FileFlags FileFlags { get { return (FileFlags)Flags; } } internal long CompressedSize { get; private set; } internal long UncompressedSize { get; private set; } diff --git a/src/SharpCompress/Common/Rar/Headers/FileNameDecoder.cs b/src/SharpCompress/Common/Rar/Headers/FileNameDecoder.cs index a9cb6ebc..98da75da 100644 --- a/src/SharpCompress/Common/Rar/Headers/FileNameDecoder.cs +++ b/src/SharpCompress/Common/Rar/Headers/FileNameDecoder.cs @@ -32,19 +32,19 @@ 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; @@ -57,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/src/SharpCompress/Common/Rar/Headers/Flags.cs b/src/SharpCompress/Common/Rar/Headers/Flags.cs index 421e983a..a2dbd550 100644 --- a/src/SharpCompress/Common/Rar/Headers/Flags.cs +++ b/src/SharpCompress/Common/Rar/Headers/Flags.cs @@ -13,12 +13,12 @@ namespace SharpCompress.Common.Rar.Headers ProtectHeader = 0x78, SignHeader = 0x79, NewSubHeader = 0x7a, - EndArchiveHeader = 0x7b, + EndArchiveHeader = 0x7b } internal enum HeaderFlags : short { - LONG_BLOCK = -0x8000, + LONG_BLOCK = -0x8000 } [Flags] @@ -33,7 +33,7 @@ namespace SharpCompress.Common.Rar.Headers PROTECT = 0x0040, PASSWORD = 0x0080, FIRSTVOLUME = 0x0100, - ENCRYPTVER = 0x0200, + ENCRYPTVER = 0x0200 } internal enum HostOS @@ -70,16 +70,15 @@ namespace SharpCompress.Common.Rar.Headers SALT = 0x0400, VERSION = 0x0800, EXTTIME = 0x1000, - EXTFLAGS = 0x2000, + EXTFLAGS = 0x2000 } - [Flags] internal enum EndArchiveFlags { EARC_NEXT_VOLUME = 0x0001, EARC_DATACRC = 0x0002, EARC_REVSPACE = 0x0004, - EARC_VOLNUMBER = 0x0008, + EARC_VOLNUMBER = 0x0008 } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Rar/Headers/NewSubHeader.cs b/src/SharpCompress/Common/Rar/Headers/NewSubHeader.cs index e259e837..6218f123 100644 --- a/src/SharpCompress/Common/Rar/Headers/NewSubHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/NewSubHeader.cs @@ -20,14 +20,14 @@ namespace SharpCompress.Common.Rar.Headers //internal static final NewSubHeaderType SUBHEAD_TYPE_BEOSEA = new NewSubHeaderType(new byte[]{'E','A','B','E'}); - private byte[] bytes; + private readonly byte[] bytes; private NewSubHeaderType(params char[] chars) { bytes = new byte[chars.Length]; for (int i = 0; i < chars.Length; ++i) { - bytes[i] = (byte) chars[i]; + bytes[i] = (byte)chars[i]; } } diff --git a/src/SharpCompress/Common/Rar/Headers/ProtectHeader.cs b/src/SharpCompress/Common/Rar/Headers/ProtectHeader.cs index a80802c8..b72391d4 100644 --- a/src/SharpCompress/Common/Rar/Headers/ProtectHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/ProtectHeader.cs @@ -19,4 +19,4 @@ namespace SharpCompress.Common.Rar.Headers internal uint TotalBlocks { get; private set; } internal byte[] Mark { get; private set; } } -} +} \ No newline at end of file diff --git a/src/SharpCompress/Common/Rar/Headers/RarHeader.cs b/src/SharpCompress/Common/Rar/Headers/RarHeader.cs index 8e3b60f5..ecfaad65 100644 --- a/src/SharpCompress/Common/Rar/Headers/RarHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/RarHeader.cs @@ -35,6 +35,7 @@ namespace SharpCompress.Common.Rar.Headers return null; } } + protected virtual void ReadFromReader(MarkingBinaryReader reader) { HeadCRC = reader.ReadInt16(); diff --git a/src/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs b/src/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs index bd83874f..0a9e5fbc 100644 --- a/src/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs +++ b/src/SharpCompress/Common/Rar/Headers/RarHeaderFactory.cs @@ -16,11 +16,11 @@ namespace SharpCompress.Common.Rar.Headers Password = password; } - private Options Options { get; set; } + private Options Options { get; } public string Password { get; private set; } - internal StreamingMode StreamingMode { get; private set; } + internal StreamingMode StreamingMode { get; } internal bool IsEncrypted { get; private set; } - + internal IEnumerable ReadHeaders(Stream stream) { if (Options.HasFlag(Options.LookForHeader)) @@ -114,7 +114,6 @@ namespace SharpCompress.Common.Rar.Headers return rewindableStream; } - private RarHeader ReadNextHeader(Stream stream) { #if !NO_CRYPTO @@ -143,109 +142,109 @@ namespace SharpCompress.Common.Rar.Headers switch (header.HeaderType) { case HeaderType.ArchiveHeader: - { - var ah = header.PromoteHeader(reader); - IsEncrypted = ah.HasPassword; - return ah; - } + { + var ah = header.PromoteHeader(reader); + IsEncrypted = ah.HasPassword; + return ah; + } case HeaderType.MarkHeader: - { - return header.PromoteHeader(reader); - } + { + return header.PromoteHeader(reader); + } case HeaderType.ProtectHeader: - { - ProtectHeader ph = header.PromoteHeader(reader); - - // skip the recovery record data, we do not use it. - switch (StreamingMode) - { - case StreamingMode.Seekable: - { - reader.BaseStream.Position += ph.DataSize; - } - break; - case StreamingMode.Streaming: - { - reader.BaseStream.Skip(ph.DataSize); - } - break; - default: - { - throw new InvalidFormatException("Invalid StreamingMode"); - } - } + { + ProtectHeader ph = header.PromoteHeader(reader); - return ph; + // skip the recovery record data, we do not use it. + switch (StreamingMode) + { + case StreamingMode.Seekable: + { + reader.BaseStream.Position += ph.DataSize; + } + break; + case StreamingMode.Streaming: + { + reader.BaseStream.Skip(ph.DataSize); + } + break; + default: + { + throw new InvalidFormatException("Invalid StreamingMode"); + } } + return ph; + } + case HeaderType.NewSubHeader: + { + FileHeader fh = header.PromoteHeader(reader); + switch (StreamingMode) { - FileHeader fh = header.PromoteHeader(reader); - switch (StreamingMode) + case StreamingMode.Seekable: { - case StreamingMode.Seekable: - { - fh.DataStartPosition = reader.BaseStream.Position; - reader.BaseStream.Position += fh.CompressedSize; - } - break; - case StreamingMode.Streaming: - { - //skip the data because it's useless? - reader.BaseStream.Skip(fh.CompressedSize); - } - break; - default: - { - throw new InvalidFormatException("Invalid StreamingMode"); - } + fh.DataStartPosition = reader.BaseStream.Position; + reader.BaseStream.Position += fh.CompressedSize; } - return fh; - } - case HeaderType.FileHeader: - { - FileHeader fh = header.PromoteHeader(reader); - switch (StreamingMode) + break; + case StreamingMode.Streaming: { - case StreamingMode.Seekable: - { - fh.DataStartPosition = reader.BaseStream.Position; - reader.BaseStream.Position += fh.CompressedSize; - } - break; - case StreamingMode.Streaming: - { - var ms = new ReadOnlySubStream(reader.BaseStream, fh.CompressedSize); - if (fh.Salt == null) - { - fh.PackedStream = ms; - } - else - { + //skip the data because it's useless? + reader.BaseStream.Skip(fh.CompressedSize); + } + break; + default: + { + throw new InvalidFormatException("Invalid StreamingMode"); + } + } + return fh; + } + case HeaderType.FileHeader: + { + FileHeader fh = header.PromoteHeader(reader); + switch (StreamingMode) + { + case StreamingMode.Seekable: + { + fh.DataStartPosition = reader.BaseStream.Position; + reader.BaseStream.Position += fh.CompressedSize; + } + break; + case StreamingMode.Streaming: + { + var ms = new ReadOnlySubStream(reader.BaseStream, fh.CompressedSize); + if (fh.Salt == null) + { + fh.PackedStream = ms; + } + else + { #if !NO_CRYPTO fh.PackedStream = new RarCryptoWrapper(ms, Password, fh.Salt); #else - throw new NotSupportedException("RarCrypto not supported"); + throw new NotSupportedException("RarCrypto not supported"); #endif - } - } - break; - default: - { - throw new InvalidFormatException("Invalid StreamingMode"); - } + } + } + break; + default: + { + throw new InvalidFormatException("Invalid StreamingMode"); } - return fh; } + return fh; + } case HeaderType.EndArchiveHeader: - { - return header.PromoteHeader(reader); - } + { + return header.PromoteHeader(reader); + } default: - { - throw new InvalidFormatException("Invalid Rar Header: " + header.HeaderType.ToString()); - } + { + throw new InvalidFormatException("Invalid Rar Header: " + header.HeaderType); + } } } } diff --git a/src/SharpCompress/Common/Rar/RarCryptoBinaryReader.cs b/src/SharpCompress/Common/Rar/RarCryptoBinaryReader.cs index 0dabc175..40f64d19 100644 --- a/src/SharpCompress/Common/Rar/RarCryptoBinaryReader.cs +++ b/src/SharpCompress/Common/Rar/RarCryptoBinaryReader.cs @@ -1,4 +1,5 @@ -#if !NO_CRYPTO + +#if !NO_CRYPTO using System.Collections.Generic; using System.IO; using SharpCompress.IO; diff --git a/src/SharpCompress/Common/Rar/RarCryptoWrapper.cs b/src/SharpCompress/Common/Rar/RarCryptoWrapper.cs index aaa93a8e..2a14ae1a 100644 --- a/src/SharpCompress/Common/Rar/RarCryptoWrapper.cs +++ b/src/SharpCompress/Common/Rar/RarCryptoWrapper.cs @@ -1,3 +1,4 @@ + #if !NO_CRYPTO using System; using System.Collections.Generic; diff --git a/src/SharpCompress/Common/Rar/RarEntry.cs b/src/SharpCompress/Common/Rar/RarEntry.cs index dc898517..c69a514e 100644 --- a/src/SharpCompress/Common/Rar/RarEntry.cs +++ b/src/SharpCompress/Common/Rar/RarEntry.cs @@ -10,71 +10,44 @@ namespace SharpCompress.Common.Rar /// /// The File's 32 bit CRC Hash /// - public override long Crc - { - get { return FileHeader.FileCRC; } - } + public override long Crc { get { return FileHeader.FileCRC; } } /// /// The path of the file internal to the Rar Archive. /// - public override string Key - { - get { return FileHeader.FileName; } - } + public override string Key { get { return FileHeader.FileName; } } /// /// The entry last modified time in the archive, if recorded /// - public override DateTime? LastModifiedTime - { - get { return FileHeader.FileLastModifiedTime; } - } + public override DateTime? LastModifiedTime { get { return FileHeader.FileLastModifiedTime; } } /// /// The entry create time in the archive, if recorded /// - public override DateTime? CreatedTime - { - get { return FileHeader.FileCreatedTime; } - } + public override DateTime? CreatedTime { get { return FileHeader.FileCreatedTime; } } /// /// The entry last accessed time in the archive, if recorded /// - public override DateTime? LastAccessedTime - { - get { return FileHeader.FileLastAccessedTime; } - } + public override DateTime? LastAccessedTime { get { return FileHeader.FileLastAccessedTime; } } /// /// The entry time whend archived, if recorded /// - public override DateTime? ArchivedTime - { - get { return FileHeader.FileArchivedTime; } - } + public override DateTime? ArchivedTime { get { return FileHeader.FileArchivedTime; } } /// /// Entry is password protected and encrypted and cannot be extracted. /// - public override bool IsEncrypted - { - get { return FileHeader.FileFlags.HasFlag(FileFlags.PASSWORD); } - } + public override bool IsEncrypted { get { return FileHeader.FileFlags.HasFlag(FileFlags.PASSWORD); } } /// /// Entry is password protected and encrypted and cannot be extracted. /// - public override bool IsDirectory - { - get { return FileHeader.FileFlags.HasFlag(FileFlags.DIRECTORY); } - } + public override bool IsDirectory { get { return FileHeader.FileFlags.HasFlag(FileFlags.DIRECTORY); } } - public override bool IsSplit - { - get { return FileHeader.FileFlags.HasFlag(FileFlags.SPLIT_AFTER); } - } + public override bool IsSplit { get { return FileHeader.FileFlags.HasFlag(FileFlags.SPLIT_AFTER); } } public override string ToString() { diff --git a/src/SharpCompress/Common/Rar/RarRijndael.cs b/src/SharpCompress/Common/Rar/RarRijndael.cs index d30be5ab..d885cb08 100644 --- a/src/SharpCompress/Common/Rar/RarRijndael.cs +++ b/src/SharpCompress/Common/Rar/RarRijndael.cs @@ -1,4 +1,5 @@ -#if !NO_CRYPTO + +#if !NO_CRYPTO using System; using System.Collections.Generic; using System.Linq; diff --git a/src/SharpCompress/Common/Rar/RarVolume.cs b/src/SharpCompress/Common/Rar/RarVolume.cs index b1db9469..e2a4abd1 100644 --- a/src/SharpCompress/Common/Rar/RarVolume.cs +++ b/src/SharpCompress/Common/Rar/RarVolume.cs @@ -13,7 +13,7 @@ namespace SharpCompress.Common.Rar public abstract class RarVolume : Volume { private readonly RarHeaderFactory headerFactory; - + internal RarVolume(StreamingMode mode, Stream stream, string password, Options options) : base(stream, options) { @@ -23,10 +23,7 @@ namespace SharpCompress.Common.Rar internal string Password { get; private set; } - internal StreamingMode Mode - { - get { return headerFactory.StreamingMode; } - } + internal StreamingMode Mode { get { return headerFactory.StreamingMode; } } internal abstract IEnumerable ReadFileParts(); @@ -35,26 +32,26 @@ namespace SharpCompress.Common.Rar internal IEnumerable GetVolumeFileParts() { MarkHeader previousMarkHeader = null; - foreach (RarHeader header in headerFactory.ReadHeaders(this.Stream)) + foreach (RarHeader header in headerFactory.ReadHeaders(Stream)) { switch (header.HeaderType) { case HeaderType.ArchiveHeader: - { - ArchiveHeader = header as ArchiveHeader; - } + { + ArchiveHeader = header as ArchiveHeader; + } break; case HeaderType.MarkHeader: - { - previousMarkHeader = header as MarkHeader; - } + { + previousMarkHeader = header as MarkHeader; + } break; case HeaderType.FileHeader: - { - FileHeader fh = header as FileHeader; - RarFilePart fp = CreateFilePart(fh, previousMarkHeader); - yield return fp; - } + { + FileHeader fh = header as FileHeader; + RarFilePart fp = CreateFilePart(fh, previousMarkHeader); + yield return fp; + } break; } } @@ -70,6 +67,7 @@ namespace SharpCompress.Common.Rar { throw new InvalidOperationException("ArchiveHeader should never been null in a streaming read."); } + //we only want to load the archive header to avoid overhead but have to do the nasty thing and reset the stream GetVolumeFileParts().First(); Stream.Position = 0; diff --git a/src/SharpCompress/Common/ReaderExtractionEventArgs.cs b/src/SharpCompress/Common/ReaderExtractionEventArgs.cs index d4db5e41..b33b8635 100644 --- a/src/SharpCompress/Common/ReaderExtractionEventArgs.cs +++ b/src/SharpCompress/Common/ReaderExtractionEventArgs.cs @@ -8,6 +8,7 @@ namespace SharpCompress.Common { Item = entry; } + public T Item { get; private set; } } -} +} \ No newline at end of file diff --git a/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs b/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs index 88d090fa..434de875 100644 --- a/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs +++ b/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs @@ -80,15 +80,19 @@ namespace SharpCompress.Common.SevenZip { // v3.13 incorrectly worked with empty folders // v4.07: Loop for skipping empty folders - for (; ; ) + for (;;) { if (folderIndex >= Folders.Count) + { throw new InvalidOperationException(); + } FolderStartFileIndex.Add(i); // check it if (NumUnpackStreamsVector[folderIndex] != 0) + { break; + } folderIndex++; } @@ -97,7 +101,9 @@ namespace SharpCompress.Common.SevenZip FileIndexToFolderIndexMap.Add(folderIndex); if (emptyStream) + { continue; + } indexInFolder++; @@ -128,7 +134,9 @@ namespace SharpCompress.Common.SevenZip long size = 0; for (int i = 0; i < folder.PackStreams.Count; i++) + { size += PackSizes[packStreamIndex + i]; + } return size; } @@ -139,7 +147,9 @@ namespace SharpCompress.Common.SevenZip long folderStartPackPos = GetFolderStreamPos(folder, 0); List packSizes = new List(); for (int j = 0; j < folder.PackStreams.Count; j++) + { packSizes.Add(PackSizes[packStreamIndex + j]); + } return DecoderStreamHelper.CreateDecoderStream(stream, folderStartPackPos, packSizes.ToArray(), folder, pw); } @@ -153,8 +163,12 @@ namespace SharpCompress.Common.SevenZip { int folderIndex = FileIndexToFolderIndexMap[fileIndex]; if (folderIndex != -1) + { if (FolderStartFileIndex[folderIndex] == fileIndex) + { return GetFolderFullPackSize(folderIndex); + } + } return 0; } } diff --git a/src/SharpCompress/Common/SevenZip/ArchiveReader.cs b/src/SharpCompress/Common/SevenZip/ArchiveReader.cs index 56fd64ee..7364a708 100644 --- a/src/SharpCompress/Common/SevenZip/ArchiveReader.cs +++ b/src/SharpCompress/Common/SevenZip/ArchiveReader.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; using SharpCompress.Compressor.LZMA; @@ -17,7 +18,7 @@ namespace SharpCompress.Common.SevenZip internal long _streamEnding; internal byte[] _header; - private Dictionary _cachedStreams = new Dictionary(); + private readonly Dictionary _cachedStreams = new Dictionary(); internal void AddByteStream(byte[] buffer, int offset, int length) { @@ -66,7 +67,9 @@ namespace SharpCompress.Common.SevenZip { ulong id = _currentReader.ReadNumber(); if (id > 25) + { return null; + } #if DEBUG Log.WriteLine("ReadId: {0}", (BlockType)id); #endif @@ -85,13 +88,17 @@ namespace SharpCompress.Common.SevenZip private void WaitAttribute(BlockType attribute) { - for (; ; ) + for (;;) { BlockType? type = ReadId(); if (type == attribute) + { return; + } if (type == BlockType.End) + { throw new InvalidOperationException(); + } SkipData(); } } @@ -99,7 +106,9 @@ namespace SharpCompress.Common.SevenZip private void ReadArchiveProperties() { while (ReadId() != BlockType.End) + { SkipData(); + } } #endregion @@ -122,7 +131,9 @@ namespace SharpCompress.Common.SevenZip } if ((data & mask) != 0) + { bits.SetBit(i); + } mask >>= 1; } @@ -134,7 +145,9 @@ namespace SharpCompress.Common.SevenZip { byte allTrue = ReadByte(); if (allTrue != 0) + { return new BitVector(length, true); + } return ReadBitVector(length); } @@ -150,9 +163,13 @@ namespace SharpCompress.Common.SevenZip for (int i = 0; i < numFiles; i++) { if (defined[i]) + { action(i, checked((long)ReadUInt64())); + } else + { action(i, null); + } } } } @@ -166,9 +183,10 @@ namespace SharpCompress.Common.SevenZip private DateTime? TranslateTime(long? time) { if (time.HasValue) + { return TranslateTime(time.Value); - else - return null; + } + return null; } private void ReadDateTimeVector(List dataVector, int numFiles, Action action) @@ -185,9 +203,13 @@ namespace SharpCompress.Common.SevenZip for (int i = 0; i < numFiles; i++) { if (boolVector[i]) + { action(i, ReadUInt32()); + } else + { action(i, null); + } } } } @@ -230,10 +252,14 @@ namespace SharpCompress.Common.SevenZip Log.WriteLine("MethodId: " + String.Join("", Enumerable.Range(0, idSize).Select(x => longID[x].ToString("x2")).ToArray())); #endif if (idSize > 8) + { throw new NotSupportedException(); + } ulong id = 0; for (int j = 0; j < idSize; j++) + { id |= (ulong)longID[idSize - 1 - j] << (8 * j); + } coder.MethodId = new CMethodId(id); if ((mainByte & 0x10) != 0) @@ -264,7 +290,9 @@ namespace SharpCompress.Common.SevenZip } if ((mainByte & 0x80) != 0) + { throw new NotSupportedException(); + } numInStreams += coder.NumInStreams; numOutStreams += coder.NumOutStreams; @@ -298,9 +326,12 @@ namespace SharpCompress.Common.SevenZip #endif if (numInStreams < numBindPairs) + { throw new NotSupportedException(); + } int numPackStreams = numInStreams - numBindPairs; + //folder.PackStreams.Reserve(numPackStreams); if (numPackStreams == 1) { @@ -317,7 +348,9 @@ namespace SharpCompress.Common.SevenZip } if (folder.PackStreams.Count != 1) + { throw new NotSupportedException(); + } } else { @@ -417,11 +450,13 @@ namespace SharpCompress.Common.SevenZip #endif BlockType? type; - for (; ; ) + for (;;) { type = ReadId(); if (type == BlockType.End) + { break; + } if (type == BlockType.CRC) { packCRCs = ReadHashDigests(numPackStreams); @@ -434,7 +469,9 @@ namespace SharpCompress.Common.SevenZip { packCRCs = new List(numPackStreams); for (int i = 0; i < numPackStreams; i++) + { packCRCs.Add(null); + } } } finally @@ -462,13 +499,14 @@ namespace SharpCompress.Common.SevenZip using (CStreamSwitch streamSwitch = new CStreamSwitch()) { streamSwitch.Set(this, dataVector); + //folders.Clear(); //folders.Reserve(numFolders); folders = new List(numFolders); int index = 0; for (int i = 0; i < numFolders; i++) { - var f = new CFolder { FirstPackStreamId = index }; + var f = new CFolder {FirstPackStreamId = index}; folders.Add(f); GetNextFolderItem(f); index += f.PackStreams.Count; @@ -499,17 +537,21 @@ namespace SharpCompress.Common.SevenZip #endif } - for (; ; ) + for (;;) { BlockType? type = ReadId(); if (type == BlockType.End) + { return; + } if (type == BlockType.CRC) { List crcs = ReadHashDigests(numFolders); for (int i = 0; i < numFolders; i++) + { folders[i].UnpackCRC = crcs[i]; + } continue; } @@ -536,7 +578,7 @@ namespace SharpCompress.Common.SevenZip numUnpackStreamsInFolders = null; BlockType? type; - for (; ; ) + for (;;) { type = ReadId(); if (type == BlockType.NumUnpackStream) @@ -559,9 +601,13 @@ namespace SharpCompress.Common.SevenZip continue; } if (type == BlockType.CRC || type == BlockType.Size) + { break; + } if (type == BlockType.End) + { break; + } SkipData(); } @@ -569,7 +615,9 @@ namespace SharpCompress.Common.SevenZip { numUnpackStreamsInFolders = new List(folders.Count); for (int i = 0; i < folders.Count; i++) + { numUnpackStreamsInFolders.Add(1); + } } unpackSizes = new List(folders.Count); @@ -579,7 +627,9 @@ namespace SharpCompress.Common.SevenZip // v4.07: we check that folder is empty int numSubstreams = numUnpackStreamsInFolders[i]; if (numSubstreams == 0) + { continue; + } #if DEBUG Log.Write("#{0} StreamSizes:", i); #endif @@ -602,7 +652,9 @@ namespace SharpCompress.Common.SevenZip #endif } if (type == BlockType.Size) + { type = ReadId(); + } int numDigests = 0; int numDigestsTotal = 0; @@ -610,13 +662,15 @@ namespace SharpCompress.Common.SevenZip { int numSubstreams = numUnpackStreamsInFolders[i]; if (numSubstreams != 1 || !folders[i].UnpackCRCDefined) + { numDigests += numSubstreams; + } numDigestsTotal += numSubstreams; } digests = null; - for (; ; ) + for (;;) { if (type == BlockType.CRC) { @@ -636,12 +690,16 @@ namespace SharpCompress.Common.SevenZip else { for (int j = 0; j < numSubstreams; j++, digestIndex++) + { digests.Add(digests2[digestIndex]); + } } } if (digestIndex != numDigests || numDigestsTotal != digests.Count) - System.Diagnostics.Debugger.Break(); + { + Debugger.Break(); + } } else if (type == BlockType.End) { @@ -649,7 +707,9 @@ namespace SharpCompress.Common.SevenZip { digests = new List(numDigestsTotal); for (int i = 0; i < numDigestsTotal; i++) + { digests.Add(null); + } } return; } @@ -693,7 +753,7 @@ namespace SharpCompress.Common.SevenZip unpackSizes = null; digests = null; - for (; ; ) + for (;;) { switch (ReadId()) { @@ -768,12 +828,18 @@ namespace SharpCompress.Common.SevenZip byte[] data = new byte[unpackSize]; outStream.ReadExact(data, 0, data.Length); if (outStream.ReadByte() >= 0) + { throw new InvalidOperationException("Decoded stream is longer than expected."); + } dataVector.Add(data); if (folder.UnpackCRCDefined) + { if (CRC.Finish(CRC.Update(CRC.kInitCRC, data, 0, unpackSize)) != folder.UnpackCRC) + { throw new InvalidOperationException("Decoded stream does not match expected CRC."); + } + } } return dataVector; } @@ -842,10 +908,14 @@ namespace SharpCompress.Common.SevenZip db.Files.Clear(); if (type == BlockType.End) + { return; + } if (type != BlockType.FilesInfo) + { throw new InvalidOperationException(); + } int numFiles = ReadNum(); #if DEBUG @@ -853,18 +923,22 @@ namespace SharpCompress.Common.SevenZip #endif db.Files = new List(numFiles); for (int i = 0; i < numFiles; i++) + { db.Files.Add(new CFileItem()); + } BitVector emptyStreamVector = new BitVector(numFiles); BitVector emptyFileVector = null; BitVector antiFileVector = null; int numEmptyStreams = 0; - for (; ; ) + for (;;) { type = ReadId(); if (type == BlockType.End) + { break; + } long size = checked((long)ReadNumber()); // TODO: throw invalid data on negative int oldPos = _currentReader.Offset; @@ -894,32 +968,34 @@ namespace SharpCompress.Common.SevenZip Log.Write("WinAttributes:"); #endif ReadAttributeVector(dataVector, numFiles, delegate(int i, uint? attr) + { + // Some third party implementations established an unofficial extension + // of the 7z archive format by placing posix file attributes in the high + // bits of the windows file attributes. This makes use of the fact that + // the official implementation does not perform checks on this value. + // + // Newer versions of the official 7z GUI client will try to parse this + // extension, thus acknowledging the unofficial use of these bits. + // + // For us it is safe to just discard the upper bits if they are set and + // keep the windows attributes from the lower bits (which should be set + // properly even if posix file attributes are present, in order to be + // compatible with older 7z archive readers) + // + // Note that the 15th bit is used by some implementations to indicate + // presence of the extension, but not all implementations do that so + // we can't trust that bit and must ignore it. + // + if (attr.HasValue && (attr.Value >> 16) != 0) { - // Some third party implementations established an unofficial extension - // of the 7z archive format by placing posix file attributes in the high - // bits of the windows file attributes. This makes use of the fact that - // the official implementation does not perform checks on this value. - // - // Newer versions of the official 7z GUI client will try to parse this - // extension, thus acknowledging the unofficial use of these bits. - // - // For us it is safe to just discard the upper bits if they are set and - // keep the windows attributes from the lower bits (which should be set - // properly even if posix file attributes are present, in order to be - // compatible with older 7z archive readers) - // - // Note that the 15th bit is used by some implementations to indicate - // presence of the extension, but not all implementations do that so - // we can't trust that bit and must ignore it. - // - if (attr.HasValue && (attr.Value >> 16) != 0) - attr = attr.Value & 0x7FFFu; + attr = attr.Value & 0x7FFFu; + } - db.Files[i].Attrib = attr; + db.Files[i].Attrib = attr; #if DEBUG - Log.Write(" " + (attr.HasValue ? attr.Value.ToString("x8") : "n/a")); + Log.Write(" " + (attr.HasValue ? attr.Value.ToString("x8") : "n/a")); #endif - }); + }); #if DEBUG Log.WriteLine(); #endif @@ -958,7 +1034,9 @@ namespace SharpCompress.Common.SevenZip #if DEBUG Log.Write("EmptyFile: "); for (int i = 0; i < numEmptyStreams; i++) + { Log.Write(emptyFileVector[i] ? "x" : "."); + } Log.WriteLine(); #endif break; @@ -967,7 +1045,9 @@ namespace SharpCompress.Common.SevenZip #if DEBUG Log.Write("Anti: "); for (int i = 0; i < numEmptyStreams; i++) + { Log.Write(antiFileVector[i] ? "x" : "."); + } Log.WriteLine(); #endif break; @@ -976,12 +1056,12 @@ namespace SharpCompress.Common.SevenZip Log.Write("StartPos:"); #endif ReadNumberVector(dataVector, numFiles, delegate(int i, long? startPos) - { - db.Files[i].StartPos = startPos; + { + db.Files[i].StartPos = startPos; #if DEBUG - Log.Write(" " + (startPos.HasValue ? startPos.Value.ToString() : "n/a")); + Log.Write(" " + (startPos.HasValue ? startPos.Value.ToString() : "n/a")); #endif - }); + }); #if DEBUG Log.WriteLine(); #endif @@ -991,12 +1071,12 @@ namespace SharpCompress.Common.SevenZip Log.Write("CTime:"); #endif ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) - { - db.Files[i].CTime = time; + { + db.Files[i].CTime = time; #if DEBUG - Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); + Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); #endif - }); + }); #if DEBUG Log.WriteLine(); #endif @@ -1006,12 +1086,12 @@ namespace SharpCompress.Common.SevenZip Log.Write("ATime:"); #endif ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) - { - db.Files[i].ATime = time; + { + db.Files[i].ATime = time; #if DEBUG - Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); + Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); #endif - }); + }); #if DEBUG Log.WriteLine(); #endif @@ -1021,12 +1101,12 @@ namespace SharpCompress.Common.SevenZip Log.Write("MTime:"); #endif ReadDateTimeVector(dataVector, numFiles, delegate(int i, DateTime? time) - { - db.Files[i].MTime = time; + { + db.Files[i].MTime = time; #if DEBUG - Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); + Log.Write(" " + (time.HasValue ? time.Value.ToString() : "n/a")); #endif - }); + }); #if DEBUG Log.WriteLine(); #endif @@ -1036,8 +1116,12 @@ namespace SharpCompress.Common.SevenZip Log.Write("Dummy: " + size); #endif for (long j = 0; j < size; j++) + { if (ReadByte() != 0) + { throw new InvalidOperationException(); + } + } break; default: SkipData(size); @@ -1047,7 +1131,9 @@ namespace SharpCompress.Common.SevenZip // since 0.3 record sizes must be correct bool checkRecordsSize = (db.MajorVersion > 0 || db.MinorVersion > 2); if (checkRecordsSize && _currentReader.Offset - oldPos != size) + { throw new InvalidOperationException(); + } } int emptyFileIndex = 0; @@ -1095,11 +1181,13 @@ namespace SharpCompress.Common.SevenZip // TODO: Check Signature! _header = new byte[0x20]; - for (int offset = 0; offset < 0x20; ) + for (int offset = 0; offset < 0x20;) { int delta = stream.Read(_header, offset, 0x20 - offset); if (delta == 0) + { throw new EndOfStreamException(); + } offset += delta; } @@ -1109,10 +1197,14 @@ namespace SharpCompress.Common.SevenZip public void Close() { if (_stream != null) + { _stream.Dispose(); + } foreach (var stream in _cachedStreams.Values) + { stream.Dispose(); + } _cachedStreams.Clear(); } @@ -1126,7 +1218,9 @@ namespace SharpCompress.Common.SevenZip db.MinorVersion = _header[7]; if (db.MajorVersion != 0) + { throw new InvalidOperationException(); + } uint crcFromArchive = DataReader.Get32(_header, 8); long nextHeaderOffset = (long)DataReader.Get64(_header, 0xC); @@ -1140,7 +1234,9 @@ namespace SharpCompress.Common.SevenZip crc = CRC.Finish(crc); if (crc != crcFromArchive) + { throw new InvalidOperationException(); + } db.StartPositionAfterHeader = _streamOrigin + 0x20; @@ -1151,12 +1247,15 @@ namespace SharpCompress.Common.SevenZip return db; } - if (nextHeaderOffset < 0 || nextHeaderSize < 0 || nextHeaderSize > Int32.MaxValue) + { throw new InvalidOperationException(); + } if (nextHeaderOffset > _streamEnding - db.StartPositionAfterHeader) + { throw new IndexOutOfRangeException(); + } _stream.Seek(nextHeaderOffset, SeekOrigin.Current); @@ -1164,7 +1263,9 @@ namespace SharpCompress.Common.SevenZip _stream.ReadExact(header, 0, header.Length); if (CRC.Finish(CRC.Update(CRC.kInitCRC, header, 0, header.Length)) != nextHeaderCrc) + { throw new InvalidOperationException(); + } using (CStreamSwitch streamSwitch = new CStreamSwitch()) { @@ -1174,7 +1275,9 @@ namespace SharpCompress.Common.SevenZip if (type != BlockType.Header) { if (type != BlockType.EncodedHeader) + { throw new InvalidOperationException(); + } var dataVector = ReadAndDecodePackedStreams(db.StartPositionAfterHeader, pass); @@ -1186,12 +1289,16 @@ namespace SharpCompress.Common.SevenZip } if (dataVector.Count != 1) + { throw new InvalidOperationException(); + } streamSwitch.Set(this, dataVector[0]); if (ReadId() != BlockType.Header) + { throw new InvalidOperationException(); + } } ReadHeader(db, pass); @@ -1211,55 +1318,41 @@ namespace SharpCompress.Common.SevenZip FileIndex = fileIndex; FolderIndex = folderIndex; if (fileIndex != -1) + { ExtractStatuses.Add(true); + } } } private class FolderUnpackStream : Stream { - private ArchiveDatabase _db; - private int _startIndex; - private List _extractStatuses; + private readonly ArchiveDatabase _db; + private readonly int _startIndex; + private readonly List _extractStatuses; public FolderUnpackStream(ArchiveDatabase db, int p, int startIndex, List list) { - this._db = db; - this._startIndex = startIndex; - this._extractStatuses = list; + _db = db; + _startIndex = startIndex; + _extractStatuses = list; } #region Stream - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { throw new NotSupportedException(); } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -1298,9 +1391,13 @@ namespace SharpCompress.Common.SevenZip Log.WriteLine(_db.Files[index].Name); #endif if (_db.Files[index].CrcDefined) + { _stream = new CrcCheckStream(_db.Files[index].Crc.Value); + } else + { _stream = new MemoryStream(); + } _rem = _db.Files[index].Size; } @@ -1312,7 +1409,9 @@ namespace SharpCompress.Common.SevenZip { int write = count; if (write > _rem) + { write = (int)_rem; + } _stream.Write(buffer, offset, write); count -= write; _rem -= write; @@ -1331,7 +1430,7 @@ namespace SharpCompress.Common.SevenZip if (_currentIndex == _extractStatuses.Count) { // we support partial extracting - System.Diagnostics.Debugger.Break(); + Debugger.Break(); throw new NotSupportedException(); } OpenFile(); @@ -1352,7 +1451,9 @@ namespace SharpCompress.Common.SevenZip long folderStartPackPos = _db.GetFolderStreamPos(folderInfo, 0); List packSizes = new List(); for (int j = 0; j < folderInfo.PackStreams.Count; j++) + { packSizes.Add(_db.PackSizes[packStreamIndex + j]); + } s = DecoderStreamHelper.CreateDecoderStream(_stream, folderStartPackPos, packSizes.ToArray(), folderInfo, pw); @@ -1367,12 +1468,16 @@ namespace SharpCompress.Common.SevenZip int numFilesInFolder = _db.NumUnpackStreamsVector[folderIndex]; int firstFileIndex = _db.FolderStartFileIndex[folderIndex]; if (firstFileIndex > fileIndex || fileIndex - firstFileIndex >= numFilesInFolder) + { throw new InvalidOperationException(); + } int skipCount = fileIndex - firstFileIndex; long skipSize = 0; for (int i = 0; i < skipCount; i++) + { skipSize += _db.Files[firstFileIndex + i].Size; + } Stream s = GetCachedDecoderStream(_db, folderIndex, pw); s.Position = skipSize; @@ -1384,12 +1489,18 @@ namespace SharpCompress.Common.SevenZip int numItems; bool allFilesMode = (indices == null); if (allFilesMode) + { numItems = _db.Files.Count; + } else + { numItems = indices.Length; + } if (numItems == 0) + { return; + } List extractFolderInfoVector = new List(); for (int i = 0; i < numItems; i++) @@ -1404,27 +1515,37 @@ namespace SharpCompress.Common.SevenZip } if (extractFolderInfoVector.Count == 0 || folderIndex != extractFolderInfoVector.Last().FolderIndex) + { extractFolderInfoVector.Add(new CExtractFolderInfo(-1, folderIndex)); + } CExtractFolderInfo efi = extractFolderInfoVector.Last(); int startIndex = _db.FolderStartFileIndex[folderIndex]; for (int index = efi.ExtractStatuses.Count; index <= fileIndex - startIndex; index++) + { efi.ExtractStatuses.Add(index == fileIndex - startIndex); + } } foreach (CExtractFolderInfo efi in extractFolderInfoVector) { int startIndex; if (efi.FileIndex != -1) + { startIndex = efi.FileIndex; + } else + { startIndex = _db.FolderStartFileIndex[efi.FolderIndex]; + } var outStream = new FolderUnpackStream(_db, 0, startIndex, efi.ExtractStatuses); if (efi.FileIndex != -1) + { continue; + } int folderIndex = efi.FolderIndex; CFolder folderInfo = _db.Folders[folderIndex]; @@ -1434,18 +1555,22 @@ namespace SharpCompress.Common.SevenZip List packSizes = new List(); for (int j = 0; j < folderInfo.PackStreams.Count; j++) + { packSizes.Add(_db.PackSizes[packStreamIndex + j]); + } // TODO: If the decoding fails the last file may be extracted incompletely. Delete it? Stream s = DecoderStreamHelper.CreateDecoderStream(_stream, folderStartPackPos, packSizes.ToArray(), folderInfo, pw); byte[] buffer = new byte[4 << 10]; - for (; ; ) + for (;;) { int processed = s.Read(buffer, 0, buffer.Length); if (processed == 0) + { break; + } outStream.Write(buffer, 0, processed); } } diff --git a/src/SharpCompress/Common/SevenZip/CFileItem.cs b/src/SharpCompress/Common/SevenZip/CFileItem.cs index 8c19d984..9d4960e3 100644 --- a/src/SharpCompress/Common/SevenZip/CFileItem.cs +++ b/src/SharpCompress/Common/SevenZip/CFileItem.cs @@ -12,19 +12,13 @@ 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 CrcDefined { get { return Crc != null; } } - public bool AttribDefined - { - get { return Attrib != null; } - } + public bool AttribDefined { get { return Attrib != null; } } public void SetAttrib(uint attrib) { - this.Attrib = attrib; + Attrib = attrib; } public DateTime? CTime { get; internal set; } diff --git a/src/SharpCompress/Common/SevenZip/CFolder.cs b/src/SharpCompress/Common/SevenZip/CFolder.cs index de0a19e7..d7c755a8 100644 --- a/src/SharpCompress/Common/SevenZip/CFolder.cs +++ b/src/SharpCompress/Common/SevenZip/CFolder.cs @@ -13,19 +13,22 @@ namespace SharpCompress.Common.SevenZip internal List UnpackSizes = new List(); internal uint? UnpackCRC; - internal bool UnpackCRCDefined - { - get { return UnpackCRC != null; } - } + internal bool UnpackCRCDefined { get { return UnpackCRC != null; } } public long GetUnpackSize() { if (UnpackSizes.Count == 0) + { return 0; + } for (int i = UnpackSizes.Count - 1; i >= 0; i--) + { if (FindBindPairForOutStream(i) < 0) + { return UnpackSizes[i]; + } + } throw new Exception(); } @@ -34,7 +37,9 @@ namespace SharpCompress.Common.SevenZip { int count = 0; for (int i = 0; i < Coders.Count; i++) + { count += Coders[i].NumOutStreams; + } return count; } @@ -42,8 +47,12 @@ namespace SharpCompress.Common.SevenZip public int FindBindPairForInStream(int inStreamIndex) { for (int i = 0; i < BindPairs.Count; i++) + { if (BindPairs[i].InIndex == inStreamIndex) + { return i; + } + } return -1; } @@ -51,8 +60,12 @@ namespace SharpCompress.Common.SevenZip public int FindBindPairForOutStream(int outStreamIndex) { for (int i = 0; i < BindPairs.Count; i++) + { if (BindPairs[i].OutIndex == outStreamIndex) + { return i; + } + } return -1; } @@ -60,8 +73,12 @@ namespace SharpCompress.Common.SevenZip public int FindPackStreamArrayIndex(int inStreamIndex) { for (int i = 0; i < PackStreams.Count; i++) + { if (PackStreams[i] == inStreamIndex) + { return i; + } + } return -1; } @@ -69,8 +86,12 @@ namespace SharpCompress.Common.SevenZip public bool IsEncrypted() { for (int i = Coders.Count - 1; i >= 0; i--) + { if (Coders[i].MethodId == CMethodId.kAES) + { return true; + } + } return false; } @@ -82,25 +103,39 @@ namespace SharpCompress.Common.SevenZip const int kNumBindsMax = 32; if (Coders.Count > kNumCodersMax || BindPairs.Count > kNumBindsMax) + { return false; + } { 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; + } + } } { 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]; @@ -112,9 +147,13 @@ namespace SharpCompress.Common.SevenZip { 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); + } } for (int i = 0; i < BindPairs.Count; i++) @@ -125,13 +164,23 @@ namespace SharpCompress.Common.SevenZip } 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; } diff --git a/src/SharpCompress/Common/SevenZip/CMethodId.cs b/src/SharpCompress/Common/SevenZip/CMethodId.cs index ecc40aaf..685d28bb 100644 --- a/src/SharpCompress/Common/SevenZip/CMethodId.cs +++ b/src/SharpCompress/Common/SevenZip/CMethodId.cs @@ -16,7 +16,7 @@ public CMethodId(ulong id) { - this.Id = id; + Id = id; } public override int GetHashCode() @@ -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) @@ -48,7 +48,9 @@ { int bytes = 0; for (ulong value = Id; value != 0; value >>= 8) + { bytes++; + } return bytes; } } diff --git a/src/SharpCompress/Common/SevenZip/CStreamSwitch.cs b/src/SharpCompress/Common/SevenZip/CStreamSwitch.cs index ca054db1..5be7094b 100644 --- a/src/SharpCompress/Common/SevenZip/CStreamSwitch.cs +++ b/src/SharpCompress/Common/SevenZip/CStreamSwitch.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; using SharpCompress.Compressor.LZMA; namespace SharpCompress.Common.SevenZip @@ -47,7 +46,9 @@ namespace SharpCompress.Common.SevenZip { int dataIndex = archive.ReadNum(); if (dataIndex < 0 || dataIndex >= dataVector.Count) + { throw new InvalidOperationException(); + } #if DEBUG Log.WriteLine("[switch to stream {0}]", dataIndex); diff --git a/src/SharpCompress/Common/SevenZip/DataReader.cs b/src/SharpCompress/Common/SevenZip/DataReader.cs index da43db15..f821aca4 100644 --- a/src/SharpCompress/Common/SevenZip/DataReader.cs +++ b/src/SharpCompress/Common/SevenZip/DataReader.cs @@ -11,31 +11,30 @@ namespace SharpCompress.Common.SevenZip 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); + return 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); + return 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 #region Variables - private byte[] _buffer; - private int _offset; - private int _ending; + private readonly byte[] _buffer; + private readonly int _ending; #endregion @@ -44,38 +43,43 @@ namespace SharpCompress.Common.SevenZip public DataReader(byte[] buffer, int offset, int length) { _buffer = buffer; - _offset = offset; + Offset = offset; _ending = offset + length; } - public int Offset - { - get { return _offset; } - } + public int Offset { get; private set; } public Byte ReadByte() { - if (_offset >= _ending) + 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) + if (length > _ending - Offset) + { throw new EndOfStreamException(); + } while (length-- > 0) - buffer[offset++] = _buffer[_offset++]; + { + buffer[offset++] = _buffer[Offset++]; + } } public void SkipData(long size) { - if (size > _ending - _offset) + if (size > _ending - Offset) + { throw new EndOfStreamException(); + } - _offset += (int) size; + Offset += (int)size; #if DEBUG Log.WriteLine("SkipData {0}", size); #endif @@ -83,15 +87,17 @@ namespace SharpCompress.Common.SevenZip public void SkipData() { - SkipData(checked((long) ReadNumber())); + SkipData(checked((long)ReadNumber())); } public ulong ReadNumber() { - if (_offset >= _ending) + if (Offset >= _ending) + { throw new EndOfStreamException(); + } - byte firstByte = _buffer[_offset++]; + byte firstByte = _buffer[Offset++]; byte mask = 0x80; ulong value = 0; @@ -100,14 +106,16 @@ namespace SharpCompress.Common.SevenZip if ((firstByte & mask) == 0) { ulong highPart = firstByte & (mask - 1u); - value += highPart << (i*8); + value += highPart << (i * 8); return value; } - if (_offset >= _ending) + if (Offset >= _ending) + { throw new EndOfStreamException(); + } - value |= (ulong) _buffer[_offset++] << (8*i); + value |= (ulong)_buffer[Offset++] << (8 * i); mask >>= 1; } @@ -118,48 +126,58 @@ namespace SharpCompress.Common.SevenZip { ulong value = ReadNumber(); if (value > Int32.MaxValue) + { throw new NotSupportedException(); + } - return (int) value; + return (int)value; } public uint ReadUInt32() { - if (_offset + 4 > _ending) + if (Offset + 4 > _ending) + { throw new EndOfStreamException(); + } - uint res = Get32(_buffer, _offset); - _offset += 4; + uint res = Get32(_buffer, Offset); + Offset += 4; return res; } public ulong ReadUInt64() { - if (_offset + 8 > _ending) + if (Offset + 8 > _ending) + { throw new EndOfStreamException(); + } - ulong res = Get64(_buffer, _offset); - _offset += 8; + ulong res = Get64(_buffer, Offset); + Offset += 8; return res; } public string ReadString() { - int ending = _offset; + int ending = Offset; for (;;) { if (ending + 2 > _ending) + { throw new EndOfStreamException(); + } if (_buffer[ending] == 0 && _buffer[ending + 1] == 0) + { break; + } ending += 2; } - string str = Encoding.Unicode.GetString(_buffer, _offset, ending - _offset); - _offset = ending + 2; + string str = Encoding.Unicode.GetString(_buffer, Offset, ending - Offset); + Offset = ending + 2; return str; } diff --git a/src/SharpCompress/Common/SevenZip/SevenZipEntry.cs b/src/SharpCompress/Common/SevenZip/SevenZipEntry.cs index c832c7b0..e6665f01 100644 --- a/src/SharpCompress/Common/SevenZip/SevenZipEntry.cs +++ b/src/SharpCompress/Common/SevenZip/SevenZipEntry.cs @@ -7,79 +7,37 @@ namespace SharpCompress.Common.SevenZip { internal SevenZipEntry(SevenZipFilePart filePart) { - this.FilePart = filePart; + FilePart = filePart; } - internal SevenZipFilePart FilePart { get; private set; } + internal SevenZipFilePart FilePart { get; } - public override CompressionType CompressionType - { - get { return FilePart.CompressionType; } - } + public override CompressionType CompressionType { get { return FilePart.CompressionType; } } - public override long Crc - { - get { return FilePart.Header.Crc ?? 0; } - } + public override long Crc { get { return FilePart.Header.Crc ?? 0; } } - public override string Key - { - get { return FilePart.Header.Name; } - } + public override string Key { get { return FilePart.Header.Name; } } - public override long CompressedSize - { - get { return 0; } - } + public override long CompressedSize { get { return 0; } } - public override long Size - { - get { return (long) FilePart.Header.Size; } - } + public override long Size { get { return FilePart.Header.Size; } } - public override DateTime? LastModifiedTime - { - get { return FilePart.Header.MTime; } - } + public override DateTime? LastModifiedTime { get { return FilePart.Header.MTime; } } - public override DateTime? CreatedTime - { - get { return null; } - } + public override DateTime? CreatedTime { get { return null; } } - public override DateTime? LastAccessedTime - { - get { return null; } - } + public override DateTime? LastAccessedTime { get { return null; } } - public override DateTime? ArchivedTime - { - get { return null; } - } + public override DateTime? ArchivedTime { get { return null; } } - public override bool IsEncrypted - { - get { return false; } - } + public override bool IsEncrypted { get { return false; } } - public override bool IsDirectory - { - get { return FilePart.Header.IsDir; } - } + public override bool IsDirectory { get { return FilePart.Header.IsDir; } } - public override bool IsSplit - { - get { return false; } - } + public override bool IsSplit { get { return false; } } - public override int? Attrib - { - get { return (int) FilePart.Header.Attrib; } - } + public override int? Attrib { get { return (int)FilePart.Header.Attrib; } } - internal override IEnumerable Parts - { - get { return FilePart.AsEnumerable(); } - } + internal override IEnumerable Parts { get { return FilePart.AsEnumerable(); } } } } \ No newline at end of file diff --git a/src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs b/src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs index ed403687..7f77aadf 100644 --- a/src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs +++ b/src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs @@ -8,8 +8,8 @@ namespace SharpCompress.Common.SevenZip internal class SevenZipFilePart : FilePart { private CompressionType? type; - private Stream stream; - private ArchiveDatabase database; + private readonly Stream stream; + private readonly ArchiveDatabase database; internal SevenZipFilePart(Stream stream, ArchiveDatabase database, int index, CFileItem fileEntry) { @@ -24,14 +24,11 @@ namespace SharpCompress.Common.SevenZip } internal Stream BaseStream { get; private set; } - internal CFileItem Header { get; private set; } - internal CFolder Folder { get; private set; } - internal int Index { get; private set; } + internal CFileItem Header { get; } + internal CFolder Folder { get; } + internal int Index { get; } - internal override string FilePartName - { - get { return Header.Name; } - } + internal override string FilePartName { get { return Header.Name; } } internal override Stream GetRawStream() { @@ -90,17 +87,17 @@ namespace SharpCompress.Common.SevenZip { case k_LZMA: case k_LZMA2: - { - return CompressionType.LZMA; - } + { + return CompressionType.LZMA; + } case k_PPMD: - { - return CompressionType.PPMd; - } + { + return CompressionType.PPMd; + } case k_BZip2: - { - return CompressionType.BZip2; - } + { + return CompressionType.BZip2; + } default: throw new NotImplementedException(); } diff --git a/src/SharpCompress/Common/Tar/Headers/EntryType.cs b/src/SharpCompress/Common/Tar/Headers/EntryType.cs index a8b55ea6..06ba1f0d 100644 --- a/src/SharpCompress/Common/Tar/Headers/EntryType.cs +++ b/src/SharpCompress/Common/Tar/Headers/EntryType.cs @@ -3,17 +3,17 @@ 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', - GlobalExtendedHeader = (byte) 'g', + 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', + GlobalExtendedHeader = (byte)'g' } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Tar/Headers/TarHeader.cs b/src/SharpCompress/Common/Tar/Headers/TarHeader.cs index 8505204f..32db86d7 100644 --- a/src/SharpCompress/Common/Tar/Headers/TarHeader.cs +++ b/src/SharpCompress/Common/Tar/Headers/TarHeader.cs @@ -10,6 +10,7 @@ namespace SharpCompress.Common.Tar.Headers internal static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal string Name { get; set; } + //internal int Mode { get; set; } //internal int UserId { get; set; } //internal string UserName { get; set; } @@ -77,7 +78,9 @@ namespace SharpCompress.Common.Tar.Headers // pad to multiple of BlockSize bytes, and make sure a terminating null is added int numPaddingBytes = BlockSize - (nameBytes.Length % BlockSize); if (numPaddingBytes == 0) + { numPaddingBytes = BlockSize; + } output.Write(new byte[numPaddingBytes], 0, numPaddingBytes); } @@ -131,11 +134,15 @@ namespace SharpCompress.Common.Tar.Headers private string ReadLongName(BinaryReader reader, byte[] buffer) { var size = ReadSize(buffer); - var nameLength = (int) size; + var nameLength = (int)size; var nameBytes = reader.ReadBytes(nameLength); - var remainingBytesToRead = BlockSize - (nameLength%BlockSize); + var remainingBytesToRead = BlockSize - (nameLength % BlockSize); + // Read the rest of the block and discard the data - if (remainingBytesToRead < BlockSize) reader.ReadBytes(remainingBytesToRead); + if (remainingBytesToRead < BlockSize) + { + reader.ReadBytes(remainingBytesToRead); + } return ArchiveEncoding.Default.GetString(nameBytes, 0, nameBytes.Length).TrimNulls(); } diff --git a/src/SharpCompress/Common/Tar/TarEntry.cs b/src/SharpCompress/Common/Tar/TarEntry.cs index a9c1f1c2..6fe0ba9e 100644 --- a/src/SharpCompress/Common/Tar/TarEntry.cs +++ b/src/SharpCompress/Common/Tar/TarEntry.cs @@ -9,78 +9,38 @@ namespace SharpCompress.Common.Tar public class TarEntry : Entry { private readonly TarFilePart filePart; - private readonly CompressionType type; internal TarEntry(TarFilePart filePart, CompressionType type) { this.filePart = filePart; - this.type = type; + CompressionType = type; } - public override CompressionType CompressionType - { - get { return type; } - } + public override CompressionType CompressionType { get; } - public override long Crc - { - get { return 0; } - } + public override long Crc { get { return 0; } } - public override string Key - { - get { return filePart.Header.Name; } - } + public override string Key { get { return filePart.Header.Name; } } - public override long CompressedSize - { - get { return filePart.Header.Size; } - } + public override long CompressedSize { get { return filePart.Header.Size; } } - public override long Size - { - get { return filePart.Header.Size; } - } + public override long Size { get { return filePart.Header.Size; } } - public override DateTime? LastModifiedTime - { - get { return filePart.Header.LastModifiedTime; } - } + public override DateTime? LastModifiedTime { get { return filePart.Header.LastModifiedTime; } } - public override DateTime? CreatedTime - { - get { return null; } - } + public override DateTime? CreatedTime { get { return null; } } - public override DateTime? LastAccessedTime - { - get { return null; } - } + public override DateTime? LastAccessedTime { get { return null; } } - public override DateTime? ArchivedTime - { - get { return null; } - } + public override DateTime? ArchivedTime { get { return null; } } - public override bool IsEncrypted - { - get { return false; } - } + public override bool IsEncrypted { get { return false; } } - public override bool IsDirectory - { - get { return filePart.Header.EntryType == EntryType.Directory; } - } + public override bool IsDirectory { get { return filePart.Header.EntryType == EntryType.Directory; } } - public override bool IsSplit - { - get { return false; } - } + public override bool IsSplit { get { return false; } } - internal override IEnumerable Parts - { - get { return filePart.AsEnumerable(); } - } + internal override IEnumerable Parts { get { return filePart.AsEnumerable(); } } internal static IEnumerable GetEntries(StreamingMode mode, Stream stream, CompressionType compressionType) diff --git a/src/SharpCompress/Common/Tar/TarFilePart.cs b/src/SharpCompress/Common/Tar/TarFilePart.cs index 766c87b8..3b0a5729 100644 --- a/src/SharpCompress/Common/Tar/TarFilePart.cs +++ b/src/SharpCompress/Common/Tar/TarFilePart.cs @@ -14,12 +14,9 @@ namespace SharpCompress.Common.Tar Header = header; } - internal TarHeader Header { get; private set; } + internal TarHeader Header { get; } - internal override string FilePartName - { - get { return Header.Name; } - } + internal override string FilePartName { get { return Header.Name; } } internal override Stream GetCompressedStream() { diff --git a/src/SharpCompress/Common/Tar/TarHeaderFactory.cs b/src/SharpCompress/Common/Tar/TarHeaderFactory.cs index 32787c8b..bc31269c 100644 --- a/src/SharpCompress/Common/Tar/TarHeaderFactory.cs +++ b/src/SharpCompress/Common/Tar/TarHeaderFactory.cs @@ -23,21 +23,22 @@ namespace SharpCompress.Common.Tar switch (mode) { case StreamingMode.Seekable: - { - header.DataStartPosition = reader.BaseStream.Position; - //skip to nearest 512 - reader.BaseStream.Position += PadTo512(header.Size); - } + { + header.DataStartPosition = reader.BaseStream.Position; + + //skip to nearest 512 + reader.BaseStream.Position += PadTo512(header.Size); + } break; case StreamingMode.Streaming: - { - header.PackedStream = new TarReadOnlySubStream(stream, header.Size); - } + { + header.PackedStream = new TarReadOnlySubStream(stream, header.Size); + } break; default: - { - throw new InvalidFormatException("Invalid StreamingMode"); - } + { + throw new InvalidFormatException("Invalid StreamingMode"); + } } } catch @@ -50,7 +51,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; diff --git a/src/SharpCompress/Common/Tar/TarReadOnlySubStream.cs b/src/SharpCompress/Common/Tar/TarReadOnlySubStream.cs index a62abe39..420bdafe 100644 --- a/src/SharpCompress/Common/Tar/TarReadOnlySubStream.cs +++ b/src/SharpCompress/Common/Tar/TarReadOnlySubStream.cs @@ -1,4 +1,5 @@ -using System.IO; +using System; +using System.IO; namespace SharpCompress.Common.Tar { @@ -39,38 +40,22 @@ namespace SharpCompress.Common.Tar private long BytesLeftToRead { get; set; } - public Stream Stream { get; private set; } + public Stream Stream { get; } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } - public override long Length - { - get { throw new System.NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new System.NotSupportedException(); } - set { throw new System.NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -89,17 +74,17 @@ namespace SharpCompress.Common.Tar public override long Seek(long offset, SeekOrigin origin) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } public override void SetLength(long value) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Volume.cs b/src/SharpCompress/Common/Volume.cs index 42c2c3d6..1d1f8ac6 100644 --- a/src/SharpCompress/Common/Volume.cs +++ b/src/SharpCompress/Common/Volume.cs @@ -13,29 +13,20 @@ namespace SharpCompress.Common Options = options; } - internal Stream Stream - { - get { return new NonDisposingStream(actualStream); } - } + internal Stream Stream { get { return new NonDisposingStream(actualStream); } } - internal Options Options { get; private set; } + internal Options Options { get; } /// /// RarArchive is the first volume of a multi-part archive. /// Only Rar 3.0 format and higher /// - public virtual bool IsFirstVolume - { - get { return true; } - } + public virtual bool IsFirstVolume { get { return true; } } /// /// RarArchive is part of a multi-part archive. /// - public virtual bool IsMultiVolume - { - get { return true; } - } + public virtual bool IsMultiVolume { get { return true; } } private bool disposed; diff --git a/src/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs b/src/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs index 755c9ae0..f776f0e1 100644 --- a/src/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs +++ b/src/SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs @@ -14,8 +14,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(); @@ -47,8 +47,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); @@ -56,10 +56,11 @@ 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); @@ -67,6 +68,7 @@ namespace SharpCompress.Common.Zip.Headers writer.Write(RelativeOffsetOfEntryHeader); writer.Write(nameBytes); + // writer.Write(Extra); writer.Write(Comment); } diff --git a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs index 73b2df15..666d683f 100644 --- a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs +++ b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs @@ -13,8 +13,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(); @@ -28,17 +28,17 @@ namespace SharpCompress.Common.Zip.Headers LoadExtra(extra); var unicodePathExtra = Extra.FirstOrDefault(u => u.Type == ExtraDataType.UnicodePathExtraField); - if (unicodePathExtra!=null) + if (unicodePathExtra != null) { - Name = ((ExtraUnicodePathExtraField) unicodePathExtra).UnicodeName; + Name = ((ExtraUnicodePathExtraField)unicodePathExtra).UnicodeName; } } 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); @@ -47,8 +47,9 @@ 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); diff --git a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs index f7a98861..3cc79850 100644 --- a/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs +++ b/src/SharpCompress/Common/Zip/Headers/LocalEntryHeaderExtraFactory.cs @@ -8,6 +8,7 @@ namespace SharpCompress.Common.Zip.Headers WinZipAes = 0x9901, NotImplementedExtraData = 0xFFFF, + // Third Party Mappings // -Info-ZIP Unicode Path Extra Field UnicodePathExtraField = 0x7075 @@ -22,17 +23,14 @@ namespace SharpCompress.Common.Zip.Headers internal class ExtraUnicodePathExtraField : ExtraData { - internal byte Version - { - get { return this.DataBytes[0]; } - } + internal byte Version { get { return DataBytes[0]; } } internal byte[] NameCRC32 { get { var crc = new byte[4]; - Buffer.BlockCopy(this.DataBytes, 1, crc, 0, 4); + Buffer.BlockCopy(DataBytes, 1, crc, 0, 4); return crc; } } @@ -42,8 +40,8 @@ namespace SharpCompress.Common.Zip.Headers get { // PathNamelength = dataLength - Version(1 byte) - NameCRC32(4 bytes) - var length = this.Length - 5; - var nameStr = Encoding.UTF8.GetString(this.DataBytes, 5, length); + var length = Length - 5; + var nameStr = Encoding.UTF8.GetString(DataBytes, 5, length); return nameStr; } } @@ -51,25 +49,25 @@ namespace SharpCompress.Common.Zip.Headers internal static class LocalEntryHeaderExtraFactory { - internal static ExtraData Create(ExtraDataType type,ushort length, byte[] extraData) + internal static ExtraData Create(ExtraDataType type, ushort length, byte[] extraData) { switch (type) { case ExtraDataType.UnicodePathExtraField: - return new ExtraUnicodePathExtraField() - { - Type = type, - Length = length, - DataBytes = extraData - }; + return new ExtraUnicodePathExtraField + { + Type = type, + Length = length, + DataBytes = extraData + }; default: return new ExtraData - { - Type = type, - Length = length, - DataBytes = extraData - }; + { + Type = type, + Length = length, + DataBytes = extraData + }; } } } -} +} \ No newline at end of file diff --git a/src/SharpCompress/Common/Zip/Headers/SplitHeader.cs b/src/SharpCompress/Common/Zip/Headers/SplitHeader.cs index 8dbb4c61..d6816b59 100644 --- a/src/SharpCompress/Common/Zip/Headers/SplitHeader.cs +++ b/src/SharpCompress/Common/Zip/Headers/SplitHeader.cs @@ -1,4 +1,5 @@ using System; +using System.IO; namespace SharpCompress.Common.Zip.Headers { @@ -9,12 +10,12 @@ namespace SharpCompress.Common.Zip.Headers { } - internal override void Read(System.IO.BinaryReader reader) + internal override void Read(BinaryReader reader) { throw new NotImplementedException(); } - internal override void Write(System.IO.BinaryWriter writer) + internal override void Write(BinaryWriter writer) { throw new NotImplementedException(); } diff --git a/src/SharpCompress/Common/Zip/Headers/ZipFileEntry.cs b/src/SharpCompress/Common/Zip/Headers/ZipFileEntry.cs index a5f79a06..1e6cdd43 100644 --- a/src/SharpCompress/Common/Zip/Headers/ZipFileEntry.cs +++ b/src/SharpCompress/Common/Zip/Headers/ZipFileEntry.cs @@ -19,13 +19,14 @@ namespace SharpCompress.Common.Zip.Headers get { if (Name.EndsWith("/")) + { return true; + } //.NET Framework 4.5 : System.IO.Compression::CreateFromDirectory() probably writes backslashes to headers return CompressedSize == 0 - && UncompressedSize == 0 - && Name.EndsWith("\\"); - + && UncompressedSize == 0 + && Name.EndsWith("\\"); } } @@ -77,10 +78,10 @@ namespace SharpCompress.Common.Zip.Headers protected void LoadExtra(byte[] extra) { - for (int i = 0; i < extra.Length-4;) + for (int i = 0; i < extra.Length - 4;) { ExtraDataType type = (ExtraDataType)DataConverter.LittleEndian.GetUInt16(extra, i); - if (!Enum.IsDefined(typeof (ExtraDataType), type)) + if (!Enum.IsDefined(typeof(ExtraDataType), type)) { type = ExtraDataType.NotImplementedExtraData; } @@ -88,7 +89,7 @@ namespace SharpCompress.Common.Zip.Headers ushort length = DataConverter.LittleEndian.GetUInt16(extra, i + 2); byte[] data = new byte[length]; Buffer.BlockCopy(extra, i + 4, data, 0, length); - Extra.Add(LocalEntryHeaderExtraFactory.Create(type,length,data)); + Extra.Add(LocalEntryHeaderExtraFactory.Create(type, length, data)); i += length + 4; } diff --git a/src/SharpCompress/Common/Zip/Headers/ZipHeaderType.cs b/src/SharpCompress/Common/Zip/Headers/ZipHeaderType.cs index 45570381..75cba925 100644 --- a/src/SharpCompress/Common/Zip/Headers/ZipHeaderType.cs +++ b/src/SharpCompress/Common/Zip/Headers/ZipHeaderType.cs @@ -6,6 +6,6 @@ LocalEntry, DirectoryEntry, DirectoryEnd, - Split, + Split } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Zip/PkwareTraditionalCryptoStream.cs b/src/SharpCompress/Common/Zip/PkwareTraditionalCryptoStream.cs index 97ac7ed4..86d0d2d9 100644 --- a/src/SharpCompress/Common/Zip/PkwareTraditionalCryptoStream.cs +++ b/src/SharpCompress/Common/Zip/PkwareTraditionalCryptoStream.cs @@ -9,7 +9,6 @@ namespace SharpCompress.Common.Zip Decrypt } - internal class PkwareTraditionalCryptoStream : Stream { private readonly PkwareTraditionalEncryptionData encryptor; @@ -24,40 +23,27 @@ namespace SharpCompress.Common.Zip this.mode = mode; } + public override bool CanRead { get { return (mode == CryptoMode.Decrypt); } } - public override bool CanRead - { - get { return (mode == CryptoMode.Decrypt); } - } + public override bool CanSeek { get { return false; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanWrite { get { return (mode == CryptoMode.Encrypt); } } - public override bool CanWrite - { - get { return (mode == CryptoMode.Encrypt); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Length - { - get { throw new NotSupportedException(); } - } - - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { if (mode == CryptoMode.Encrypt) + { throw new NotSupportedException("This stream does not encrypt via Read()"); + } if (buffer == null) + { throw new ArgumentNullException("buffer"); + } byte[] temp = new byte[count]; int readBytes = stream.Read(temp, 0, count); @@ -69,7 +55,9 @@ namespace SharpCompress.Common.Zip public override void Write(byte[] buffer, int offset, int count) { if (mode == CryptoMode.Decrypt) + { throw new NotSupportedException("This stream does not Decrypt via Write()"); + } if (count == 0) { diff --git a/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs b/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs index 313bb64a..c7cd622e 100644 --- a/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs +++ b/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs @@ -19,8 +19,8 @@ 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); } } @@ -29,13 +29,13 @@ namespace SharpCompress.Common.Zip { 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."); } @@ -43,17 +43,18 @@ namespace SharpCompress.Common.Zip return encryptor; } - public byte[] Decrypt(byte[] cipherText, int length) { if (length > cipherText.Length) + { throw new ArgumentOutOfRangeException("length", "Bad length during Decryption: the length parameter must be smaller than or equal to the size of the destination array."); + } 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; } @@ -63,17 +64,21 @@ namespace SharpCompress.Common.Zip public byte[] Encrypt(byte[] plainText, int length) { if (plainText == null) + { throw new ArgumentNullException("plaintext"); + } if (length > plainText.Length) + { throw new ArgumentOutOfRangeException("length", "Bad length during Encryption: The length parameter must be smaller than or equal to the size of the destination array."); + } var cipherText = new byte[length]; 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; @@ -83,7 +88,9 @@ namespace SharpCompress.Common.Zip { byte[] p = StringToByteArray(password); for (int i = 0; i < password.Length; i++) + { UpdateKeys(p[i]); + } } internal static byte[] StringToByteArray(string value, Encoding encoding) @@ -99,10 +106,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/src/SharpCompress/Common/Zip/SeekableZipFilePart.cs b/src/SharpCompress/Common/Zip/SeekableZipFilePart.cs index dc4fc61d..5042f23f 100644 --- a/src/SharpCompress/Common/Zip/SeekableZipFilePart.cs +++ b/src/SharpCompress/Common/Zip/SeekableZipFilePart.cs @@ -24,10 +24,7 @@ namespace SharpCompress.Common.Zip return base.GetCompressedStream(); } - internal string Comment - { - get { return (Header as DirectoryEntryHeader).Comment; } - } + internal string Comment { get { return (Header as DirectoryEntryHeader).Comment; } } private void LoadLocalHeader() { diff --git a/src/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs b/src/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs index 98eb9f43..874c88f1 100644 --- a/src/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs +++ b/src/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs @@ -35,9 +35,10 @@ namespace SharpCompress.Common.Zip 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."); + "Could not find Zip file Directory at the end of the file. File may be corrupted."); } - } while (signature != DIRECTORY_END_HEADER_BYTES); + } + while (signature != DIRECTORY_END_HEADER_BYTES); var entry = new DirectoryEndHeader(); entry.Read(reader); @@ -55,6 +56,7 @@ namespace SharpCompress.Common.Zip { yield break; } + //entry could be zero bytes so we need to know that. directoryEntryHeader.HasData = directoryEntryHeader.CompressedSize != 0; yield return directoryEntryHeader; diff --git a/src/SharpCompress/Common/Zip/WinzipAesCryptoStream.cs b/src/SharpCompress/Common/Zip/WinzipAesCryptoStream.cs index 637fb7c3..e571e50e 100644 --- a/src/SharpCompress/Common/Zip/WinzipAesCryptoStream.cs +++ b/src/SharpCompress/Common/Zip/WinzipAesCryptoStream.cs @@ -1,3 +1,4 @@ + #if !NO_CRYPTO using System; using System.IO; diff --git a/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs b/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs index 075398c1..baf9cd7f 100644 --- a/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs +++ b/src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs @@ -1,3 +1,4 @@ + #if !NO_CRYPTO using System; using System.Security.Cryptography; diff --git a/src/SharpCompress/Common/Zip/WinzipAesKeySize.cs b/src/SharpCompress/Common/Zip/WinzipAesKeySize.cs index 7df0cb6f..4a39f46d 100644 --- a/src/SharpCompress/Common/Zip/WinzipAesKeySize.cs +++ b/src/SharpCompress/Common/Zip/WinzipAesKeySize.cs @@ -4,6 +4,6 @@ { KeySize128 = 1, KeySize192 = 2, - KeySize256 = 3, + KeySize256 = 3 } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Zip/ZipEntry.cs b/src/SharpCompress/Common/Zip/ZipEntry.cs index 7b962ace..45363306 100644 --- a/src/SharpCompress/Common/Zip/ZipEntry.cs +++ b/src/SharpCompress/Common/Zip/ZipEntry.cs @@ -7,14 +7,13 @@ namespace SharpCompress.Common.Zip public class ZipEntry : Entry { private readonly ZipFilePart filePart; - private readonly DateTime? lastModifiedTime; internal ZipEntry(ZipFilePart filePart) { if (filePart != null) { this.filePart = filePart; - lastModifiedTime = Utility.DosDateToDateTime(filePart.Header.LastModifiedDate, + LastModifiedTime = Utility.DosDateToDateTime(filePart.Header.LastModifiedDate, filePart.Header.LastModifiedTime); } } @@ -26,91 +25,55 @@ namespace SharpCompress.Common.Zip switch (filePart.Header.CompressionMethod) { case ZipCompressionMethod.BZip2: - { - return CompressionType.BZip2; - } + { + return CompressionType.BZip2; + } case ZipCompressionMethod.Deflate: - { - return CompressionType.Deflate; - } + { + return CompressionType.Deflate; + } case ZipCompressionMethod.LZMA: - { - return CompressionType.LZMA; - } + { + return CompressionType.LZMA; + } case ZipCompressionMethod.PPMd: - { - return CompressionType.PPMd; - } + { + return CompressionType.PPMd; + } case ZipCompressionMethod.None: - { - return CompressionType.None; - } + { + return CompressionType.None; + } default: - { - return CompressionType.Unknown; - } + { + return CompressionType.Unknown; + } } } } - public override long Crc - { - get { return filePart.Header.Crc; } - } + public override long Crc { get { return filePart.Header.Crc; } } - public override string Key - { - get { return filePart.Header.Name; } - } + public override string Key { get { return filePart.Header.Name; } } - public override long CompressedSize - { - get { return filePart.Header.CompressedSize; } - } + public override long CompressedSize { get { return filePart.Header.CompressedSize; } } - public override long Size - { - get { return filePart.Header.UncompressedSize; } - } + public override long Size { get { return filePart.Header.UncompressedSize; } } - public override DateTime? LastModifiedTime - { - get { return lastModifiedTime; } - } + public override DateTime? LastModifiedTime { get; } - public override DateTime? CreatedTime - { - get { return null; } - } + public override DateTime? CreatedTime { get { return null; } } - public override DateTime? LastAccessedTime - { - get { return null; } - } + public override DateTime? LastAccessedTime { get { return null; } } - public override DateTime? ArchivedTime - { - get { return null; } - } + public override DateTime? ArchivedTime { get { return null; } } - public override bool IsEncrypted - { - get { return FlagUtility.HasFlag(filePart.Header.Flags, HeaderFlags.Encrypted); } - } + public override bool IsEncrypted { get { return FlagUtility.HasFlag(filePart.Header.Flags, HeaderFlags.Encrypted); } } - public override bool IsDirectory - { - get { return filePart.Header.IsDirectory; } - } + public override bool IsDirectory { get { return filePart.Header.IsDirectory; } } - public override bool IsSplit - { - get { return false; } - } + public override bool IsSplit { get { return false; } } - internal override IEnumerable Parts - { - get { return filePart.AsEnumerable(); } - } + internal override IEnumerable Parts { get { return filePart.AsEnumerable(); } } } } \ No newline at end of file diff --git a/src/SharpCompress/Common/Zip/ZipFilePart.cs b/src/SharpCompress/Common/Zip/ZipFilePart.cs index fd1b0a2f..a8377aca 100644 --- a/src/SharpCompress/Common/Zip/ZipFilePart.cs +++ b/src/SharpCompress/Common/Zip/ZipFilePart.cs @@ -18,17 +18,13 @@ namespace SharpCompress.Common.Zip { Header = header; header.Part = this; - this.BaseStream = stream; + BaseStream = stream; } internal Stream BaseStream { get; private set; } internal ZipFileEntry Header { get; set; } - - internal override string FilePartName - { - get { return Header.Name; } - } + internal override string FilePartName { get { return Header.Name; } } internal override Stream GetCompressedStream() { @@ -55,79 +51,76 @@ namespace SharpCompress.Common.Zip protected abstract Stream CreateBaseStream(); - protected bool LeaveStreamOpen - { - get { return FlagUtility.HasFlag(Header.Flags, HeaderFlags.UsePostDataDescriptor); } - } + protected bool LeaveStreamOpen { get { return FlagUtility.HasFlag(Header.Flags, HeaderFlags.UsePostDataDescriptor); } } protected Stream CreateDecompressionStream(Stream stream) { switch (Header.CompressionMethod) { case ZipCompressionMethod.None: - { - return stream; - } + { + return stream; + } case ZipCompressionMethod.Deflate: - { - return new DeflateStream(stream, CompressionMode.Decompress); - } + { + return new DeflateStream(stream, CompressionMode.Decompress); + } case ZipCompressionMethod.BZip2: - { - return new BZip2Stream(stream, CompressionMode.Decompress); - } + { + return new BZip2Stream(stream, CompressionMode.Decompress); + } case ZipCompressionMethod.LZMA: + { + if (FlagUtility.HasFlag(Header.Flags, HeaderFlags.Encrypted)) { - if (FlagUtility.HasFlag(Header.Flags, HeaderFlags.Encrypted)) - { - throw new NotSupportedException("LZMA with pkware encryption."); - } - var reader = new BinaryReader(stream); - reader.ReadUInt16(); //LZMA version - var props = new byte[reader.ReadUInt16()]; - reader.Read(props, 0, props.Length); - return new LzmaStream(props, stream, - Header.CompressedSize > 0 ? Header.CompressedSize - 4 - props.Length : -1, - FlagUtility.HasFlag(Header.Flags, HeaderFlags.Bit1) - ? -1 - : (long)Header.UncompressedSize); + throw new NotSupportedException("LZMA with pkware encryption."); } + var reader = new BinaryReader(stream); + reader.ReadUInt16(); //LZMA version + var props = new byte[reader.ReadUInt16()]; + reader.Read(props, 0, props.Length); + return new LzmaStream(props, stream, + Header.CompressedSize > 0 ? Header.CompressedSize - 4 - props.Length : -1, + FlagUtility.HasFlag(Header.Flags, HeaderFlags.Bit1) + ? -1 + : (long)Header.UncompressedSize); + } case ZipCompressionMethod.PPMd: - { - var props = new byte[2]; - stream.Read(props, 0, props.Length); - return new PpmdStream(new PpmdProperties(props), stream, false); - } + { + var props = new byte[2]; + stream.Read(props, 0, props.Length); + return new PpmdStream(new PpmdProperties(props), stream, false); + } case ZipCompressionMethod.WinzipAes: + { + ExtraData data = Header.Extra.Where(x => x.Type == ExtraDataType.WinZipAes).SingleOrDefault(); + if (data == null) { - ExtraData data = Header.Extra.Where(x => x.Type == ExtraDataType.WinZipAes).SingleOrDefault(); - if (data == null) - { - throw new InvalidFormatException("No Winzip AES extra data found."); - } - if (data.Length != 7) - { - throw new InvalidFormatException("Winzip data length is not 7."); - } - ushort method = DataConverter.LittleEndian.GetUInt16(data.DataBytes, 0); - - if (method != 0x01 && method != 0x02) - { - throw new InvalidFormatException("Unexpected vendor version number for WinZip AES metadata"); - } - - ushort vendorId = DataConverter.LittleEndian.GetUInt16(data.DataBytes, 2); - if (vendorId != 0x4541) - { - throw new InvalidFormatException("Unexpected vendor ID for WinZip AES metadata"); - } - Header.CompressionMethod = (ZipCompressionMethod)DataConverter.LittleEndian.GetUInt16(data.DataBytes, 5); - return CreateDecompressionStream(stream); + throw new InvalidFormatException("No Winzip AES extra data found."); } + if (data.Length != 7) + { + throw new InvalidFormatException("Winzip data length is not 7."); + } + ushort method = DataConverter.LittleEndian.GetUInt16(data.DataBytes, 0); + + if (method != 0x01 && method != 0x02) + { + throw new InvalidFormatException("Unexpected vendor version number for WinZip AES metadata"); + } + + ushort vendorId = DataConverter.LittleEndian.GetUInt16(data.DataBytes, 2); + if (vendorId != 0x4541) + { + throw new InvalidFormatException("Unexpected vendor ID for WinZip AES metadata"); + } + Header.CompressionMethod = (ZipCompressionMethod)DataConverter.LittleEndian.GetUInt16(data.DataBytes, 5); + return CreateDecompressionStream(stream); + } default: - { - throw new NotSupportedException("CompressionMethod: " + Header.CompressionMethod); - } + { + throw new NotSupportedException("CompressionMethod: " + Header.CompressionMethod); + } } } @@ -137,7 +130,7 @@ namespace SharpCompress.Common.Zip #if !NO_CRYPTO && ((Header.PkwareTraditionalEncryptionData != null) || (Header.WinzipAesEncryptionData != null))) -#else +#else && (Header.PkwareTraditionalEncryptionData != null)) #endif { diff --git a/src/SharpCompress/Common/Zip/ZipHeaderFactory.cs b/src/SharpCompress/Common/Zip/ZipHeaderFactory.cs index 3275e345..542dbe3c 100644 --- a/src/SharpCompress/Common/Zip/ZipHeaderFactory.cs +++ b/src/SharpCompress/Common/Zip/ZipHeaderFactory.cs @@ -2,7 +2,6 @@ using System.IO; using SharpCompress.Common.Zip.Headers; using SharpCompress.IO; -using System.Linq; namespace SharpCompress.Common.Zip { @@ -18,10 +17,9 @@ namespace SharpCompress.Common.Zip private const uint ZIP64_END_OF_CENTRAL_DIRECTORY = 0x06064b50; private const uint ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR = 0x07064b50; - protected LocalEntryHeader lastEntryHeader; - private string password; - private StreamingMode mode; + private readonly string password; + private readonly StreamingMode mode; protected ZipHeaderFactory(StreamingMode mode, string password) { @@ -34,55 +32,55 @@ namespace SharpCompress.Common.Zip switch (headerBytes) { case ENTRY_HEADER_BYTES: - { - var entryHeader = new LocalEntryHeader(); - entryHeader.Read(reader); - LoadHeader(entryHeader, reader.BaseStream); + { + var entryHeader = new LocalEntryHeader(); + entryHeader.Read(reader); + LoadHeader(entryHeader, reader.BaseStream); - lastEntryHeader = entryHeader; - return entryHeader; - } + lastEntryHeader = entryHeader; + return entryHeader; + } case DIRECTORY_START_HEADER_BYTES: - { - var entry = new DirectoryEntryHeader(); - entry.Read(reader); - return entry; - } + { + var entry = new DirectoryEntryHeader(); + entry.Read(reader); + return entry; + } case POST_DATA_DESCRIPTOR: + { + if (FlagUtility.HasFlag(lastEntryHeader.Flags, HeaderFlags.UsePostDataDescriptor)) { - if (FlagUtility.HasFlag(lastEntryHeader.Flags, HeaderFlags.UsePostDataDescriptor)) - { - lastEntryHeader.Crc = reader.ReadUInt32(); - lastEntryHeader.CompressedSize = reader.ReadUInt32(); - lastEntryHeader.UncompressedSize = reader.ReadUInt32(); - } - else - { - reader.ReadUInt32(); - reader.ReadUInt32(); - reader.ReadUInt32(); - } - return null; + lastEntryHeader.Crc = reader.ReadUInt32(); + lastEntryHeader.CompressedSize = reader.ReadUInt32(); + lastEntryHeader.UncompressedSize = reader.ReadUInt32(); } + else + { + reader.ReadUInt32(); + reader.ReadUInt32(); + reader.ReadUInt32(); + } + return null; + } case DIGITAL_SIGNATURE: return null; case DIRECTORY_END_HEADER_BYTES: - { - var entry = new DirectoryEndHeader(); - entry.Read(reader); - return entry; - } + { + var entry = new DirectoryEndHeader(); + entry.Read(reader); + return entry; + } case SPLIT_ARCHIVE_HEADER_BYTES: - { - return new SplitHeader(); - } + { + return new SplitHeader(); + } case ZIP64_END_OF_CENTRAL_DIRECTORY: case ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR: - { - var entry = new IgnoreHeader(ZipHeaderType.Ignore); - entry.Read(reader); - return entry; - } + { + var entry = new IgnoreHeader(ZipHeaderType.Ignore); + entry.Read(reader); + return entry; + } default: throw new NotSupportedException("Unknown header: " + headerBytes); } @@ -115,7 +113,7 @@ namespace SharpCompress.Common.Zip 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."); + "SharpCompress cannot currently read non-seekable Zip Streams with encrypted data that has been written in a non-seekable manner."); } if (password == null) { @@ -154,6 +152,7 @@ namespace SharpCompress.Common.Zip { return; } + //if (FlagUtility.HasFlag(entryHeader.Flags, HeaderFlags.UsePostDataDescriptor)) //{ // entryHeader.PackedStream = new ReadOnlySubStream(stream); @@ -163,21 +162,22 @@ namespace SharpCompress.Common.Zip switch (mode) { case StreamingMode.Seekable: - { - entryHeader.DataStartPosition = stream.Position; - stream.Position += entryHeader.CompressedSize; - } + { + entryHeader.DataStartPosition = stream.Position; + stream.Position += entryHeader.CompressedSize; + } break; case StreamingMode.Streaming: - { - entryHeader.PackedStream = stream; - } + { + entryHeader.PackedStream = stream; + } break; default: - { - throw new InvalidFormatException("Invalid StreamingMode"); - } + { + throw new InvalidFormatException("Invalid StreamingMode"); + } } + //} } } diff --git a/src/SharpCompress/Compressor/ADC/ADCBase.cs b/src/SharpCompress/Compressor/ADC/ADCBase.cs index c16be093..aa67fc5c 100644 --- a/src/SharpCompress/Compressor/ADC/ADCBase.cs +++ b/src/SharpCompress/Compressor/ADC/ADCBase.cs @@ -24,6 +24,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; +using System; using System.IO; namespace SharpCompress.Compressor.ADC @@ -40,9 +41,13 @@ namespace SharpCompress.Compressor.ADC static int GetChunkType(byte byt) { if ((byt & 0x80) == 0x80) + { return Plain; + } if ((byt & 0x40) == 0x40) + { return ThreeByte; + } return TwoByte; } @@ -100,7 +105,9 @@ namespace SharpCompress.Compressor.ADC output = null; if (input == null || input.Length == 0) + { return 0; + } int start = (int)input.Position; int position = (int)input.Position; @@ -116,7 +123,9 @@ namespace SharpCompress.Compressor.ADC { int readByte = input.ReadByte(); if (readByte == -1) + { break; + } chunkType = GetChunkType((byte)readByte); @@ -199,7 +208,9 @@ namespace SharpCompress.Compressor.ADC } if (full) + { break; + } } output = new byte[outPosition]; @@ -207,4 +218,4 @@ namespace SharpCompress.Compressor.ADC return position - start; } } -} +} \ No newline at end of file diff --git a/src/SharpCompress/Compressor/ADC/ADCStream.cs b/src/SharpCompress/Compressor/ADC/ADCStream.cs index 1c3e9120..f2e14395 100644 --- a/src/SharpCompress/Compressor/ADC/ADCStream.cs +++ b/src/SharpCompress/Compressor/ADC/ADCStream.cs @@ -24,6 +24,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; +using System; using System.IO; namespace SharpCompress.Compressor.ADC @@ -37,18 +38,22 @@ namespace SharpCompress.Compressor.ADC /// This stream holds the compressed data /// private readonly Stream stream; + /// /// Is this instance disposed? /// private bool isDisposed; + /// /// Position in decompressed data /// - private long position = 0; + private long position; + /// /// Buffer with currently used chunk of decompressed data /// private byte[] outBuffer; + /// /// Position in buffer of decompressed data /// @@ -62,36 +67,22 @@ namespace SharpCompress.Compressor.ADC public ADCStream(Stream stream, CompressionMode compressionMode = CompressionMode.Decompress) { if (compressionMode == CompressionMode.Compress) + { throw new NotSupportedException(); + } this.stream = stream; } - public override bool CanRead - { - get { return stream.CanRead; } - } + public override bool CanRead { get { return stream.CanRead; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { return position; } - set { throw new NotSupportedException(); } - } + public override long Position { get { return position; } set { throw new NotSupportedException(); } } public override void Flush() { @@ -100,7 +91,9 @@ namespace SharpCompress.Compressor.ADC protected override void Dispose(bool disposing) { if (isDisposed) + { return; + } isDisposed = true; base.Dispose(disposing); } @@ -108,15 +101,25 @@ namespace SharpCompress.Compressor.ADC public override int Read(byte[] buffer, int offset, int count) { if (count == 0) + { return 0; + } if (buffer == null) + { throw new ArgumentNullException("buffer"); + } if (count < 0) + { throw new ArgumentOutOfRangeException("count"); + } if (offset < buffer.GetLowerBound(0)) + { throw new ArgumentOutOfRangeException("offset"); + } if ((offset + count) > buffer.GetLength(0)) + { throw new ArgumentOutOfRangeException("count"); + } int size = -1; @@ -141,7 +144,9 @@ namespace SharpCompress.Compressor.ADC size = ADCBase.Decompress(stream, out outBuffer); outPosition = 0; if (size == 0 || outBuffer == null || outBuffer.Length == 0) + { return copied; + } } Array.Copy(outBuffer, outPosition, buffer, inPosition, toCopy); @@ -166,4 +171,4 @@ namespace SharpCompress.Compressor.ADC throw new NotSupportedException(); } } -} +} \ No newline at end of file diff --git a/src/SharpCompress/Compressor/BZip2/BZip2Constants.cs b/src/SharpCompress/Compressor/BZip2/BZip2Constants.cs index 8d445fa2..9c8cbb5b 100644 --- a/src/SharpCompress/Compressor/BZip2/BZip2Constants.cs +++ b/src/SharpCompress/Compressor/BZip2/BZip2Constants.cs @@ -39,63 +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 - }; + { + 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/src/SharpCompress/Compressor/BZip2/BZip2Stream.cs b/src/SharpCompress/Compressor/BZip2/BZip2Stream.cs index 8f986428..518d3fb4 100644 --- a/src/SharpCompress/Compressor/BZip2/BZip2Stream.cs +++ b/src/SharpCompress/Compressor/BZip2/BZip2Stream.cs @@ -27,10 +27,10 @@ namespace SharpCompress.Compressor.BZip2 this.stream = new CBZip2InputStream(stream, decompressContacted, leaveOpen); } } - + public void Finish() { - (this.stream as CBZip2OutputStream)?.Finish(); + (stream as CBZip2OutputStream)?.Finish(); } protected override void Dispose(bool disposing) @@ -46,38 +46,22 @@ namespace SharpCompress.Compressor.BZip2 } } - public CompressionMode Mode { get; private set; } + public CompressionMode Mode { get; } - public override bool CanRead - { - get { return stream.CanRead; } - } + public override bool CanRead { get { return stream.CanRead; } } - public override bool CanSeek - { - get { return stream.CanSeek; } - } + public override bool CanSeek { get { return stream.CanSeek; } } - public override bool CanWrite - { - get { return stream.CanWrite; } - } + public override bool CanWrite { get { return stream.CanWrite; } } public override void Flush() { stream.Flush(); } - public override long Length - { - get { return stream.Length; } - } + public override long Length { get { return stream.Length; } } - public override long Position - { - get { return stream.Position; } - set { stream.Position = value; } - } + public override long Position { get { return stream.Position; } set { stream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { diff --git a/src/SharpCompress/Compressor/BZip2/CBZip2InputStream.cs b/src/SharpCompress/Compressor/BZip2/CBZip2InputStream.cs index 4e82ee65..9e3a43fb 100644 --- a/src/SharpCompress/Compressor/BZip2/CBZip2InputStream.cs +++ b/src/SharpCompress/Compressor/BZip2/CBZip2InputStream.cs @@ -93,16 +93,16 @@ namespace SharpCompress.Compressor.BZip2 private int bsBuff; private int bsLive; - private CRC mCrc = new CRC(); + private readonly CRC mCrc = new CRC(); - private bool[] inUse = new bool[256]; + private readonly bool[] inUse = new bool[256]; private int nInUse; - private char[] seqToUnseq = new char[256]; - private char[] unseqToSeq = new char[256]; + private readonly char[] seqToUnseq = new char[256]; + private readonly char[] unseqToSeq = new char[256]; - private char[] selector = new char[BZip2Constants.MAX_SELECTORS]; - private char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS]; + private readonly char[] selector = new char[BZip2Constants.MAX_SELECTORS]; + private readonly char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS]; private int[] tt; private char[] ll8; @@ -111,17 +111,17 @@ namespace SharpCompress.Compressor.BZip2 freq table collected to save a pass over the data during decompression. */ - private int[] unzftab = new int[256]; + private readonly int[] unzftab = new int[256]; - private int[][] limit = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); - private int[][] basev = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); - private int[][] perm = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); - private int[] minLens = new int[BZip2Constants.N_GROUPS]; + private readonly int[][] limit = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); + private readonly int[][] basev = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); + private readonly int[][] perm = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); + private readonly int[] minLens = new int[BZip2Constants.N_GROUPS]; private Stream bsStream; private bool leaveOpen; - private bool streamEnd = false; + private bool streamEnd; private int currentChar = -1; @@ -137,12 +137,12 @@ namespace SharpCompress.Compressor.BZip2 private int storedBlockCRC, storedCombinedCRC; private int computedBlockCRC, computedCombinedCRC; - private bool decompressConcatenated; + private readonly bool decompressConcatenated; private int i2, count, chPrev, ch2; private int i, tPos; - private int rNToGo = 0; - private int rTPos = 0; + private int rNToGo; + private int rTPos; private int j2; private char z; private bool isDisposed; @@ -198,34 +198,31 @@ namespace SharpCompress.Compressor.BZip2 { return -1; } - else + int retChar = currentChar; + switch (currentState) { - int retChar = currentChar; - switch (currentState) - { - case START_BLOCK_STATE: - break; - case RAND_PART_A_STATE: - break; - case RAND_PART_B_STATE: - SetupRandPartB(); - break; - case RAND_PART_C_STATE: - SetupRandPartC(); - break; - case NO_RAND_PART_A_STATE: - break; - case NO_RAND_PART_B_STATE: - SetupNoRandPartB(); - break; - case NO_RAND_PART_C_STATE: - SetupNoRandPartC(); - break; - default: - break; - } - return retChar; + case START_BLOCK_STATE: + break; + case RAND_PART_A_STATE: + break; + case RAND_PART_B_STATE: + SetupRandPartB(); + break; + case RAND_PART_C_STATE: + SetupRandPartC(); + break; + case NO_RAND_PART_A_STATE: + break; + case NO_RAND_PART_B_STATE: + SetupNoRandPartB(); + break; + case NO_RAND_PART_C_STATE: + SetupNoRandPartC(); + break; + default: + break; } + return retChar; } private bool Initialize(bool isFirstStream) @@ -250,7 +247,7 @@ namespace SharpCompress.Compressor.BZip2 } SetDecompressStructureSizes(magic3 - '0'); - this.bsLive = 0; + bsLive = 0; computedCombinedCRC = 0; return true; } @@ -275,7 +272,9 @@ namespace SharpCompress.Compressor.BZip2 } if (Complete()) + { return; + } } if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 @@ -357,11 +356,13 @@ namespace SharpCompress.Compressor.BZip2 { try { - if (this.bsStream != null) + if (bsStream != null) { if (!leaveOpen) - this.bsStream.Dispose(); - this.bsStream = null; + { + bsStream.Dispose(); + } + bsStream = null; } } catch @@ -424,12 +425,12 @@ namespace SharpCompress.Compressor.BZip2 private int BsGetIntVS(int numBits) { - return (int)BsR(numBits); + return BsR(numBits); } private int BsGetInt32() { - return (int)BsGetint(); + return BsGetint(); } private void HbCreateDecodeTables(int[] limit, int[] basev, @@ -748,7 +749,8 @@ namespace SharpCompress.Compressor.BZip2 } nextSym = perm[zt][zvec - basev[zt][zn]]; } - } while (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB); + } + while (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB); s++; ch = seqToUnseq[yy[0]]; @@ -765,7 +767,6 @@ namespace SharpCompress.Compressor.BZip2 { BlockOverrun(); } - continue; } else { @@ -841,7 +842,6 @@ namespace SharpCompress.Compressor.BZip2 } nextSym = perm[zt][zvec - basev[zt][zn]]; } - continue; } } } @@ -863,7 +863,7 @@ namespace SharpCompress.Compressor.BZip2 for (i = 0; i <= last; i++) { - ch = (char)ll8[i]; + ch = ll8[i]; tt[cftab[ch]] = i; cftab[ch]++; } @@ -904,7 +904,7 @@ namespace SharpCompress.Compressor.BZip2 } } rNToGo--; - ch2 ^= (int)((rNToGo == 1) ? 1 : 0); + ch2 ^= (rNToGo == 1) ? 1 : 0; i2++; currentChar = ch2; @@ -980,7 +980,7 @@ namespace SharpCompress.Compressor.BZip2 private void SetupRandPartC() { - if (j2 < (int)z) + if (j2 < z) { currentChar = ch2; mCrc.UpdateCRC(ch2); @@ -1024,7 +1024,7 @@ namespace SharpCompress.Compressor.BZip2 private void SetupNoRandPartC() { - if (j2 < (int)z) + if (j2 < z) { currentChar = ch2; mCrc.UpdateCRC(ch2); @@ -1071,7 +1071,9 @@ namespace SharpCompress.Compressor.BZip2 { c = ReadByte(); if (c == -1) + { break; + } buffer[k + offset] = (byte)c; } return k; @@ -1090,30 +1092,14 @@ namespace SharpCompress.Compressor.BZip2 { } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } - public override long Length - { - get { return 0; } - } + public override long Length { get { return 0; } } - public override long Position - { - get { return 0; } - set { } - } + public override long Position { get { return 0; } set { } } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/BZip2/CBZip2OutputStream.cs b/src/SharpCompress/Compressor/BZip2/CBZip2OutputStream.cs index 7addf723..6442ca28 100644 --- a/src/SharpCompress/Compressor/BZip2/CBZip2OutputStream.cs +++ b/src/SharpCompress/Compressor/BZip2/CBZip2OutputStream.cs @@ -69,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++; } } @@ -87,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++) { @@ -187,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++; @@ -209,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(); } @@ -224,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; @@ -239,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; } } @@ -260,23 +260,23 @@ namespace SharpCompress.Compressor.BZip2 always: in the range 0 .. 9. The current block size is 100000 * this number. */ - private int blockSize100k; + private readonly int blockSize100k; private bool blockRandomised; private int bytesOut; private int bsBuff; private int bsLive; - private CRC mCrc = new CRC(); + private readonly CRC mCrc = new CRC(); - private bool[] inUse = new bool[256]; + private readonly bool[] inUse = new bool[256]; private int nInUse; - private char[] seqToUnseq = new char[256]; - private char[] unseqToSeq = new char[256]; + private readonly char[] seqToUnseq = new char[256]; + private readonly char[] unseqToSeq = new char[256]; - private char[] selector = new char[BZip2Constants.MAX_SELECTORS]; - private char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS]; + private readonly char[] selector = new char[BZip2Constants.MAX_SELECTORS]; + private readonly char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS]; private char[] block; private int[] quadrant; @@ -286,21 +286,21 @@ namespace SharpCompress.Compressor.BZip2 private int nMTF; - private int[] mtfFreq = new int[BZip2Constants.MAX_ALPHA_SIZE]; + private readonly int[] mtfFreq = new int[BZip2Constants.MAX_ALPHA_SIZE]; /* * Used when sorting. If too many long comparisons * happen, we stop sorting, randomise the block * slightly, and try again. */ - private int workFactor; + private readonly int workFactor; private int workDone; private int workLimit; private bool firstAttempt; private int nBlocksRandomised; private int currentChar = -1; - private int runLength = 0; + private int runLength; public CBZip2OutputStream(Stream inStream) : this(inStream, 9, false) @@ -319,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); @@ -347,7 +347,7 @@ namespace SharpCompress.Compressor.BZip2 public override void WriteByte(byte bv) { - int b = (256 + bv)%256; + int b = (256 + bv) % 256; if (currentChar != -1) { if (currentChar == b) @@ -381,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; } } @@ -426,7 +426,7 @@ namespace SharpCompress.Compressor.BZip2 } } - private bool disposed = false; + private bool disposed; protected override void Dispose(bool disposing) { @@ -442,7 +442,9 @@ namespace SharpCompress.Compressor.BZip2 disposed = true; base.Dispose(); if (!leaveOpen) + { bsStream.Dispose(); + } bsStream = null; } } @@ -493,6 +495,7 @@ namespace SharpCompress.Compressor.BZip2 // blockNo++; mCrc.InitialiseCRC(); last = -1; + // ch = 0; for (int i = 0; i < 256; i++) @@ -501,13 +504,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 */ @@ -609,7 +612,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) { @@ -628,7 +631,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) { @@ -673,7 +676,7 @@ namespace SharpCompress.Compressor.BZip2 { for (v = 0; v < alphaSize; v++) { - len[t][v] = (char) GREATER_ICOST; + len[t][v] = (char)GREATER_ICOST; } } @@ -713,7 +716,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) @@ -723,7 +726,7 @@ namespace SharpCompress.Compressor.BZip2 } if (ge > gs && nPart != nGroups && nPart != 1 - && ((nGroups - nPart)%2 == 1)) + && ((nGroups - nPart) % 2 == 1)) { aFreq -= mtfFreq[ge]; ge--; @@ -733,11 +736,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; } } @@ -800,12 +803,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; @@ -821,7 +824,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]; } } } @@ -843,7 +846,7 @@ namespace SharpCompress.Compressor.BZip2 ; totc += bc; fave[bt]++; - selector[nSelectors] = (char) bt; + selector[nSelectors] = (char)bt; nSelectors++; /* @@ -874,19 +877,18 @@ namespace SharpCompress.Compressor.BZip2 { Panic(); } - if (!(nSelectors < 32768 && nSelectors <= (2 + (900000/BZip2Constants.G_SIZE)))) + if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / BZip2Constants.G_SIZE)))) { Panic(); } - /* Compute MTF values for the selectors. */ { char[] pos = new char[BZip2Constants.N_GROUPS]; 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++) { @@ -901,7 +903,7 @@ namespace SharpCompress.Compressor.BZip2 pos[j] = tmp2; } pos[0] = tmp; - selectorMtf[i] = (char) j; + selectorMtf[i] = (char)j; } } @@ -942,7 +944,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; } @@ -968,7 +970,7 @@ namespace SharpCompress.Compressor.BZip2 { for (j = 0; j < 16; j++) { - if (inUse[i*16 + j]) + if (inUse[i * 16 + j]) { BsW(1, 1); } @@ -1244,7 +1246,7 @@ namespace SharpCompress.Compressor.BZip2 { break; } - n = ((int) block[zptr[unLo] + d + 1]) - med; + n = block[zptr[unLo] + d + 1] - med; if (n == 0) { int temp = 0; @@ -1268,7 +1270,7 @@ namespace SharpCompress.Compressor.BZip2 { break; } - n = ((int) block[zptr[unHi] + d + 1]) - med; + n = block[zptr[unHi] + d + 1] - med; if (n == 0) { int temp = 0; @@ -1349,14 +1351,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] = block[last + 1]; if (last < 4000) { @@ -1428,11 +1430,12 @@ 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]; @@ -1450,7 +1453,8 @@ namespace SharpCompress.Compressor.BZip2 } runningOrder[j] = vv; } - } while (h != 1); + } + while (h != 1); } /* @@ -1571,7 +1575,7 @@ namespace SharpCompress.Compressor.BZip2 { if (rNToGo == 0) { - rNToGo = (char) BZip2Constants.rNums[rTPos]; + rNToGo = (char)BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { @@ -1579,9 +1583,10 @@ 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; } @@ -1591,7 +1596,7 @@ namespace SharpCompress.Compressor.BZip2 { int i; - workLimit = workFactor*last; + workLimit = workFactor * last; workDone = 0; blockRandomised = false; firstAttempt = true; @@ -1763,7 +1768,8 @@ namespace SharpCompress.Compressor.BZip2 k -= 4; workDone++; - } while (k >= 0); + } + while (k >= 0); return false; } @@ -1775,16 +1781,16 @@ namespace SharpCompress.Compressor.BZip2 usually small, typically <= 20. */ - private int[] incs = - { - 1, 4, 13, 40, 121, 364, 1093, 3280, - 9841, 29524, 88573, 265720, - 797161, 2391484 - }; + private readonly 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]; @@ -1809,8 +1815,7 @@ namespace SharpCompress.Compressor.BZip2 */ // szptr = zptr; - - szptr = new short[2*n]; + szptr = new short[2 * n]; } private void GenerateMTFValues() @@ -1835,10 +1840,9 @@ namespace SharpCompress.Compressor.BZip2 zPend = 0; for (i = 0; i < nInUse; i++) { - yy[i] = (char) i; + yy[i] = (char)i; } - for (i = 0; i <= last; i++) { char ll_i; @@ -1868,15 +1872,15 @@ namespace SharpCompress.Compressor.BZip2 zPend--; while (true) { - switch (zPend%2) + switch (zPend % 2) { case 0: - szptr[wr] = (short) BZip2Constants.RUNA; + szptr[wr] = BZip2Constants.RUNA; wr++; mtfFreq[BZip2Constants.RUNA]++; break; case 1: - szptr[wr] = (short) BZip2Constants.RUNB; + szptr[wr] = BZip2Constants.RUNB; wr++; mtfFreq[BZip2Constants.RUNB]++; break; @@ -1886,12 +1890,12 @@ namespace SharpCompress.Compressor.BZip2 { 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]++; } @@ -1902,15 +1906,15 @@ namespace SharpCompress.Compressor.BZip2 zPend--; while (true) { - switch (zPend%2) + switch (zPend % 2) { case 0: - szptr[wr] = (short) BZip2Constants.RUNA; + szptr[wr] = BZip2Constants.RUNA; wr++; mtfFreq[BZip2Constants.RUNA]++; break; case 1: - szptr[wr] = (short) BZip2Constants.RUNB; + szptr[wr] = BZip2Constants.RUNB; wr++; mtfFreq[BZip2Constants.RUNB]++; break; @@ -1919,11 +1923,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]++; @@ -1952,30 +1956,14 @@ namespace SharpCompress.Compressor.BZip2 } } - public override bool CanRead - { - get { return false; } - } + public override bool CanRead { get { return false; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return true; } - } + public override bool CanWrite { get { return true; } } - public override long Length - { - get { return 0; } - } + public override long Length { get { return 0; } } - public override long Position - { - get { return 0; } - set { } - } + public override long Position { get { return 0; } set { } } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/BZip2/CRC.cs b/src/SharpCompress/Compressor/BZip2/CRC.cs index 42aa516f..89a16dd7 100644 --- a/src/SharpCompress/Compressor/BZip2/CRC.cs +++ b/src/SharpCompress/Compressor/BZip2/CRC.cs @@ -32,136 +32,136 @@ namespace SharpCompress.Compressor.BZip2 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) - }; + { + 0x00000000, 0x04c11db7, 0x09823b6e, + 0x0d4326d9, + 0x130476dc, 0x17c56b6b, 0x1a864db2, + 0x1e475005, + 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, + 0x2b4bcb61, + 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, + 0x384fbdbd, + 0x4c11db70, 0x48d0c6c7, 0x4593e01e, + 0x4152fda9, + 0x5f15adac, 0x5bd4b01b, 0x569796c2, + 0x52568b75, + 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, + 0x675a1011, + 0x791d4014, 0x7ddc5da3, 0x709f7b7a, + 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), + 0x34867077, 0x30476dc0, 0x3d044b19, + 0x39c556ae, + 0x278206ab, 0x23431b1c, 0x2e003dc5, + 0x2ac12072, + 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, + 0x1fcdbb16, + 0x018aeb13, 0x054bf6a4, 0x0808d07d, + 0x0cc9cdca, + 0x7897ab07, 0x7c56b6b0, 0x71159069, + 0x75d48dde, + 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, + 0x66d0fb02, + 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, + 0x53dc6066, + 0x4d9b3063, 0x495a2dd4, 0x44190b0d, + 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), + 0x690ce0ee, 0x6dcdfd59, 0x608edb80, + 0x644fc637, + 0x7a089632, 0x7ec98b85, 0x738aad5c, + 0x774bb0eb, + 0x4f040d56, 0x4bc510e1, 0x46863638, + 0x42472b8f, + 0x5c007b8a, 0x58c1663d, 0x558240e4, + 0x51435d53, + 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, + 0x285e1d47, + 0x36194d42, 0x32d850f5, 0x3f9b762c, + 0x3b5a6b9b, + 0x0315d626, 0x07d4cb91, 0x0a97ed48, + 0x0e56f0ff, + 0x1011a0fa, 0x14d0bd4d, 0x19939b94, + 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), + 0x5d8a9099, 0x594b8d2e, 0x5408abf7, + 0x50c9b640, + 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, + 0x43cdc09c, + 0x7b827d21, 0x7f436096, 0x7200464f, + 0x76c15bf8, + 0x68860bfd, 0x6c47164a, 0x61043093, + 0x65c52d24, + 0x119b4be9, 0x155a565e, 0x18197087, + 0x1cd86d30, + 0x029f3d35, 0x065e2082, 0x0b1d065b, + 0x0fdc1bec, + 0x3793a651, 0x3352bbe6, 0x3e119d3f, + 0x3ad08088, + 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, + 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() { @@ -170,7 +170,7 @@ namespace SharpCompress.Compressor.BZip2 internal void InitialiseCRC() { - globalCrc = unchecked((int) 0xffffffff); + globalCrc = unchecked((int)0xffffffff); } internal int GetFinalCRC() @@ -195,7 +195,7 @@ namespace SharpCompress.Compressor.BZip2 { temp = 256 + temp; } - globalCrc = (globalCrc << 8) ^ CRC.crc32Table[temp]; + globalCrc = (globalCrc << 8) ^ crc32Table[temp]; } internal int globalCrc; diff --git a/src/SharpCompress/Compressor/CompressionMode.cs b/src/SharpCompress/Compressor/CompressionMode.cs index 31d1ebe4..53db28e6 100644 --- a/src/SharpCompress/Compressor/CompressionMode.cs +++ b/src/SharpCompress/Compressor/CompressionMode.cs @@ -3,6 +3,6 @@ public enum CompressionMode { Compress = 0, - Decompress = 1, + Decompress = 1 } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Deflate/CRC32.cs b/src/SharpCompress/Compressor/Deflate/CRC32.cs index acc179b2..f4812939 100644 --- a/src/SharpCompress/Compressor/Deflate/CRC32.cs +++ b/src/SharpCompress/Compressor/Deflate/CRC32.cs @@ -49,7 +49,6 @@ namespace SharpCompress.Compressor.Deflate private const int BUFFER_SIZE = 8192; private static readonly UInt32[] crc32Table; private UInt32 runningCrc32Result = 0xFFFFFFFF; - private Int64 totalBytesRead; static CRC32() { @@ -89,10 +88,7 @@ namespace SharpCompress.Compressor.Deflate /// indicates the total number of bytes read on the CRC stream. /// This is used when writing the ZipDirEntry when compressing files. /// - public Int64 TotalBytesRead - { - get { return totalBytesRead; } - } + public Int64 TotalBytesRead { get; private set; } /// /// Indicates the current CRC for all blocks slurped in. @@ -102,7 +98,7 @@ namespace SharpCompress.Compressor.Deflate get { // return one's complement of the running result - return unchecked((Int32) (~runningCrc32Result)); + return unchecked((Int32)(~runningCrc32Result)); } } @@ -126,7 +122,9 @@ namespace SharpCompress.Compressor.Deflate public Int32 GetCrc32AndCopy(Stream input, Stream output) { if (input == null) + { throw new ZlibException("The input stream must not be null."); + } unchecked { @@ -135,23 +133,28 @@ namespace SharpCompress.Compressor.Deflate var buffer = new byte[BUFFER_SIZE]; int readSize = BUFFER_SIZE; - totalBytesRead = 0; + TotalBytesRead = 0; int count = input.Read(buffer, 0, readSize); - if (output != null) output.Write(buffer, 0, count); - totalBytesRead += count; + if (output != null) + { + output.Write(buffer, 0, count); + } + TotalBytesRead += count; while (count > 0) { SlurpBlock(buffer, 0, count); count = input.Read(buffer, 0, readSize); - if (output != null) output.Write(buffer, 0, count); - totalBytesRead += count; + if (output != null) + { + output.Write(buffer, 0, count); + } + TotalBytesRead += count; } - return (Int32) (~runningCrc32Result); + return (Int32)(~runningCrc32Result); } } - /// /// Get the CRC32 for the given (word,byte) combo. This is a computation /// defined by PKzip. @@ -161,12 +164,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)); } /// @@ -179,7 +182,9 @@ namespace SharpCompress.Compressor.Deflate public void SlurpBlock(byte[] block, int offset, int count) { if (block == null) + { throw new ZlibException("The data buffer must not be null."); + } for (int i = 0; i < count; i++) { @@ -187,13 +192,11 @@ namespace SharpCompress.Compressor.Deflate runningCrc32Result = ((runningCrc32Result) >> 8) ^ crc32Table[(block[x]) ^ ((runningCrc32Result) & 0x000000FF)]; } - totalBytesRead += count; + TotalBytesRead += count; } - // pre-initialize the crc table for speed of lookup. - private uint gf2_matrix_times(uint[] matrix, uint vec) { uint sum = 0; @@ -201,7 +204,9 @@ namespace SharpCompress.Compressor.Deflate while (vec != 0) { if ((vec & 0x01) == 0x01) + { sum ^= matrix[i]; + } vec >>= 1; i++; } @@ -211,10 +216,11 @@ namespace SharpCompress.Compressor.Deflate private void gf2_matrix_square(uint[] square, uint[] mat) { for (int i = 0; i < 32; i++) + { square[i] = gf2_matrix_times(mat, mat[i]); + } } - /// /// Combines the given CRC32 value with the current running total. /// @@ -231,10 +237,12 @@ namespace SharpCompress.Compressor.Deflate var odd = new uint[32]; // odd-power-of-two zeros operator if (length == 0) + { 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 +259,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) @@ -261,28 +269,33 @@ namespace SharpCompress.Compressor.Deflate gf2_matrix_square(even, odd); if ((len2 & 1) == 1) + { crc1 = gf2_matrix_times(even, crc1); + } len2 >>= 1; if (len2 == 0) + { break; + } // another iteration of the loop with odd and even swapped gf2_matrix_square(odd, even); if ((len2 & 1) == 1) + { crc1 = gf2_matrix_times(odd, crc1); + } len2 >>= 1; - } while (len2 != 0); + } + while (len2 != 0); crc1 ^= crc2; runningCrc32Result = ~crc1; //return (int) crc1; - return; } - // private member vars } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Deflate/DeflateManager.cs b/src/SharpCompress/Compressor/Deflate/DeflateManager.cs index cf46ae37..c786e989 100644 --- a/src/SharpCompress/Compressor/Deflate/DeflateManager.cs +++ b/src/SharpCompress/Compressor/Deflate/DeflateManager.cs @@ -74,18 +74,18 @@ namespace SharpCompress.Compressor.Deflate internal sealed partial class DeflateManager { // 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 - }; + internal static readonly int[] ExtraLengthBits = + { + 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 - }; + internal static readonly int[] ExtraDistanceBits = + { + 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 { @@ -130,55 +130,53 @@ namespace SharpCompress.Compressor.Deflate private Config(int goodLength, int maxLazy, int niceLength, int maxChainLength, DeflateFlavor flavor) { - this.GoodLength = goodLength; - this.MaxLazy = maxLazy; - this.NiceLength = niceLength; - this.MaxChainLength = maxChainLength; - this.Flavor = flavor; + GoodLength = goodLength; + MaxLazy = maxLazy; + NiceLength = niceLength; + MaxChainLength = maxChainLength; + Flavor = flavor; } 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[] + { + 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; } - 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", - "" - }; + private static readonly String[] _ErrorMessage = + { + "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,14 +197,14 @@ 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; @@ -235,10 +233,12 @@ namespace SharpCompress.Compressor.Deflate // To do: use the user input buffer as sliding window. internal int window_size; + // Actual size of window: 2*wSize, except when the user input buffer // is directly used as sliding window. internal short[] prev; + // Link to older string with same hash index. To limit the size of this // 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. @@ -280,20 +280,19 @@ namespace SharpCompress.Compressor.Deflate private CompressionLevel compressionLevel; // compression level (1..9) private CompressionStrategy compressionStrategy; // favor or force Huffman coding + private readonly short[] dyn_ltree; // literal and length tree + private readonly short[] dyn_dtree; // distance tree + private readonly 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 treeBitLengths = new Tree(); // desc for bit length tree + private readonly Tree treeLiterals = new Tree(); // desc for literal tree + private readonly Tree treeDistances = new Tree(); // desc for distance tree + private readonly 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]; + private readonly 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 readonly 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 @@ -302,11 +301,10 @@ namespace SharpCompress.Compressor.Deflate // 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 readonly sbyte[] depth = new sbyte[2 * InternalConstants.L_CODES + 1]; private int _lengthOffset; // index for literals or lengths - // Size of match buffer for literals/lengths. There are 4 reasons for // limiting lit_bufsize to 64K: // - frequencies can be kept in 16 bit counters @@ -347,22 +345,21 @@ namespace SharpCompress.Compressor.Deflate // are always zero. internal int bi_valid; - 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); + //for (int i = 0; i < hash_size; i++) head[i] = 0; config = Config.Lookup(compressionLevel); @@ -400,13 +397,19 @@ 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; } @@ -426,13 +429,17 @@ namespace SharpCompress.Compressor.Deflate { j++; } + // Exit if v is smaller than both sons if (IsSmaller(tree, v, heap[j], depth)) + { break; + } // Exchange v with the smallest son heap[k] = heap[j]; k = j; + // And continue down the tree, setting j to the left son of k j <<= 1; } @@ -441,12 +448,11 @@ 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])); } - // Scan a literal or distance tree to determine the frequencies of the codes // in the bit length tree. internal void ScanTree(short[] tree, int maxCode) @@ -454,7 +460,7 @@ 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 = 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 @@ -464,33 +470,35 @@ namespace SharpCompress.Compressor.Deflate max_count = 138; min_count = 3; } - tree[(maxCode + 1)*2 + 1] = (short) 0x7fff; // guard //?? + tree[(maxCode + 1) * 2 + 1] = 0x7fff; // guard //?? for (n = 0; n <= maxCode; n++) { curlen = nextlen; - nextlen = (int) tree[(n + 1)*2 + 1]; + nextlen = tree[(n + 1) * 2 + 1]; if (++count < max_count && curlen == nextlen) { continue; } - else if (count < min_count) + 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; @@ -524,6 +532,7 @@ namespace SharpCompress.Compressor.Deflate // Build the bit length tree: treeBitLengths.build_tree(this); + // opt_len now includes the length of the tree representations, except // the lengths of the bit lengths codes and the 5+5+4 bits for the counts. @@ -532,16 +541,18 @@ 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; } - // Send the header for a block using dynamic Huffman trees: the counts, the // lengths of the bit length codes, the literal tree and the distance tree. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. @@ -554,7 +565,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 @@ -567,7 +578,7 @@ 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 = tree[0*2 + 1]; // length of next 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 @@ -581,17 +592,18 @@ namespace SharpCompress.Compressor.Deflate for (n = 0; n <= max_code; n++) { curlen = nextlen; - nextlen = tree[(n + 1)*2 + 1]; + nextlen = tree[(n + 1) * 2 + 1]; if (++count < max_count && curlen == nextlen) { continue; } - else if (count < min_count) + if (count < min_count) { do { send_code(curlen, bl_tree); - } while (--count != 0); + } + while (--count != 0); } else if (curlen != 0) { @@ -666,7 +678,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)); } @@ -676,18 +688,18 @@ namespace SharpCompress.Compressor.Deflate int len = length; unchecked { - if (bi_valid > (int) Buf_size - len) + if (bi_valid > Buf_size - len) { //int val = value; // bi_buf |= (val << bi_valid); 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 @@ -729,31 +741,31 @@ namespace SharpCompress.Compressor.Deflate last_eob_len = 7; } - // Save the match info and tally the frequency counts. Return true if // 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; @@ -762,21 +774,23 @@ namespace SharpCompress.Compressor.Deflate for (dcode = 0; dcode < InternalConstants.D_CODES; dcode++) { out_length = - (int) (out_length + (int) dyn_dtree[dcode*2]*(5L + DeflateManager.ExtraDistanceBits[dcode])); + (int)(out_length + dyn_dtree[dcode * 2] * (5L + 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; + } } return (last_lit == lit_bufsize - 1) || (last_lit == lit_bufsize); + // dinoch - wraparound? // We avoid equality with lit_bufsize because of wraparound at 64K // on 16 bit machines and because stored blocks are restricted to // 64K-1 bytes. } - // Send the block data compressed using the given Huffman trees internal void send_compressed_block(short[] ltree, short[] dtree) { @@ -790,7 +804,7 @@ namespace SharpCompress.Compressor.Deflate { do { - int ix = _distanceOffset + lx*2; + int ix = _distanceOffset + lx * 2; distance = ((pending[ix] << 8) & 0xff00) | (pending[ix + 1] & 0xff); lc = (pending[_lengthOffset + lx]) & 0xff; @@ -808,7 +822,7 @@ namespace SharpCompress.Compressor.Deflate // send the length code send_code(code + InternalConstants.LITERALS + 1, ltree); - extra = DeflateManager.ExtraLengthBits[code]; + extra = ExtraLengthBits[code]; if (extra != 0) { // send the extra length bits @@ -821,7 +835,7 @@ namespace SharpCompress.Compressor.Deflate // send the distance code send_code(code, dtree); - extra = DeflateManager.ExtraDistanceBits[code]; + extra = ExtraDistanceBits[code]; if (extra != 0) { // send the extra distance bits @@ -831,14 +845,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 @@ -850,37 +864,36 @@ namespace SharpCompress.Compressor.Deflate int bin_freq = 0; while (n < 7) { - bin_freq += dyn_ltree[n*2]; + bin_freq += dyn_ltree[n * 2]; n++; } while (n < 128) { - ascii_freq += dyn_ltree[n*2]; + ascii_freq += dyn_ltree[n * 2]; n++; } while (n < InternalConstants.LITERALS) { - bin_freq += dyn_ltree[n*2]; + 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; } @@ -891,13 +904,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; @@ -911,15 +924,18 @@ namespace SharpCompress.Compressor.Deflate last_eob_len = 8; // enough lookahead for inflate if (header) + { 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); } @@ -959,9 +975,13 @@ namespace SharpCompress.Compressor.Deflate { _fillWindow(); if (lookahead == 0 && flush == FlushType.None) + { return BlockState.NeedMore; + } if (lookahead == 0) + { break; // flush the current block + } } strstart += lookahead; @@ -972,12 +992,14 @@ 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 = strstart - max_start; + strstart = max_start; flush_block_only(false); if (_codec.AvailableBytesOut == 0) + { return BlockState.NeedMore; + } } // Flush if we may have to slide, otherwise block_start may become @@ -986,18 +1008,21 @@ namespace SharpCompress.Compressor.Deflate { flush_block_only(false); if (_codec.AvailableBytesOut == 0) + { return BlockState.NeedMore; + } } } flush_block_only(flush == FlushType.Finish); if (_codec.AvailableBytesOut == 0) + { return (flush == FlushType.Finish) ? BlockState.FinishStarted : BlockState.NeedMore; + } return flush == FlushType.Finish ? BlockState.FinishDone : BlockState.BlockDone; } - // Send a stored block internal void _tr_stored_block(int buf, int stored_len, bool eof) { @@ -1017,7 +1042,9 @@ namespace SharpCompress.Compressor.Deflate { // Check if the file is ascii or binary if (data_type == Z_UNKNOWN) + { set_data_type(); + } // Construct the literal and distance trees treeLiterals.build_tree(this); @@ -1036,7 +1063,9 @@ namespace SharpCompress.Compressor.Deflate static_lenb = (static_len + 3 + 7) >> 3; if (static_lenb <= opt_lenb) + { opt_lenb = static_lenb; + } } else { @@ -1126,23 +1155,28 @@ 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; } if (_codec.AvailableBytesIn == 0) + { return; + } // If there was no sliding: // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && @@ -1164,9 +1198,11 @@ namespace SharpCompress.Compressor.Deflate ins_h = window[strstart] & 0xff; ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask; } + // 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 +1230,9 @@ namespace SharpCompress.Compressor.Deflate return BlockState.NeedMore; } if (lookahead == 0) + { break; // flush the current block + } } // Insert the string window[strstart .. strstart+2] in the @@ -1206,7 +1244,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. @@ -1221,6 +1259,7 @@ namespace SharpCompress.Compressor.Deflate { match_length = longest_match(hash_head); } + // longest_match() sets match_start } if (match_length >= MIN_MATCH) @@ -1241,14 +1280,16 @@ namespace SharpCompress.Compressor.Deflate strstart++; 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); // strstart never exceeds WSIZE-MAX_MATCH, so there are // always MIN_MATCH bytes ahead. - } while (--match_length != 0); + } + while (--match_length != 0); strstart++; } else @@ -1258,6 +1299,7 @@ namespace SharpCompress.Compressor.Deflate ins_h = window[strstart] & 0xff; ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask; + // If lookahead < MIN_MATCH, ins_h is garbage, but it does not // matter since it will be recomputed at next deflate call. } @@ -1274,7 +1316,9 @@ namespace SharpCompress.Compressor.Deflate { flush_block_only(false); if (_codec.AvailableBytesOut == 0) + { return BlockState.NeedMore; + } } } @@ -1282,9 +1326,10 @@ namespace SharpCompress.Compressor.Deflate if (_codec.AvailableBytesOut == 0) { if (flush == FlushType.Finish) + { return BlockState.FinishStarted; - else - return BlockState.NeedMore; + } + return BlockState.NeedMore; } return flush == FlushType.Finish ? BlockState.FinishDone : BlockState.BlockDone; } @@ -1310,10 +1355,14 @@ namespace SharpCompress.Compressor.Deflate { _fillWindow(); if (lookahead < MIN_LOOKAHEAD && flush == FlushType.None) + { return BlockState.NeedMore; + } if (lookahead == 0) + { break; // flush the current block + } } // Insert the string window[strstart .. strstart+2] in the @@ -1322,10 +1371,11 @@ namespace SharpCompress.Compressor.Deflate if (lookahead >= MIN_MATCH) { 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); } // Find the longest match, discarding those <= prev_length. @@ -1344,6 +1394,7 @@ namespace SharpCompress.Compressor.Deflate { match_length = longest_match(hash_head); } + // longest_match() sets match_start if (match_length <= 5 && (compressionStrategy == CompressionStrategy.Filtered || @@ -1360,6 +1411,7 @@ namespace SharpCompress.Compressor.Deflate if (prev_length >= MIN_MATCH && match_length <= prev_length) { int max_insert = strstart + lookahead - MIN_MATCH; + // Do not insert strings in hash table beyond this. // check_match(strstart-1, prev_match, prev_length); @@ -1378,12 +1430,14 @@ namespace SharpCompress.Compressor.Deflate { 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++; @@ -1392,7 +1446,9 @@ namespace SharpCompress.Compressor.Deflate { flush_block_only(false); if (_codec.AvailableBytesOut == 0) + { return BlockState.NeedMore; + } } } else if (match_available != 0) @@ -1410,7 +1466,9 @@ namespace SharpCompress.Compressor.Deflate strstart++; lookahead--; if (_codec.AvailableBytesOut == 0) + { return BlockState.NeedMore; + } } else { @@ -1433,15 +1491,15 @@ namespace SharpCompress.Compressor.Deflate if (_codec.AvailableBytesOut == 0) { if (flush == FlushType.Finish) + { return BlockState.FinishStarted; - else - return BlockState.NeedMore; + } + return BlockState.NeedMore; } return flush == FlushType.Finish ? BlockState.FinishDone : BlockState.BlockDone; } - internal int longest_match(int cur_match) { int chain_length = config.MaxChainLength; // max hash chain length @@ -1474,7 +1532,9 @@ namespace SharpCompress.Compressor.Deflate // Do not look for matches beyond the end of the input. This is necessary // to make deflate deterministic. if (niceLength > lookahead) + { niceLength = lookahead; + } do { @@ -1486,7 +1546,9 @@ namespace SharpCompress.Compressor.Deflate window[match + best_len - 1] != scan_end1 || window[match] != window[scan] || window[++match] != window[scan + 1]) + { continue; + } // The check at best_len-1 can be removed because it will be made // again later. (This heuristic is not always a win.) @@ -1500,16 +1562,17 @@ namespace SharpCompress.Compressor.Deflate // 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 - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) @@ -1517,27 +1580,25 @@ namespace SharpCompress.Compressor.Deflate match_start = cur_match; best_len = len; if (len >= niceLength) + { break; + } 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; + } return lookahead; } + private bool Rfc1950BytesEmitted; - private bool Rfc1950BytesEmitted = false; - private bool _WantRfc1950HeaderBytes = true; - - internal bool WantRfc1950HeaderBytes - { - get { return _WantRfc1950HeaderBytes; } - set { _WantRfc1950HeaderBytes = value; } - } - + internal bool WantRfc1950HeaderBytes { get; set; } = true; internal int Initialize(ZlibCodec codec, CompressionLevel level) { @@ -1563,10 +1624,14 @@ namespace SharpCompress.Compressor.Deflate // validation if (windowBits < 9 || windowBits > 15) + { throw new ZlibException("windowBits must be in the range 9..15."); + } if (memLevel < 1 || memLevel > MEM_LEVEL_MAX) + { throw new ZlibException(String.Format("memLevel must be in the range 1.. {0}", MEM_LEVEL_MAX)); + } _codec.dstate = this; @@ -1577,9 +1642,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]; @@ -1590,27 +1655,27 @@ 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. // The middle slice, of 32k, is used for distance codes. // The final 16k are length codes. - this.compressionLevel = level; - this.compressionStrategy = strategy; + compressionLevel = level; + compressionStrategy = strategy; Reset(); return ZlibConstants.Z_OK; } - internal void Reset() { _codec.TotalBytesIn = _codec.TotalBytesOut = 0; _codec.Message = null; + //strm.data_type = Z_UNKNOWN; pendingCount = 0; @@ -1621,30 +1686,30 @@ 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(); } - internal int End() { if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) { return ZlibConstants.Z_STREAM_ERROR; } + // Deallocate in reverse order of allocations: pending = null; head = null; prev = null; window = null; + // free // dstate=null; return status == BUSY_STATE ? ZlibConstants.Z_DATA_ERROR : ZlibConstants.Z_OK; } - private void SetDeflater() { switch (config.Flavor) @@ -1661,7 +1726,6 @@ namespace SharpCompress.Compressor.Deflate } } - internal int SetParams(CompressionLevel level, CompressionStrategy strategy) { int result = ZlibConstants.Z_OK; @@ -1688,19 +1752,22 @@ namespace SharpCompress.Compressor.Deflate return result; } - internal int SetDictionary(byte[] dictionary) { int length = dictionary.Length; int index = 0; if (dictionary == null || status != INIT_STATE) + { throw new ZlibException("Stream error."); + } _codec._Adler32 = Adler.Adler32(_codec._Adler32, dictionary, 0, dictionary.Length); if (length < MIN_MATCH) + { return ZlibConstants.Z_OK; + } if (length > w_size - MIN_LOOKAHEAD) { length = w_size - MIN_LOOKAHEAD; @@ -1721,12 +1788,11 @@ 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,48 +1803,56 @@ namespace SharpCompress.Compressor.Deflate { _codec.Message = _ErrorMessage[ZlibConstants.Z_NEED_DICT - (ZlibConstants.Z_STREAM_ERROR)]; throw new ZlibException(String.Format("Something is fishy. [{0}]", _codec.Message)); + //return ZlibConstants.Z_STREAM_ERROR; } if (_codec.AvailableBytesOut == 0) { _codec.Message = _ErrorMessage[ZlibConstants.Z_NEED_DICT - (ZlibConstants.Z_BUF_ERROR)]; throw new ZlibException("OutputBuffer is full (AvailableBytesOut == 0)"); + //return ZlibConstants.Z_BUF_ERROR; } 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) { ////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); } @@ -1804,7 +1878,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 @@ -1826,7 +1900,6 @@ namespace SharpCompress.Compressor.Deflate throw new ZlibException("status == FINISH_STATE && _codec.AvailableBytesIn != 0"); } - // Start a new block or continue the current one. if (_codec.AvailableBytesIn != 0 || lookahead != 0 || (flush != FlushType.None && status != FINISH_STATE)) { @@ -1843,6 +1916,7 @@ namespace SharpCompress.Compressor.Deflate last_flush = -1; // avoid BUF_ERROR next call, see above } return ZlibConstants.Z_OK; + // If flush != Z_NO_FLUSH && avail_out == 0, the next call // of deflate should use the same flush parameter to make sure // that the flush is complete. So we don't have to output an @@ -1861,13 +1935,16 @@ namespace SharpCompress.Compressor.Deflate { // FlushType.Full or FlushType.Sync _tr_stored_block(0, 0, false); + // For a full flush, this empty block will be recognized // as a special marker by inflate_sync(). if (flush == FlushType.Full) { // clear hash (forget the history) for (int i = 0; i < hash_size; i++) + { head[i] = 0; + } } } _codec.flush_pending(); @@ -1880,16 +1957,21 @@ namespace SharpCompress.Compressor.Deflate } if (flush != FlushType.Finish) + { return ZlibConstants.Z_OK; + } if (!WantRfc1950HeaderBytes || Rfc1950BytesEmitted) + { 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)); diff --git a/src/SharpCompress/Compressor/Deflate/DeflateStream.cs b/src/SharpCompress/Compressor/Deflate/DeflateStream.cs index ccf88b31..b4716a68 100644 --- a/src/SharpCompress/Compressor/Deflate/DeflateStream.cs +++ b/src/SharpCompress/Compressor/Deflate/DeflateStream.cs @@ -35,7 +35,6 @@ namespace SharpCompress.Compressor.Deflate private readonly ZlibBaseStream _baseStream; private bool _disposed; - public DeflateStream(Stream stream, CompressionMode mode, CompressionLevel level = CompressionLevel.Default, bool leaveOpen = false) @@ -55,7 +54,10 @@ namespace SharpCompress.Compressor.Deflate get { return (_baseStream._flushMode); } set { - if (_disposed) throw new ObjectDisposedException("DeflateStream"); + if (_disposed) + { + throw new ObjectDisposedException("DeflateStream"); + } _baseStream._flushMode = value; } } @@ -82,13 +84,20 @@ namespace SharpCompress.Compressor.Deflate get { return _baseStream._bufferSize; } set { - if (_disposed) throw new ObjectDisposedException("DeflateStream"); + if (_disposed) + { + throw new ObjectDisposedException("DeflateStream"); + } if (_baseStream._workingBuffer != null) + { throw new ZlibException("The working buffer is already set."); + } if (value < ZlibConstants.WorkingBufferSizeMin) + { throw new ZlibException( - String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, - ZlibConstants.WorkingBufferSizeMin)); + String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, + ZlibConstants.WorkingBufferSizeMin)); + } _baseStream._bufferSize = value; } } @@ -106,22 +115,19 @@ namespace SharpCompress.Compressor.Deflate get { return _baseStream.Strategy; } set { - if (_disposed) throw new ObjectDisposedException("DeflateStream"); + if (_disposed) + { + throw new ObjectDisposedException("DeflateStream"); + } _baseStream.Strategy = value; } } /// Returns the total number of bytes input so far. - public virtual long TotalIn - { - get { return _baseStream._z.TotalBytesIn; } - } + public virtual long TotalIn { get { return _baseStream._z.TotalBytesIn; } } /// Returns the total number of bytes output so far. - public virtual long TotalOut - { - get { return _baseStream._z.TotalBytesOut; } - } + public virtual long TotalOut { get { return _baseStream._z.TotalBytesOut; } } #endregion @@ -137,7 +143,10 @@ namespace SharpCompress.Compressor.Deflate { get { - if (_disposed) throw new ObjectDisposedException("DeflateStream"); + if (_disposed) + { + throw new ObjectDisposedException("DeflateStream"); + } return _baseStream._stream.CanRead; } } @@ -148,11 +157,7 @@ namespace SharpCompress.Compressor.Deflate /// /// Always returns false. /// - public override bool CanSeek - { - get { return false; } - } - + public override bool CanSeek { get { return false; } } /// /// Indicates whether the stream can be written. @@ -164,7 +169,10 @@ namespace SharpCompress.Compressor.Deflate { get { - if (_disposed) throw new ObjectDisposedException("DeflateStream"); + if (_disposed) + { + throw new ObjectDisposedException("DeflateStream"); + } return _baseStream._stream.CanWrite; } } @@ -172,10 +180,7 @@ namespace SharpCompress.Compressor.Deflate /// /// Reading this property always throws a . /// - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } /// /// The position of the stream pointer. @@ -193,9 +198,13 @@ namespace SharpCompress.Compressor.Deflate get { if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Writer) + { return _baseStream._z.TotalBytesOut; + } if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Reader) + { return _baseStream._z.TotalBytesIn; + } return 0; } set { throw new NotSupportedException(); } @@ -215,7 +224,9 @@ namespace SharpCompress.Compressor.Deflate if (!_disposed) { if (disposing && (_baseStream != null)) + { _baseStream.Dispose(); + } _disposed = true; } } @@ -230,7 +241,10 @@ namespace SharpCompress.Compressor.Deflate /// public override void Flush() { - if (_disposed) throw new ObjectDisposedException("DeflateStream"); + if (_disposed) + { + throw new ObjectDisposedException("DeflateStream"); + } _baseStream.Flush(); } @@ -262,11 +276,13 @@ namespace SharpCompress.Compressor.Deflate /// the number of bytes actually read public override int Read(byte[] buffer, int offset, int count) { - if (_disposed) throw new ObjectDisposedException("DeflateStream"); + if (_disposed) + { + throw new ObjectDisposedException("DeflateStream"); + } return _baseStream.Read(buffer, offset, count); } - /// /// Calling this method always throws a . /// @@ -318,7 +334,10 @@ namespace SharpCompress.Compressor.Deflate /// the number of bytes to write. public override void Write(byte[] buffer, int offset, int count) { - if (_disposed) throw new ObjectDisposedException("DeflateStream"); + if (_disposed) + { + throw new ObjectDisposedException("DeflateStream"); + } _baseStream.Write(buffer, offset, count); } diff --git a/src/SharpCompress/Compressor/Deflate/FlushType.cs b/src/SharpCompress/Compressor/Deflate/FlushType.cs index fd8d7b20..0595b248 100644 --- a/src/SharpCompress/Compressor/Deflate/FlushType.cs +++ b/src/SharpCompress/Compressor/Deflate/FlushType.cs @@ -39,6 +39,6 @@ Full, /// Signals the end of the compression/decompression stream. - Finish, + Finish } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Deflate/GZipStream.cs b/src/SharpCompress/Compressor/Deflate/GZipStream.cs index 97cf548a..e98d7713 100644 --- a/src/SharpCompress/Compressor/Deflate/GZipStream.cs +++ b/src/SharpCompress/Compressor/Deflate/GZipStream.cs @@ -41,7 +41,6 @@ namespace SharpCompress.Compressor.Deflate public DateTime? LastModified { get; set; } private string comment; - private int crc32; private string fileName; internal ZlibBaseStream BaseStream; @@ -49,7 +48,6 @@ namespace SharpCompress.Compressor.Deflate private bool firstReadDone; private int headerByteCount; - public GZipStream(Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { @@ -78,7 +76,9 @@ namespace SharpCompress.Compressor.Deflate set { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } BaseStream._flushMode = value; } } @@ -89,27 +89,26 @@ namespace SharpCompress.Compressor.Deflate set { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } if (BaseStream._workingBuffer != null) + { throw new ZlibException("The working buffer is already set."); + } if (value < ZlibConstants.WorkingBufferSizeMin) + { throw new ZlibException( - String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, - ZlibConstants.WorkingBufferSizeMin)); + String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, + ZlibConstants.WorkingBufferSizeMin)); + } BaseStream._bufferSize = value; } } + internal virtual long TotalIn { get { return BaseStream._z.TotalBytesIn; } } - internal virtual long TotalIn - { - get { return BaseStream._z.TotalBytesIn; } - } - - internal virtual long TotalOut - { - get { return BaseStream._z.TotalBytesOut; } - } + internal virtual long TotalOut { get { return BaseStream._z.TotalBytesOut; } } #endregion @@ -126,7 +125,9 @@ namespace SharpCompress.Compressor.Deflate get { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } return BaseStream._stream.CanRead; } } @@ -137,11 +138,7 @@ namespace SharpCompress.Compressor.Deflate /// /// Always returns false. /// - public override bool CanSeek - { - get { return false; } - } - + public override bool CanSeek { get { return false; } } /// /// Indicates whether the stream can be written. @@ -154,7 +151,9 @@ namespace SharpCompress.Compressor.Deflate get { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } return BaseStream._stream.CanWrite; } } @@ -162,10 +161,7 @@ namespace SharpCompress.Compressor.Deflate /// /// Reading this property always throws a . /// - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } /// /// The position of the stream pointer. @@ -183,9 +179,13 @@ namespace SharpCompress.Compressor.Deflate get { if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Writer) + { return BaseStream._z.TotalBytesOut + headerByteCount; + } if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Reader) + { return BaseStream._z.TotalBytesIn + BaseStream._gzipHeaderByteCount; + } return 0; } @@ -208,7 +208,7 @@ namespace SharpCompress.Compressor.Deflate if (disposing && (BaseStream != null)) { BaseStream.Dispose(); - crc32 = BaseStream.Crc32; + Crc32 = BaseStream.Crc32; } disposed = true; } @@ -225,7 +225,9 @@ namespace SharpCompress.Compressor.Deflate public override void Flush() { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } BaseStream.Flush(); } @@ -263,7 +265,9 @@ namespace SharpCompress.Compressor.Deflate public override int Read(byte[] buffer, int offset, int count) { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } int n = BaseStream.Read(buffer, offset, count); // Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n); @@ -278,7 +282,6 @@ namespace SharpCompress.Compressor.Deflate return n; } - /// /// Calling this method always throws a . /// @@ -324,7 +327,9 @@ namespace SharpCompress.Compressor.Deflate public override void Write(byte[] buffer, int offset, int count) { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Undefined) { //Console.WriteLine("GZipStream: First write"); @@ -350,7 +355,9 @@ namespace SharpCompress.Compressor.Deflate set { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } comment = value; } } @@ -361,16 +368,22 @@ namespace SharpCompress.Compressor.Deflate set { if (disposed) + { throw new ObjectDisposedException("GZipStream"); + } fileName = value; if (fileName == null) + { return; + } if (fileName.IndexOf("/") != -1) { fileName = fileName.Replace("/", "\\"); } if (fileName.EndsWith("\\")) + { throw new InvalidOperationException("Illegal filename"); + } var index = fileName.IndexOf("\\"); if (index != -1) @@ -390,11 +403,7 @@ namespace SharpCompress.Compressor.Deflate } } - public int Crc32 - { - get { return crc32; } - } - + public int Crc32 { get; private set; } private int EmitHeader() { @@ -407,6 +416,7 @@ namespace SharpCompress.Compressor.Deflate int bufferLength = 10 + cbLength + fnLength; var header = new byte[bufferLength]; int i = 0; + // ID header[i++] = 0x1F; header[i++] = 0x8B; @@ -415,23 +425,30 @@ namespace SharpCompress.Compressor.Deflate header[i++] = 8; byte flag = 0; if (Comment != null) + { flag ^= 0x10; + } if (FileName != null) + { flag ^= 0x8; + } // flag header[i++] = flag; // mtime if (!LastModified.HasValue) + { LastModified = DateTime.Now; + } TimeSpan delta = LastModified.Value - UnixEpoch; - var timet = (Int32) delta.TotalSeconds; + var timet = (Int32)delta.TotalSeconds; DataConverter.LittleEndian.PutBytes(header, i, timet); i += 4; // xflg header[i++] = 0; // this field is totally useless + // OS header[i++] = 0xFF; // 0xFF == unspecified diff --git a/src/SharpCompress/Compressor/Deflate/InfTree.cs b/src/SharpCompress/Compressor/Deflate/InfTree.cs index 8a304a4f..a455251c 100644 --- a/src/SharpCompress/Compressor/Deflate/InfTree.cs +++ b/src/SharpCompress/Compressor/Deflate/InfTree.cs @@ -83,148 +83,148 @@ namespace SharpCompress.Compressor.Deflate internal const int BMAX = 15; // maximum bit length of any code //UPGRADE_NOTE: Final was removed from the declaration of 'fixed_tl'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] fixed_tl = new[] - { - 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, - 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, - 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, - 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, - 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, - 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, - 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, - 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, - 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, - 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0 - , 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, - 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50 - , 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2 - , 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26 - , 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, - 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, - 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, - 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8 - , 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, - 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, - 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0 - , 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, - 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, - 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, - 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, - 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, - 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, - 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0 - , 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, - 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, - 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, - 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, - 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, - 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, - 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, - 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, - 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, - 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, - 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, - 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0 - , 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0 - , 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, - 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15 - , 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, - 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, - 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8 - , 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, - 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0 - , 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, - 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116 - , 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, - 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, - 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, - 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8 - , 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, - 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, - 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0 - , 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, - 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42 - , 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, - 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, - 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8 - , 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, - 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, - 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, - 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8 - , 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, - 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, - 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, - 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, - 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, - 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8 - , 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, - 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, - 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, - 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0 - , 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, - 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, - 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, - 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, - 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8 - , 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, - 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, - 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0 - , 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, - 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, - 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143 - , 0, 8, 79, 0, 9, 255 - }; + internal static readonly int[] fixed_tl = + { + 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, + 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, + 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, + 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, + 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, + 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, + 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, + 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, + 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, + 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0 + , 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, + 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50 + , 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2 + , 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26 + , 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, + 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, + 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, + 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8 + , 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, + 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, + 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0 + , 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, + 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, + 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, + 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, + 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, + 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, + 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0 + , 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, + 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, + 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, + 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, + 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, + 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, + 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, + 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, + 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, + 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, + 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, + 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0 + , 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0 + , 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, + 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15 + , 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, + 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, + 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8 + , 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, + 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0 + , 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, + 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116 + , 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, + 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, + 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, + 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8 + , 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, + 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, + 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0 + , 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, + 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42 + , 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, + 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, + 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8 + , 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, + 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, + 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, + 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8 + , 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, + 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, + 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, + 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, + 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, + 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8 + , 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, + 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, + 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, + 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0 + , 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, + 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, + 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, + 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, + 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8 + , 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, + 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, + 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0 + , 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, + 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, + 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143 + , 0, 8, 79, 0, 9, 255 + }; //UPGRADE_NOTE: Final was removed from the declaration of 'fixed_td'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - 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 - , 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 - }; + internal static readonly int[] fixed_td = + { + 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 + , 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 + }; // Tables for deflate from PKZIP's appnote.txt. //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 - , 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 - }; + internal static readonly int[] cplens = + { + 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 + }; // see note #13 above about 258 //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 - , 4, 5, 5, 5, 5, 0, 112, 112 - }; + internal static readonly int[] cplext = + { + 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, - 24577 - }; + internal static readonly int[] cpdist = + { + 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 - , - 10, 10, 11, 11, 12, 12, 13, 13 - }; + internal static readonly int[] cpdext = + { + 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 + }; // If BMAX needs to be larger than 16, then h and x[] should be uLong. internal int[] c; // bit length count table @@ -268,7 +268,8 @@ namespace SharpCompress.Compressor.Deflate c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX - } while (i != 0); + } + while (i != 0); if (c[0] == n) { @@ -281,8 +282,12 @@ namespace SharpCompress.Compressor.Deflate // Find minimum and maximum length, bound *m by those l = m[0]; for (j = 1; j <= BMAX; j++) + { if (c[j] != 0) + { break; + } + } k = j; // minimum code length if (l < j) { @@ -291,7 +296,9 @@ namespace SharpCompress.Compressor.Deflate for (i = BMAX; i != 0; i--) { if (c[i] != 0) + { break; + } } g = i; // maximum code length if (l > i) @@ -336,7 +343,8 @@ namespace SharpCompress.Compressor.Deflate v[x[j]++] = i; } p++; - } while (++i < n); + } + while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries @@ -360,6 +368,7 @@ namespace SharpCompress.Compressor.Deflate { h++; w += l; // previous table always l bits + // compute minimum size table less than or equal to l bits z = g - w; z = (z > l) ? l : z; // table size upper limit @@ -375,7 +384,9 @@ namespace SharpCompress.Compressor.Deflate { // try smaller tables up to z bits if ((f <<= 1) <= c[++xp]) + { break; // enough codes to use up j bits + } f -= c[xp]; // else deduct codes from patterns } } @@ -395,11 +406,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 { @@ -408,19 +419,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]; } @@ -428,7 +439,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 @@ -448,6 +459,7 @@ namespace SharpCompress.Compressor.Deflate } } } + // Return Z_BUF_ERROR if we were given an incomplete table return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; } @@ -551,9 +563,11 @@ namespace SharpCompress.Compressor.Deflate r[0] = 0; r[1] = 0; r[2] = 0; + // for(int i=0; i> 1) + switch ((uint)t >> 1) { case 0: // stored b >>= 3; @@ -309,16 +309,22 @@ namespace SharpCompress.Compressor.Deflate t = left; if (t > n) + { t = n; + } if (t > m) + { t = m; + } Array.Copy(_codec.InputBuffer, p, window, q, t); p += t; n -= t; q += t; m -= t; if ((left -= t) != 0) + { break; + } mode = last != 0 ? InflateBlockMode.DRY : InflateBlockMode.TYPE; break; @@ -369,6 +375,7 @@ namespace SharpCompress.Compressor.Deflate else { Array.Clear(blens, 0, t); + // for (int i = 0; i < t; i++) // { // blens[i] = 0; @@ -378,7 +385,6 @@ namespace SharpCompress.Compressor.Deflate b >>= 14; k -= 14; - index = 0; mode = InflateBlockMode.BTREE; goto case InflateBlockMode.BTREE; @@ -478,8 +484,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) { @@ -545,41 +551,42 @@ namespace SharpCompress.Compressor.Deflate do { blens[i++] = c; - } while (--j != 0); + } + while (--j != 0); index = i; } } tb[0] = -1; + { + var bl = new[] {9}; // must be <= 9 for lookahead assumptions + var bd = new[] {6}; // must be <= 9 for lookahead assumptions + var tl = new int[1]; + var td = new int[1]; + + t = table; + t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, + td, hufts, _codec); + + if (t != ZlibConstants.Z_OK) { - var bl = new[] {9}; // must be <= 9 for lookahead assumptions - var bd = new[] {6}; // must be <= 9 for lookahead assumptions - var tl = new int[1]; - var td = new int[1]; - - t = table; - t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, - td, hufts, _codec); - - if (t != ZlibConstants.Z_OK) + if (t == ZlibConstants.Z_DATA_ERROR) { - if (t == ZlibConstants.Z_DATA_ERROR) - { - blens = null; - mode = InflateBlockMode.BAD; - } - r = t; - - bitb = b; - bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - writeAt = q; - return Flush(r); + blens = null; + mode = InflateBlockMode.BAD; } - codes.Init(bl[0], bd[0], hufts, tl[0], hufts, td[0]); + r = t; + + bitb = b; + bitk = k; + _codec.AvailableBytesIn = n; + _codec.TotalBytesIn += p - _codec.NextIn; + _codec.NextIn = p; + writeAt = q; + return Flush(r); } + codes.Init(bl[0], bd[0], hufts, tl[0], hufts, td[0]); + } mode = InflateBlockMode.CODES; goto case InflateBlockMode.CODES; @@ -652,7 +659,6 @@ namespace SharpCompress.Compressor.Deflate writeAt = q; return Flush(r); - default: r = ZlibConstants.Z_STREAM_ERROR; @@ -667,7 +673,6 @@ namespace SharpCompress.Compressor.Deflate } } - internal void Free() { Reset(); @@ -710,15 +715,21 @@ namespace SharpCompress.Compressor.Deflate if (nBytes == 0) { if (r == ZlibConstants.Z_BUF_ERROR) + { r = ZlibConstants.Z_OK; + } return r; } if (nBytes > _codec.AvailableBytesOut) + { nBytes = _codec.AvailableBytesOut; + } if (nBytes != 0 && r == ZlibConstants.Z_BUF_ERROR) + { r = ZlibConstants.Z_OK; + } // update counters _codec.AvailableBytesOut -= nBytes; @@ -726,7 +737,9 @@ namespace SharpCompress.Compressor.Deflate // update check information if (checkfn != null) + { _codec._Adler32 = check = Adler.Adler32(check, window, readAt, nBytes); + } // copy as far as end of window Array.Copy(window, readAt, _codec.OutputBuffer, _codec.NextOut, nBytes); @@ -739,9 +752,14 @@ namespace SharpCompress.Compressor.Deflate // wrap pointers readAt = 0; if (writeAt == end) + { writeAt = 0; + } + } + else + { + pass++; } - else pass++; } // done @@ -761,26 +779,24 @@ namespace SharpCompress.Compressor.Deflate CODES = 6, // processing fixed or dynamic block DRY = 7, // output remaining window bytes DONE = 8, // finished last block, done - BAD = 9, // ot a data error--stuck here + BAD = 9 // ot a data error--stuck here } #endregion } - internal static class InternalInflateConstants { // And'ing with mask[n] masks the lower n bits - internal static readonly int[] InflateMask = new[] - { - 0x00000000, 0x00000001, 0x00000003, 0x00000007, - 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, - 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, - 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff - }; + internal static readonly int[] InflateMask = + { + 0x00000000, 0x00000001, 0x00000003, 0x00000007, + 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, + 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, + 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff + }; } - internal sealed class InflateCodes { // waiting for "i:"=input, @@ -817,8 +833,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 +870,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) { @@ -892,14 +908,18 @@ namespace SharpCompress.Compressor.Deflate while (k < j) { if (n != 0) + { r = ZlibConstants.Z_OK; + } else { // Handling missing trailing bit(s) - var tmp_tindex = (tree_index + (b & InternalInflateConstants.InflateMask[k]))*3; + var tmp_tindex = (tree_index + (b & InternalInflateConstants.InflateMask[k])) * 3; if (k >= tree[tmp_tindex + 1]) + { break; - + } + blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; @@ -913,7 +933,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]); @@ -939,7 +959,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) @@ -960,14 +980,15 @@ namespace SharpCompress.Compressor.Deflate blocks.writeAt = q; return blocks.Flush(r); - case LENEXT: // i: getting length extra (have base) j = bitsToGet; while (k < j) { if (n != 0) + { r = ZlibConstants.Z_OK; + } else { blocks.bitb = b; @@ -1000,13 +1021,17 @@ namespace SharpCompress.Compressor.Deflate while (k < j) { if (n != 0) + { r = ZlibConstants.Z_OK; + } else { // Handling missing trailing bit(s) - var tmp_tindex = (tree_index + (b & InternalInflateConstants.InflateMask[k]))*3; + var tmp_tindex = (tree_index + (b & InternalInflateConstants.InflateMask[k])) * 3; if (k >= tree[tmp_tindex + 1]) + { break; + } blocks.bitb = b; blocks.bitk = k; @@ -1021,7 +1046,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]; @@ -1039,7 +1064,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 @@ -1054,14 +1079,15 @@ namespace SharpCompress.Compressor.Deflate blocks.writeAt = q; return blocks.Flush(r); - case DISTEXT: // i: getting distance extra j = bitsToGet; while (k < j) { if (n != 0) + { r = ZlibConstants.Z_OK; + } else { blocks.bitb = b; @@ -1131,7 +1157,9 @@ namespace SharpCompress.Compressor.Deflate m--; if (f == blocks.end) + { f = 0; + } len--; } mode = START; @@ -1171,7 +1199,7 @@ namespace SharpCompress.Compressor.Deflate } r = ZlibConstants.Z_OK; - blocks.window[q++] = (byte) lit; + blocks.window[q++] = (byte)lit; m--; mode = START; @@ -1240,7 +1268,6 @@ namespace SharpCompress.Compressor.Deflate } } - // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ @@ -1295,13 +1322,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; } @@ -1330,7 +1357,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 @@ -1383,7 +1410,8 @@ namespace SharpCompress.Compressor.Deflate do { r += s.end; // force pointer in window - } while (r < 0); // covers invalid distances + } + while (r < 0); // covers invalid distances e = s.end - r; if (c > e) { @@ -1394,7 +1422,8 @@ namespace SharpCompress.Compressor.Deflate do { s.window[q++] = s.window[r++]; - } while (--e != 0); + } + while (--e != 0); } else { @@ -1413,7 +1442,8 @@ namespace SharpCompress.Compressor.Deflate do { s.window[q++] = s.window[r++]; - } while (--c != 0); + } + while (--c != 0); } else { @@ -1424,11 +1454,11 @@ namespace SharpCompress.Compressor.Deflate } break; } - else if ((e & 64) == 0) + if ((e & 64) == 0) { 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 @@ -1450,7 +1480,8 @@ namespace SharpCompress.Compressor.Deflate return ZlibConstants.Z_DATA_ERROR; } - } while (true); + } + while (true); break; } @@ -1458,12 +1489,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; } @@ -1504,8 +1535,10 @@ namespace SharpCompress.Compressor.Deflate return ZlibConstants.Z_DATA_ERROR; } - } while (true); - } while (m >= 258 && n >= 10); + } + while (true); + } + while (m >= 258 && n >= 10); // not enough input or output--restore pointers and return c = z.AvailableBytesIn - n; @@ -1525,17 +1558,15 @@ namespace SharpCompress.Compressor.Deflate } } - internal sealed class InflateManager { // preset dictionary flag in zlib header 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 = {0, 0, 0xff, 0xff}; internal ZlibCodec _codec; // pointer back to this zlib stream - private bool _handleRfc1950HeaderBytes = true; internal InflateBlocks blocks; // current inflate_blocks state // mode dependent information @@ -1560,14 +1591,10 @@ namespace SharpCompress.Compressor.Deflate public InflateManager(bool expectRfc1950HeaderBytes) { - _handleRfc1950HeaderBytes = expectRfc1950HeaderBytes; + HandleRfc1950HeaderBytes = expectRfc1950HeaderBytes; } - internal bool HandleRfc1950HeaderBytes - { - get { return _handleRfc1950HeaderBytes; } - set { _handleRfc1950HeaderBytes = value; } - } + internal bool HandleRfc1950HeaderBytes { get; set; } = true; internal int Reset() { @@ -1581,7 +1608,9 @@ namespace SharpCompress.Compressor.Deflate internal int End() { if (blocks != null) + { blocks.Free(); + } blocks = null; return ZlibConstants.Z_OK; } @@ -1619,13 +1648,14 @@ namespace SharpCompress.Compressor.Deflate return ZlibConstants.Z_OK; } - internal int Inflate(FlushType flush) { int b; if (_codec.InputBuffer == null) + { throw new ZlibException("InputBuffer is null. "); + } // int f = (flush == FlushType.Finish) // ? ZlibConstants.Z_BUF_ERROR @@ -1640,7 +1670,10 @@ namespace SharpCompress.Compressor.Deflate switch (mode) { case InflateManagerMode.METHOD: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; @@ -1661,15 +1694,17 @@ namespace SharpCompress.Compressor.Deflate mode = InflateManagerMode.FLAG; break; - case InflateManagerMode.FLAG: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } r = f; _codec.AvailableBytesIn--; _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"; @@ -1683,52 +1718,61 @@ namespace SharpCompress.Compressor.Deflate break; case InflateManagerMode.DICT4: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } 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; case InflateManagerMode.DICT3: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } 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; case InflateManagerMode.DICT2: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } 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; - case InflateManagerMode.DICT1: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } 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; - case InflateManagerMode.DICT0: mode = InflateManagerMode.BAD; _codec.Message = "need dictionary"; marker = 0; // can try inflateSync return ZlibConstants.Z_STREAM_ERROR; - case InflateManagerMode.BLOCKS: r = blocks.Process(r); if (r == ZlibConstants.Z_DATA_ERROR) @@ -1738,10 +1782,15 @@ namespace SharpCompress.Compressor.Deflate break; } - if (r == ZlibConstants.Z_OK) r = f; + if (r == ZlibConstants.Z_OK) + { + r = f; + } if (r != ZlibConstants.Z_STREAM_END) + { return r; + } r = f; computedCheck = blocks.Reset(); @@ -1754,38 +1803,50 @@ namespace SharpCompress.Compressor.Deflate break; case InflateManagerMode.CHECK4: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } 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; case InflateManagerMode.CHECK3: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } 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; case InflateManagerMode.CHECK2: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } 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; case InflateManagerMode.CHECK1: - if (_codec.AvailableBytesIn == 0) return r; + if (_codec.AvailableBytesIn == 0) + { + return r; + } 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; @@ -1808,13 +1869,14 @@ namespace SharpCompress.Compressor.Deflate } } - internal int SetDictionary(byte[] dictionary) { int index = 0; int length = dictionary.Length; if (mode != InflateManagerMode.DICT0) + { throw new ZlibException("Stream error."); + } if (Adler.Adler32(1, dictionary, 0, dictionary.Length) != _codec._Adler32) { @@ -1833,7 +1895,6 @@ namespace SharpCompress.Compressor.Deflate return ZlibConstants.Z_OK; } - internal int Sync() { int n; // number of bytes to look at @@ -1848,7 +1909,9 @@ namespace SharpCompress.Compressor.Deflate marker = 0; } if ((n = _codec.AvailableBytesIn) == 0) + { return ZlibConstants.Z_BUF_ERROR; + } p = _codec.NextIn; m = marker; @@ -1891,7 +1954,6 @@ namespace SharpCompress.Compressor.Deflate return ZlibConstants.Z_OK; } - // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP // implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH @@ -1920,7 +1982,7 @@ namespace SharpCompress.Compressor.Deflate CHECK2 = 10, // two check bytes to go CHECK1 = 11, // one check byte to go DONE = 12, // finished check, done - BAD = 13, // got an error--stay here + BAD = 13 // got an error--stay here } #endregion diff --git a/src/SharpCompress/Compressor/Deflate/Tree.cs b/src/SharpCompress/Compressor/Deflate/Tree.cs index fd9e27f0..c92f1269 100644 --- a/src/SharpCompress/Compressor/Deflate/Tree.cs +++ b/src/SharpCompress/Compressor/Deflate/Tree.cs @@ -71,17 +71,15 @@ 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 static readonly sbyte[] bl_order = new sbyte[] - { - 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, - 14, - 1, 15 - }; + internal const int Buf_size = 8 * 2; + private static readonly int HEAP_SIZE = (2 * InternalConstants.L_CODES + 1); + internal static readonly sbyte[] bl_order = + { + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, + 14, + 1, 15 + }; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit @@ -90,123 +88,120 @@ namespace SharpCompress.Compressor.Deflate // see definition of array dist_code below //internal const int DIST_CODE_LEN = 512; - private static readonly sbyte[] _dist_code = new sbyte[] - { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, - 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, - 10, 10, - 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, - 11, 11, - 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 12, - 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 12, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, - 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, - 21, 21, - 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, - 23, 23, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, - 24, 24, - 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, - 25, 25, - 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, - 26, 26, - 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, - 26, 26, - 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, - 27, 27, - 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, - 27, 27, - 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, - 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, - 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, - 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29 - }; + private static readonly sbyte[] _dist_code = + { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, + 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 11, 11, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, + 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, + 21, 21, + 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, + 23, 23, + 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, + 24, 24, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, + 25, 25, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 27, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29 + }; - internal static readonly sbyte[] LengthCode = new sbyte[] - { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, - 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15 - , 15, 15, - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17 - , 17, 17, - 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19 - , 19, 19, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 - , 20, 20, - 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21 - , 21, 21, - 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22 - , 22, 22, - 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23 - , 23, 23, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 - , 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 - , 24, 24, - 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25 - , 25, 25, - 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25 - , 25, 25, - 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26 - , 26, 26, - 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26 - , 26, 26, - 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27 - , 27, 27, - 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27 - , 27, 28 - }; + internal static readonly sbyte[] LengthCode = + { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, + 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15 + , 15, 15, + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17 + , 17, 17, + 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19 + , 19, 19, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 + , 20, 20, + 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21 + , 21, 21, + 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22 + , 22, 22, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23 + , 23, 23, + 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 + , 24, 24, + 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 + , 24, 24, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25 + , 25, 25, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25 + , 25, 25, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26 + , 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26 + , 26, 26, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27 + , 27, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27 + , 27, 28 + }; + internal static readonly int[] LengthBase = + { + 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, 0 + }; - internal static readonly int[] LengthBase = new[] - { - 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, 0 - }; - - - internal static readonly int[] DistanceBase = new[] - { - 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 - }; - + internal static readonly int[] DistanceBase = + { + 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 + }; internal short[] dyn_tree; // the dynamic tree internal int max_code; // largest code with non zero frequency @@ -248,38 +243,49 @@ namespace SharpCompress.Compressor.Deflate int overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= InternalConstants.MAX_BITS; bits++) + { s.bl_count[bits] = 0; + } // 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) + { continue; // not a leaf node + } s.bl_count[bits]++; 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; + } // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: @@ -287,14 +293,18 @@ namespace SharpCompress.Compressor.Deflate { bits = max_length - 1; 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] overflow -= 2; - } while (overflow > 0); + } + while (overflow > 0); for (bits = max_length; bits != 0; bits--) { @@ -303,11 +313,13 @@ namespace SharpCompress.Compressor.Deflate { m = s.heap[--h]; if (m > max_code) - continue; - 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; + continue; + } + 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; } n--; } @@ -337,14 +349,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; } } @@ -355,11 +367,14 @@ 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; @@ -367,8 +382,10 @@ 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 // frequent nodes. @@ -386,14 +403,15 @@ 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++; s.pqdownheap(tree, 1); - } while (s.heap_len >= 2); + } + while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1]; @@ -422,10 +440,12 @@ namespace SharpCompress.Compressor.Deflate // The distribution counts are first used to generate the code values // without bit reversal. 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 // must be all ones. @@ -435,11 +455,14 @@ 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))); } } @@ -454,7 +477,8 @@ namespace SharpCompress.Compressor.Deflate res |= code & 1; code >>= 1; //SharedUtils.URShift(code, 1); res <<= 1; - } while (--len > 0); + } + while (--len > 0); return res >> 1; } } diff --git a/src/SharpCompress/Compressor/Deflate/Zlib.cs b/src/SharpCompress/Compressor/Deflate/Zlib.cs index 57cd0f7a..143b39b5 100644 --- a/src/SharpCompress/Compressor/Deflate/Zlib.cs +++ b/src/SharpCompress/Compressor/Deflate/Zlib.cs @@ -62,6 +62,8 @@ // // ----------------------------------------------------------------------- +using System; +using System.IO; namespace SharpCompress.Compressor.Deflate { @@ -141,7 +143,7 @@ namespace SharpCompress.Compressor.Deflate /// /// A synonym for BestCompression. /// - Level9 = 9, + Level9 = 9 } /// @@ -169,21 +171,19 @@ namespace SharpCompress.Compressor.Deflate /// Using HuffmanOnly will force the compressor to do Huffman encoding only, with no /// string matching. /// - HuffmanOnly = 2, + HuffmanOnly = 2 } - /// /// A general purpose exception class for exceptions in the Zlib library. /// - public class ZlibException : System.Exception + public class ZlibException : Exception { /// /// The ZlibException class captures exception information generated /// by the Zlib library. /// public ZlibException() - : base() { } @@ -191,13 +191,12 @@ namespace SharpCompress.Compressor.Deflate /// This ctor collects a message attached to the exception. /// /// - public ZlibException(System.String s) + public ZlibException(String s) : base(s) { } } - internal class SharedUtils { /// @@ -208,16 +207,17 @@ 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); @@ -239,19 +239,27 @@ namespace SharpCompress.Compressor.Deflate /// count depending on the data available in the source TextReader. Returns -1 /// if the end of the stream is reached. /// - public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) + public static Int32 ReadInput(TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target - if (target.Length == 0) return 0; + if (target.Length == 0) + { + return 0; + } char[] charArray = new char[target.Length]; int bytesRead = sourceTextReader.Read(charArray, start, count); // Returns -1 if EOF - if (bytesRead == 0) return -1; + 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; } @@ -281,94 +289,92 @@ namespace SharpCompress.Compressor.Deflate 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 = + { + 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 = + { + 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 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; internal static readonly StaticTree Literals; internal static readonly StaticTree Distances; @@ -400,7 +406,6 @@ namespace SharpCompress.Compressor.Deflate } } - /// /// Computes an Adler-32 checksum. /// @@ -414,16 +419,19 @@ namespace SharpCompress.Compressor.Deflate { // largest prime smaller than 65536 private static readonly int BASE = 65521; + // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 private static readonly int NMAX = 5552; 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) { @@ -472,12 +480,13 @@ 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/src/SharpCompress/Compressor/Deflate/ZlibBaseStream.cs b/src/SharpCompress/Compressor/Deflate/ZlibBaseStream.cs index 00e23224..0241f7c3 100644 --- a/src/SharpCompress/Compressor/Deflate/ZlibBaseStream.cs +++ b/src/SharpCompress/Compressor/Deflate/ZlibBaseStream.cs @@ -25,6 +25,8 @@ // ------------------------------------------------------------------ using System; +using System.Collections.Generic; +using System.IO; using SharpCompress.Common; using SharpCompress.Common.Tar.Headers; using SharpCompress.Converter; @@ -38,9 +40,9 @@ namespace SharpCompress.Compressor.Deflate GZIP = 1952 } - internal class ZlibBaseStream : System.IO.Stream + internal class ZlibBaseStream : Stream { - protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec(); + protected internal ZlibCodec _z; // deferred init... new ZlibCodec(); protected internal StreamMode _streamMode = StreamMode.Undefined; protected internal FlushType _flushMode; @@ -52,11 +54,11 @@ namespace SharpCompress.Compressor.Deflate protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault; protected internal byte[] _buf1 = new byte[1]; - protected internal System.IO.Stream _stream; + protected internal Stream _stream; protected internal CompressionStrategy Strategy = CompressionStrategy.Default; // workitem 7159 - private CRC32 crc; + private readonly CRC32 crc; protected internal string _GzipFileName; protected internal string _GzipComment; protected internal DateTime _GzipMtime; @@ -67,25 +69,28 @@ namespace SharpCompress.Compressor.Deflate get { if (crc == null) + { return 0; + } return crc.Crc32Result; } } - public ZlibBaseStream(System.IO.Stream stream, + public ZlibBaseStream(Stream stream, CompressionMode compressionMode, CompressionLevel level, ZlibStreamFlavor flavor, bool leaveOpen) - : base() { - this._flushMode = FlushType.None; + _flushMode = FlushType.None; + //this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT]; - this._stream = stream; - this._leaveOpen = leaveOpen; - this._compressionMode = compressionMode; - this._flavor = flavor; - this._level = level; + _stream = stream; + _leaveOpen = leaveOpen; + _compressionMode = compressionMode; + _flavor = flavor; + _level = level; + // workitem 7159 if (flavor == ZlibStreamFlavor.GZIP) { @@ -93,11 +98,7 @@ namespace SharpCompress.Compressor.Deflate } } - - protected internal bool _wantCompress - { - get { return (this._compressionMode == CompressionMode.Compress); } - } + protected internal bool _wantCompress { get { return (_compressionMode == CompressionMode.Compress); } } private ZlibCodec z { @@ -105,48 +106,56 @@ namespace SharpCompress.Compressor.Deflate { if (_z == null) { - bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB); + bool wantRfc1950Header = (_flavor == ZlibStreamFlavor.ZLIB); _z = new ZlibCodec(); - if (this._compressionMode == CompressionMode.Decompress) + if (_compressionMode == CompressionMode.Decompress) { _z.InitializeInflate(wantRfc1950Header); } else { _z.Strategy = Strategy; - _z.InitializeDeflate(this._level, wantRfc1950Header); + _z.InitializeDeflate(_level, wantRfc1950Header); } } return _z; } } - private byte[] workingBuffer { get { if (_workingBuffer == null) + { _workingBuffer = new byte[_bufferSize]; + } return _workingBuffer; } } - - public override void Write(System.Byte[] buffer, int offset, int count) + public override void Write(Byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (crc != null) + { crc.SlurpBlock(buffer, offset, count); + } if (_streamMode == StreamMode.Undefined) + { _streamMode = StreamMode.Writer; + } else if (_streamMode != StreamMode.Writer) + { throw new ZlibException("Cannot Write after Reading."); + } if (count == 0) + { return; + } // first reference of z property will initialize the private var _z z.InputBuffer = buffer; @@ -162,7 +171,9 @@ namespace SharpCompress.Compressor.Deflate ? _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); + } //if (_workingBuffer.Length - _z.AvailableBytesOut > 0) _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); @@ -171,15 +182,19 @@ 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; + } if (_streamMode == StreamMode.Writer) { @@ -197,9 +212,10 @@ namespace SharpCompress.Compressor.Deflate { string verb = (_wantCompress ? "de" : "in") + "flating"; if (_z.Message == null) + { throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc)); - else - throw new ZlibException(verb + ": " + _z.Message); + } + throw new ZlibException(verb + ": " + _z.Message); } if (_workingBuffer.Length - _z.AvailableBytesOut > 0) @@ -208,10 +224,14 @@ namespace SharpCompress.Compressor.Deflate } done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; + // 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(); @@ -232,6 +252,7 @@ namespace SharpCompress.Compressor.Deflate } } } + // workitem 7159 else if (_streamMode == StreamMode.Reader) { @@ -241,7 +262,9 @@ namespace SharpCompress.Compressor.Deflate { // workitem 8501: handle edge case (decompress empty stream) if (_z.TotalBytesOut == 0L) + { return; + } // Read and potentially verify the GZIP trailer: CRC32 and size mod 2^32 byte[] trailer = new byte[8]; @@ -258,8 +281,8 @@ namespace SharpCompress.Compressor.Deflate if (bytesNeeded != bytesRead) { throw new ZlibException(String.Format( - "Protocol error. AvailableBytesIn={0}, expected 8", - _z.AvailableBytesIn + bytesRead)); + "Protocol error. AvailableBytesIn={0}, expected 8", + _z.AvailableBytesIn + bytesRead)); } } else @@ -267,21 +290,24 @@ namespace SharpCompress.Compressor.Deflate Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length); } - Int32 crc32_expected = DataConverter.LittleEndian.GetInt32(trailer, 0); Int32 crc32_actual = crc.Crc32Result; Int32 isize_expected = DataConverter.LittleEndian.GetInt32(trailer, 4); 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)); + 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)); + String.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isize_actual, + isize_expected)); + } } else { @@ -291,11 +317,12 @@ namespace SharpCompress.Compressor.Deflate } } - private void end() { if (z == null) + { return; + } if (_wantCompress) { _z.EndDeflate(); @@ -318,7 +345,9 @@ namespace SharpCompress.Compressor.Deflate if (disposing) { if (_stream == null) + { return; + } try { finish(); @@ -327,7 +356,9 @@ namespace SharpCompress.Compressor.Deflate { end(); if (!_leaveOpen) + { _stream.Dispose(); + } _stream = null; } } @@ -338,18 +369,18 @@ namespace SharpCompress.Compressor.Deflate _stream.Flush(); } - public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) + public override Int64 Seek(Int64 offset, SeekOrigin origin) { throw new NotSupportedException(); + //_outStream.Seek(offset, origin); } - public override void SetLength(System.Int64 value) + public override void SetLength(Int64 value) { _stream.SetLength(value); } - #if NOT public int Read() { @@ -362,49 +393,58 @@ namespace SharpCompress.Compressor.Deflate } #endif - private bool nomoreinput = false; + private bool nomoreinput; private bool isDisposed; - private string ReadZeroTerminatedString() { - var list = new System.Collections.Generic.List(); + var list = new List(); bool done = false; do { // workitem 7740 int n = _stream.Read(_buf1, 0, 1); if (n != 1) + { throw new ZlibException("Unexpected EOF reading GZIP header."); + } + if (_buf1[0] == 0) + { + done = true; + } else { - if (_buf1[0] == 0) - done = true; - else - list.Add(_buf1[0]); + list.Add(_buf1[0]); } - } while (!done); + } + while (!done); byte[] a = list.ToArray(); return ArchiveEncoding.Default.GetString(a, 0, a.Length); } - private int _ReadAndValidateGzipHeader() { int totalBytesRead = 0; + // read the header on the first read byte[] header = new byte[10]; int n = _stream.Read(header, 0, header.Length); // workitem 8501: handle edge case (decompress empty stream) if (n == 0) + { return 0; + } if (n != 10) + { throw new ZlibException("Not a valid GZIP stream."); + } if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) + { throw new ZlibException("Bad GZIP header."); + } Int32 timet = DataConverter.LittleEndian.GetInt32(header, 4); _GzipMtime = TarHeader.Epoch.AddSeconds(timet); @@ -419,21 +459,28 @@ namespace SharpCompress.Compressor.Deflate byte[] extra = new byte[extraLength]; n = _stream.Read(extra, 0, extra.Length); if (n != extraLength) + { throw new ZlibException("Unexpected end-of-file reading GZIP header."); + } totalBytesRead += n; } if ((header[3] & 0x08) == 0x08) + { _GzipFileName = ReadZeroTerminatedString(); + } if ((header[3] & 0x10) == 0x010) + { _GzipComment = ReadZeroTerminatedString(); + } if ((header[3] & 0x02) == 0x02) + { Read(_buf1, 0, 1); // CRC16, ignore + } return totalBytesRead; } - - public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) + public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, @@ -443,37 +490,58 @@ namespace SharpCompress.Compressor.Deflate if (_streamMode == StreamMode.Undefined) { - if (!this._stream.CanRead) + if (!_stream.CanRead) + { throw new ZlibException("The stream is not readable."); + } + // for the first read, set up some controls. _streamMode = StreamMode.Reader; + // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); + // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) + { return 0; + } } } if (_streamMode != StreamMode.Reader) + { throw new ZlibException("Cannot Read after Writing."); + } if (count == 0) + { return 0; + } 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"); + } if ((offset + count) > buffer.GetLength(0)) + { throw new ArgumentOutOfRangeException("count"); + } int rc = 0; @@ -496,26 +564,34 @@ namespace SharpCompress.Compressor.Deflate _z.NextIn = 0; _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); 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)); + } 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 > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); - // workitem 8557 // is there more room in output? if (_z.AvailableBytesOut > 0) @@ -536,53 +612,39 @@ namespace SharpCompress.Compressor.Deflate rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) + { throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); + } } } } - rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) + { crc.SlurpBlock(buffer, offset, rc); + } return rc; } + public override Boolean CanRead { get { return _stream.CanRead; } } - public override System.Boolean CanRead - { - get { return this._stream.CanRead; } - } + public override Boolean CanSeek { get { return _stream.CanSeek; } } - public override System.Boolean CanSeek - { - get { return this._stream.CanSeek; } - } + public override Boolean CanWrite { get { return _stream.CanWrite; } } - public override System.Boolean CanWrite - { - get { return this._stream.CanWrite; } - } + public override Int64 Length { get { return _stream.Length; } } - public override System.Int64 Length - { - get { return _stream.Length; } - } - - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } internal enum StreamMode { Writer, Reader, - Undefined, + Undefined } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Deflate/ZlibCodec.cs b/src/SharpCompress/Compressor/Deflate/ZlibCodec.cs index b559838d..3699b138 100644 --- a/src/SharpCompress/Compressor/Deflate/ZlibCodec.cs +++ b/src/SharpCompress/Compressor/Deflate/ZlibCodec.cs @@ -131,7 +131,7 @@ namespace SharpCompress.Compressor.Deflate /// /// used for diagnostics, when something goes wrong! /// - public System.String Message; + public String Message; internal DeflateManager dstate; internal InflateManager istate; @@ -169,15 +169,10 @@ namespace SharpCompress.Compressor.Deflate /// public CompressionStrategy Strategy = CompressionStrategy.Default; - /// /// 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; } } /// /// Create a ZlibCodec. @@ -202,14 +197,23 @@ namespace SharpCompress.Compressor.Deflate if (mode == CompressionMode.Compress) { int rc = InitializeDeflate(); - if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate."); + if (rc != ZlibConstants.Z_OK) + { + throw new ZlibException("Cannot initialize for deflate."); + } } else if (mode == CompressionMode.Decompress) { int rc = InitializeInflate(); - if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate."); + if (rc != ZlibConstants.Z_OK) + { + throw new ZlibException("Cannot initialize for inflate."); + } + } + else + { + throw new ZlibException("Invalid ZlibStreamFlavor."); } - else throw new ZlibException("Invalid ZlibStreamFlavor."); } /// @@ -222,7 +226,7 @@ namespace SharpCompress.Compressor.Deflate /// Z_OK if everything goes well. public int InitializeInflate() { - return InitializeInflate(this.WindowBits); + return InitializeInflate(WindowBits); } /// @@ -245,7 +249,7 @@ namespace SharpCompress.Compressor.Deflate /// Z_OK if everything goes well. public int InitializeInflate(bool expectRfc1950Header) { - return InitializeInflate(this.WindowBits, expectRfc1950Header); + return InitializeInflate(WindowBits, expectRfc1950Header); } /// @@ -256,7 +260,7 @@ namespace SharpCompress.Compressor.Deflate /// Z_OK if all goes well. public int InitializeInflate(int windowBits) { - this.WindowBits = windowBits; + WindowBits = windowBits; return InitializeInflate(windowBits, true); } @@ -281,9 +285,11 @@ namespace SharpCompress.Compressor.Deflate /// Z_OK if everything goes well. public int InitializeInflate(int windowBits, bool expectRfc1950Header) { - this.WindowBits = windowBits; + WindowBits = windowBits; if (dstate != null) + { throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); + } istate = new InflateManager(expectRfc1950Header); return istate.Initialize(this, windowBits); } @@ -354,11 +360,12 @@ namespace SharpCompress.Compressor.Deflate public int Inflate(FlushType flush) { if (istate == null) + { throw new ZlibException("No Inflate State!"); + } return istate.Inflate(flush); } - /// /// Ends an inflation session. /// @@ -371,7 +378,9 @@ namespace SharpCompress.Compressor.Deflate public int EndInflate() { if (istate == null) + { throw new ZlibException("No Inflate State!"); + } int ret = istate.End(); istate = null; return ret; @@ -384,7 +393,9 @@ namespace SharpCompress.Compressor.Deflate public int SyncInflate() { if (istate == null) + { throw new ZlibException("No Inflate State!"); + } return istate.Sync(); } @@ -444,11 +455,10 @@ namespace SharpCompress.Compressor.Deflate /// Z_OK if all goes well. public int InitializeDeflate(CompressionLevel level) { - this.CompressLevel = level; + CompressLevel = level; return _InternalInitializeDeflate(true); } - /// /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the explicit flag governing whether to emit an RFC1950 header byte pair. @@ -465,11 +475,10 @@ namespace SharpCompress.Compressor.Deflate /// Z_OK if all goes well. public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header) { - this.CompressLevel = level; + CompressLevel = level; return _InternalInitializeDeflate(wantRfc1950Header); } - /// /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the specified number of window bits. @@ -482,8 +491,8 @@ namespace SharpCompress.Compressor.Deflate /// Z_OK if all goes well. public int InitializeDeflate(CompressionLevel level, int bits) { - this.CompressLevel = level; - this.WindowBits = bits; + CompressLevel = level; + WindowBits = bits; return _InternalInitializeDeflate(true); } @@ -499,19 +508,21 @@ namespace SharpCompress.Compressor.Deflate /// Z_OK if all goes well. public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header) { - this.CompressLevel = level; - this.WindowBits = bits; + CompressLevel = level; + WindowBits = bits; return _InternalInitializeDeflate(wantRfc1950Header); } private int _InternalInitializeDeflate(bool wantRfc1950Header) { if (istate != null) + { throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate()."); + } dstate = new DeflateManager(); dstate.WantRfc1950HeaderBytes = wantRfc1950Header; - return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy); + return dstate.Initialize(this, CompressLevel, WindowBits, Strategy); } /// @@ -585,7 +596,9 @@ namespace SharpCompress.Compressor.Deflate public int Deflate(FlushType flush) { if (dstate == null) + { throw new ZlibException("No Deflate State!"); + } return dstate.Deflate(flush); } @@ -599,7 +612,10 @@ namespace SharpCompress.Compressor.Deflate public int EndDeflate() { if (dstate == null) + { throw new ZlibException("No Deflate State!"); + } + // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this) //int ret = dstate.End(); dstate = null; @@ -618,11 +634,12 @@ namespace SharpCompress.Compressor.Deflate public void ResetDeflate() { if (dstate == null) + { throw new ZlibException("No Deflate State!"); + } dstate.Reset(); } - /// /// Set the CompressionStrategy and CompressionLevel for a deflation session. /// @@ -632,11 +649,12 @@ namespace SharpCompress.Compressor.Deflate public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy) { if (dstate == null) + { throw new ZlibException("No Deflate State!"); + } return dstate.SetParams(level, strategy); } - /// /// Set the dictionary to be used for either Inflation or Deflation. /// @@ -645,10 +663,14 @@ namespace SharpCompress.Compressor.Deflate public int SetDictionary(byte[] dictionary) { if (istate != null) + { return istate.SetDictionary(dictionary); + } if (dstate != null) + { return dstate.SetDictionary(dictionary); + } throw new ZlibException("No Inflate or Deflate state!"); } @@ -662,9 +684,13 @@ namespace SharpCompress.Compressor.Deflate int len = dstate.pendingCount; if (len > AvailableBytesOut) + { len = AvailableBytesOut; + } if (len == 0) + { return; + } if (dstate.pending.Length <= dstate.nextPending || OutputBuffer.Length <= NextOut || @@ -698,9 +724,13 @@ namespace SharpCompress.Compressor.Deflate int len = AvailableBytesIn; if (len > size) + { len = size; + } if (len == 0) + { return 0; + } AvailableBytesIn -= len; diff --git a/src/SharpCompress/Compressor/Deflate/ZlibStream.cs b/src/SharpCompress/Compressor/Deflate/ZlibStream.cs index 2a0fa10b..64bf59f6 100644 --- a/src/SharpCompress/Compressor/Deflate/ZlibStream.cs +++ b/src/SharpCompress/Compressor/Deflate/ZlibStream.cs @@ -66,7 +66,10 @@ namespace SharpCompress.Compressor.Deflate get { return (_baseStream._flushMode); } set { - if (_disposed) throw new ObjectDisposedException("ZlibStream"); + if (_disposed) + { + throw new ObjectDisposedException("ZlibStream"); + } _baseStream._flushMode = value; } } @@ -93,28 +96,29 @@ namespace SharpCompress.Compressor.Deflate get { return _baseStream._bufferSize; } set { - if (_disposed) throw new ObjectDisposedException("ZlibStream"); + if (_disposed) + { + throw new ObjectDisposedException("ZlibStream"); + } if (_baseStream._workingBuffer != null) + { throw new ZlibException("The working buffer is already set."); + } if (value < ZlibConstants.WorkingBufferSizeMin) + { throw new ZlibException( - String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, - ZlibConstants.WorkingBufferSizeMin)); + String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, + ZlibConstants.WorkingBufferSizeMin)); + } _baseStream._bufferSize = value; } } /// Returns the total number of bytes input so far. - public virtual long TotalIn - { - get { return _baseStream._z.TotalBytesIn; } - } + public virtual long TotalIn { get { return _baseStream._z.TotalBytesIn; } } /// Returns the total number of bytes output so far. - public virtual long TotalOut - { - get { return _baseStream._z.TotalBytesOut; } - } + public virtual long TotalOut { get { return _baseStream._z.TotalBytesOut; } } #endregion @@ -130,7 +134,10 @@ namespace SharpCompress.Compressor.Deflate { get { - if (_disposed) throw new ObjectDisposedException("ZlibStream"); + if (_disposed) + { + throw new ObjectDisposedException("ZlibStream"); + } return _baseStream._stream.CanRead; } } @@ -141,10 +148,7 @@ namespace SharpCompress.Compressor.Deflate /// /// Always returns false. /// - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } /// /// Indicates whether the stream can be written. @@ -156,7 +160,10 @@ namespace SharpCompress.Compressor.Deflate { get { - if (_disposed) throw new ObjectDisposedException("ZlibStream"); + if (_disposed) + { + throw new ObjectDisposedException("ZlibStream"); + } return _baseStream._stream.CanWrite; } } @@ -164,10 +171,7 @@ namespace SharpCompress.Compressor.Deflate /// /// Reading this property always throws a . /// - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } /// /// The position of the stream pointer. @@ -185,9 +189,13 @@ namespace SharpCompress.Compressor.Deflate get { if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Writer) + { return _baseStream._z.TotalBytesOut; + } if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Reader) + { return _baseStream._z.TotalBytesIn; + } return 0; } @@ -208,7 +216,9 @@ namespace SharpCompress.Compressor.Deflate if (!_disposed) { if (disposing && (_baseStream != null)) + { _baseStream.Dispose(); + } _disposed = true; } } @@ -223,7 +233,10 @@ namespace SharpCompress.Compressor.Deflate /// public override void Flush() { - if (_disposed) throw new ObjectDisposedException("ZlibStream"); + if (_disposed) + { + throw new ObjectDisposedException("ZlibStream"); + } _baseStream.Flush(); } @@ -255,7 +268,10 @@ namespace SharpCompress.Compressor.Deflate /// the number of bytes to read. public override int Read(byte[] buffer, int offset, int count) { - if (_disposed) throw new ObjectDisposedException("ZlibStream"); + if (_disposed) + { + throw new ObjectDisposedException("ZlibStream"); + } return _baseStream.Read(buffer, offset, count); } @@ -303,7 +319,10 @@ namespace SharpCompress.Compressor.Deflate /// the number of bytes to write. public override void Write(byte[] buffer, int offset, int count) { - if (_disposed) throw new ObjectDisposedException("ZlibStream"); + if (_disposed) + { + throw new ObjectDisposedException("ZlibStream"); + } _baseStream.Write(buffer, offset, count); } diff --git a/src/SharpCompress/Compressor/Filters/BCJ2Filter.cs b/src/SharpCompress/Compressor/Filters/BCJ2Filter.cs index baca08ff..1ec435c3 100644 --- a/src/SharpCompress/Compressor/Filters/BCJ2Filter.cs +++ b/src/SharpCompress/Compressor/Filters/BCJ2Filter.cs @@ -7,26 +7,26 @@ namespace SharpCompress.Compressor.Filters { private readonly Stream baseStream; private readonly byte[] input = new byte[4096]; - private int inputOffset = 0; - private int inputCount = 0; - private bool endReached = false; + private int inputOffset; + private int inputCount; + private bool endReached; - private long position = 0; - private byte[] output = new byte[4]; - private int outputOffset = 0; - private int outputCount = 0; + private long position; + private readonly byte[] output = new byte[4]; + private int outputOffset; + private int outputCount; - private byte[] control; - private byte[] data1; - private byte[] data2; + private readonly byte[] control; + private readonly byte[] data1; + private readonly byte[] data2; - private int controlPos = 0; - private int data1Pos = 0; - private int data2Pos = 0; + private int controlPos; + private int data1Pos; + private int data2Pos; - private ushort[] p = new ushort[256 + 2]; + private readonly ushort[] p = new ushort[256 + 2]; private uint range, code; - private byte prevByte = 0; + private byte prevByte; private bool isDisposed; private const int kNumTopBits = 24; @@ -55,12 +55,16 @@ namespace SharpCompress.Compressor.Filters int i; for (i = 0; i < p.Length; i++) + { p[i] = kBitModelTotal >> 1; + } code = 0; range = 0xFFFFFFFF; for (i = 0; i < 5; i++) + { code = (code << 8) | control[controlPos++]; + } } protected override void Dispose(bool disposing) @@ -74,36 +78,20 @@ namespace SharpCompress.Compressor.Filters baseStream.Dispose(); } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { throw new NotSupportedException(); } - public override long Length - { - get { return baseStream.Length + data1.Length + data2.Length; } - } + public override long Length { get { return baseStream.Length + data1.Length + data2.Length; } } - public override long Position - { - get { return position; } - set { throw new NotSupportedException(); } - } + public override long Position { get { return position; } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -121,7 +109,9 @@ namespace SharpCompress.Compressor.Filters prevByte = b; if (size == count) + { return size; + } } if (inputOffset == inputCount) @@ -141,16 +131,24 @@ namespace SharpCompress.Compressor.Filters position++; if (!IsJ(prevByte, b)) + { prevByte = b; + } else { int prob; if (b == 0xE8) + { prob = prevByte; + } else if (b == 0xE9) + { prob = 256; + } else + { prob = 257; + } uint bound = (range >> kNumBitModelTotalBits) * p[prob]; if (code < bound) @@ -177,15 +175,19 @@ namespace SharpCompress.Compressor.Filters uint dest; if (b == 0xE8) + { 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)(position + 4); output[0] = (byte)dest; diff --git a/src/SharpCompress/Compressor/Filters/BCJFilter.cs b/src/SharpCompress/Compressor/Filters/BCJFilter.cs index 8e1627d3..ec6f89ab 100644 --- a/src/SharpCompress/Compressor/Filters/BCJFilter.cs +++ b/src/SharpCompress/Compressor/Filters/BCJFilter.cs @@ -4,12 +4,12 @@ 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 bool[] MASK_TO_ALLOWED_STATUS = {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 static readonly int[] MASK_TO_BIT_NUMBER = {0, 1, 2, 2, 3, 3, 3, 3}; private int pos; - private int prevMask = 0; + private int prevMask; public BCJFilter(bool isEncoder, Stream baseStream) : base(isEncoder, baseStream, 5) @@ -31,7 +31,9 @@ namespace SharpCompress.Compressor.Filters for (i = offset; i <= end; ++i) { if ((buffer[i] & 0xFE) != 0xE8) + { continue; + } prevPos = i - prevPos; if ((prevPos & ~3) != 0) @@ -45,7 +47,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; @@ -66,16 +68,24 @@ namespace SharpCompress.Compressor.Filters while (true) { if (isEncoder) + { dest = src + (pos + i - offset); + } else + { dest = src - (pos + i - offset); + } if (prevMask == 0) + { break; + } int index = MASK_TO_BIT_NUMBER[prevMask] * 8; if (!test86MSByte((byte)(dest >> (24 - index)))) + { break; + } src = dest ^ ((1 << (32 - index)) - 1); } diff --git a/src/SharpCompress/Compressor/Filters/Filter.cs b/src/SharpCompress/Compressor/Filters/Filter.cs index e1961943..723dd203 100644 --- a/src/SharpCompress/Compressor/Filters/Filter.cs +++ b/src/SharpCompress/Compressor/Filters/Filter.cs @@ -8,11 +8,11 @@ namespace SharpCompress.Compressor.Filters protected bool isEncoder; protected Stream baseStream; - private byte[] tail; - private byte[] window; - private int transformed = 0; - private int read = 0; - private bool endReached = false; + private readonly byte[] tail; + private readonly byte[] window; + private int transformed; + private int read; + private bool endReached; private bool isDisposed; protected Filter(bool isEncoder, Stream baseStream, int lookahead) @@ -34,36 +34,20 @@ namespace SharpCompress.Compressor.Filters baseStream.Dispose(); } - public override bool CanRead - { - get { return !isEncoder; } - } + public override bool CanRead { get { return !isEncoder; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return isEncoder; } - } + public override bool CanWrite { get { return isEncoder; } } public override void Flush() { throw new NotSupportedException(); } - public override long Length - { - get { return baseStream.Length; } - } + public override long Length { get { return baseStream.Length; } } - public override long Position - { - get { return baseStream.Position; } - set { throw new NotSupportedException(); } - } + public override long Position { get { return baseStream.Position; } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -73,7 +57,9 @@ namespace SharpCompress.Compressor.Filters { int copySize = transformed; if (copySize > count) + { copySize = count; + } Buffer.BlockCopy(tail, 0, buffer, offset, copySize); transformed -= copySize; read -= copySize; @@ -83,11 +69,15 @@ namespace SharpCompress.Compressor.Filters Buffer.BlockCopy(tail, copySize, tail, 0, read); } if (count == 0) + { return size; + } int inSize = read; if (inSize > count) + { inSize = count; + } Buffer.BlockCopy(tail, 0, buffer, offset, inSize); read -= inSize; Buffer.BlockCopy(tail, inSize, tail, 0, read); @@ -96,14 +86,18 @@ namespace SharpCompress.Compressor.Filters int baseRead = baseStream.Read(buffer, offset + inSize, count - inSize); inSize += baseRead; if (baseRead == 0) + { endReached = true; + } } while (!endReached && read < tail.Length) { int baseRead = baseStream.Read(tail, read, tail.Length - read); read += baseRead; if (baseRead == 0) + { endReached = true; + } } if (inSize > tail.Length) @@ -117,14 +111,20 @@ namespace SharpCompress.Compressor.Filters } if (count == 0) + { return size; + } Buffer.BlockCopy(buffer, offset, window, 0, inSize); Buffer.BlockCopy(tail, 0, window, inSize, read); if (inSize + read > tail.Length) + { transformed = Transform(window, 0, inSize + read); + } else + { transformed = inSize + read; + } Buffer.BlockCopy(window, 0, buffer, offset, inSize); Buffer.BlockCopy(window, inSize, tail, 0, read); size += inSize; diff --git a/src/SharpCompress/Compressor/LZMA/AesDecoderStream.cs b/src/SharpCompress/Compressor/LZMA/AesDecoderStream.cs index 018e4379..30ffbc39 100644 --- a/src/SharpCompress/Compressor/LZMA/AesDecoderStream.cs +++ b/src/SharpCompress/Compressor/LZMA/AesDecoderStream.cs @@ -1,4 +1,5 @@ -#if !NO_CRYPTO + +#if !NO_CRYPTO using System; using System.IO; using System.Security.Cryptography; diff --git a/src/SharpCompress/Compressor/LZMA/Bcj2DecoderStream.cs b/src/SharpCompress/Compressor/LZMA/Bcj2DecoderStream.cs index b64f085c..e38ff75a 100644 --- a/src/SharpCompress/Compressor/LZMA/Bcj2DecoderStream.cs +++ b/src/SharpCompress/Compressor/LZMA/Bcj2DecoderStream.cs @@ -11,7 +11,7 @@ namespace SharpCompress.Compressor.LZMA private class RangeDecoder { - internal Stream mStream; + internal readonly Stream mStream; internal uint Range; internal uint Code; @@ -20,14 +20,18 @@ namespace SharpCompress.Compressor.LZMA mStream = stream; Range = 0xFFFFFFFF; for (int i = 0; i < 5; i++) + { Code = (Code << 8) | ReadByte(); + } } public byte ReadByte() { int bt = mStream.ReadByte(); if (bt < 0) + { throw new EndOfStreamException(); + } return (byte)bt; } @@ -59,9 +63,13 @@ namespace SharpCompress.Compressor.LZMA Prob += (1 - symbol) << (kNumBitModelTotalBits - numMoveBits); */ if (symbol == 0) + { Prob += (kBitModelTotal - Prob) >> numMoveBits; + } else + { Prob -= (Prob) >> numMoveBits; + } } public uint Decode(RangeDecoder decoder) @@ -78,38 +86,39 @@ namespace SharpCompress.Compressor.LZMA } return 0; } - else + decoder.Range -= newBound; + decoder.Code -= newBound; + Prob -= Prob >> numMoveBits; + if (decoder.Range < kTopValue) { - decoder.Range -= newBound; - decoder.Code -= newBound; - Prob -= Prob >> numMoveBits; - if (decoder.Range < kTopValue) - { - decoder.Code = (decoder.Code << 8) | decoder.ReadByte(); - decoder.Range <<= 8; - } - return 1; + decoder.Code = (decoder.Code << 8) | decoder.ReadByte(); + decoder.Range <<= 8; } + return 1; } } - private Stream mMainStream; - private Stream mCallStream; - private Stream mJumpStream; - private RangeDecoder mRangeDecoder; - private StatusDecoder[] mStatusDecoder; + private readonly Stream mMainStream; + private readonly Stream mCallStream; + private readonly Stream mJumpStream; + private readonly RangeDecoder mRangeDecoder; + private readonly StatusDecoder[] mStatusDecoder; private long mWritten; - private IEnumerator mIter; + private readonly IEnumerator mIter; private bool mFinished; private bool isDisposed; public Bcj2DecoderStream(Stream[] streams, byte[] info, long limit) { if (info != null && info.Length > 0) + { throw new NotSupportedException(); + } if (streams.Length != 4) + { throw new NotSupportedException(); + } mMainStream = streams[0]; mCallStream = streams[1]; @@ -118,7 +127,9 @@ namespace SharpCompress.Compressor.LZMA mStatusDecoder = new StatusDecoder[256 + 2]; for (int i = 0; i < mStatusDecoder.Length; i++) + { mStatusDecoder[i] = new StatusDecoder(); + } mIter = Run().GetEnumerator(); } @@ -151,17 +162,22 @@ namespace SharpCompress.Compressor.LZMA private static int GetIndex(byte b0, byte b1) { if (b1 == 0xE8) + { return b0; - else if (b1 == 0xE9) + } + if (b1 == 0xE9) + { return 256; - else - return 257; + } + return 257; } public override int Read(byte[] buffer, int offset, int count) { if (count == 0 || mFinished) + { return 0; + } for (int i = 0; i < count; i++) { @@ -183,7 +199,7 @@ namespace SharpCompress.Compressor.LZMA byte prevByte = 0; uint processedBytes = 0; - for (; ; ) + for (;;) { byte b = 0; uint i; @@ -191,20 +207,26 @@ namespace SharpCompress.Compressor.LZMA { int tmp = mMainStream.ReadByte(); if (tmp < 0) + { yield break; + } b = (byte)tmp; mWritten++; yield return b; if (IsJ(prevByte, b)) + { break; + } prevByte = b; } processedBytes += i; if (i == kBurstSize) + { continue; + } if (mStatusDecoder[GetIndex(prevByte, b)].Decode(mRangeDecoder) == 1) { @@ -215,7 +237,9 @@ namespace SharpCompress.Compressor.LZMA { int b0 = s.ReadByte(); if (b0 < 0) + { throw new EndOfStreamException(); + } src <<= 8; src |= (uint)b0; diff --git a/src/SharpCompress/Compressor/LZMA/BitVector.cs b/src/SharpCompress/Compressor/LZMA/BitVector.cs index ec7443a3..01db0edc 100644 --- a/src/SharpCompress/Compressor/LZMA/BitVector.cs +++ b/src/SharpCompress/Compressor/LZMA/BitVector.cs @@ -6,52 +6,60 @@ namespace SharpCompress.Compressor.LZMA { internal class BitVector { - private uint[] mBits; - private int mLength; + private readonly uint[] mBits; public BitVector(int length) { - mLength = length; + Length = length; mBits = new uint[(length + 31) >> 5]; } public BitVector(int length, bool initValue) { - mLength = length; + Length = length; mBits = new uint[(length + 31) >> 5]; if (initValue) + { for (int i = 0; i < mBits.Length; i++) + { mBits[i] = ~0u; + } + } } public BitVector(List bits) : this(bits.Count) { for (int i = 0; i < bits.Count; i++) + { if (bits[i]) + { SetBit(i); + } + } } public bool[] ToArray() { - bool[] bits = new bool[mLength]; + bool[] bits = new bool[Length]; for (int i = 0; i < bits.Length; i++) + { bits[i] = this[i]; + } return bits; } - public int Length - { - get { return mLength; } - } + public int Length { get; } public bool this[int index] { get { - if (index < 0 || index >= mLength) + if (index < 0 || index >= Length) + { throw new ArgumentOutOfRangeException("index"); + } return (mBits[index >> 5] & (1u << (index & 31))) != 0; } @@ -59,16 +67,20 @@ namespace SharpCompress.Compressor.LZMA public void SetBit(int index) { - if (index < 0 || index >= mLength) + if (index < 0 || index >= Length) + { throw new ArgumentOutOfRangeException("index"); + } mBits[index >> 5] |= 1u << (index & 31); } internal bool GetAndSet(int index) { - if (index < 0 || index >= mLength) + if (index < 0 || index >= Length) + { throw new ArgumentOutOfRangeException("index"); + } uint bits = mBits[index >> 5]; uint mask = 1u << (index & 31); @@ -78,9 +90,11 @@ namespace SharpCompress.Compressor.LZMA public override string ToString() { - StringBuilder sb = new StringBuilder(mLength); - for (int i = 0; i < mLength; i++) + StringBuilder sb = new StringBuilder(Length); + for (int i = 0; i < Length; i++) + { sb.Append(this[i] ? 'x' : '.'); + } return sb.ToString(); } } diff --git a/src/SharpCompress/Compressor/LZMA/CRC.cs b/src/SharpCompress/Compressor/LZMA/CRC.cs index 6f261767..b5f82559 100644 --- a/src/SharpCompress/Compressor/LZMA/CRC.cs +++ b/src/SharpCompress/Compressor/LZMA/CRC.cs @@ -6,7 +6,7 @@ namespace SharpCompress.Compressor.LZMA internal static class CRC { public const uint kInitCRC = 0xFFFFFFFF; - private static uint[] kTable = new uint[4 * 256]; + private static readonly uint[] kTable = new uint[4 * 256]; static CRC() { @@ -16,7 +16,9 @@ namespace SharpCompress.Compressor.LZMA { uint r = i; for (int j = 0; j < 8; j++) + { r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); + } kTable[i] = r; } @@ -36,7 +38,9 @@ namespace SharpCompress.Compressor.LZMA { 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; } @@ -75,7 +79,9 @@ namespace SharpCompress.Compressor.LZMA public static uint Update(uint crc, byte[] buffer, int offset, int length) { for (int i = 0; i < length; i++) + { crc = Update(crc, buffer[offset + i]); + } return crc; } diff --git a/src/SharpCompress/Compressor/LZMA/DecoderStream.cs b/src/SharpCompress/Compressor/LZMA/DecoderStream.cs index a5084f00..0947d047 100644 --- a/src/SharpCompress/Compressor/LZMA/DecoderStream.cs +++ b/src/SharpCompress/Compressor/LZMA/DecoderStream.cs @@ -8,36 +8,20 @@ namespace SharpCompress.Compressor.LZMA { internal abstract class DecoderStream2 : Stream { - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { throw new NotSupportedException(); } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { @@ -64,7 +48,9 @@ namespace SharpCompress.Compressor.LZMA var coderInfo = folderInfo.Coders[coderIndex]; outStreamIndex -= coderInfo.NumOutStreams; if (outStreamIndex < 0) + { return coderIndex; + } } throw new InvalidOperationException("Could not link output stream to coder."); @@ -88,7 +74,9 @@ namespace SharpCompress.Compressor.LZMA if (folderInfo.FindBindPairForOutStream(outStreamIndex) < 0) { if (foundPrimaryOutStream) + { throw new NotSupportedException("Multiple output streams."); + } foundPrimaryOutStream = true; primaryCoderIndex = coderIndex; @@ -98,7 +86,9 @@ namespace SharpCompress.Compressor.LZMA } if (!foundPrimaryOutStream) + { throw new NotSupportedException("No output stream."); + } } private static Stream CreateDecoderStream(Stream[] packStreams, long[] packSizes, Stream[] outStreams, @@ -106,15 +96,21 @@ namespace SharpCompress.Compressor.LZMA { var coderInfo = folderInfo.Coders[coderIndex]; if (coderInfo.NumOutStreams != 1) + { throw new NotSupportedException("Multiple output streams are not supported."); + } int inStreamId = 0; for (int i = 0; i < coderIndex; i++) + { inStreamId += folderInfo.Coders[i].NumInStreams; + } int outStreamId = 0; for (int i = 0; i < coderIndex; i++) + { outStreamId += folderInfo.Coders[i].NumOutStreams; + } Stream[] inStreams = new Stream[coderInfo.NumInStreams]; @@ -126,15 +122,20 @@ namespace SharpCompress.Compressor.LZMA int pairedOutIndex = folderInfo.BindPairs[bindPairIndex].OutIndex; 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); + //inStreamSizes[i] = folderInfo.UnpackSizes[pairedOutIndex]; if (outStreams[pairedOutIndex] != null) + { throw new NotSupportedException("Overlapping stream bindings are not supported."); + } outStreams[pairedOutIndex] = inStreams[i]; } @@ -142,9 +143,12 @@ namespace SharpCompress.Compressor.LZMA { int index = folderInfo.FindPackStreamArrayIndex(inStreamId); if (index < 0) + { throw new NotSupportedException("Could not find input stream binding."); + } inStreams[i] = packStreams[index]; + //inStreamSizes[i] = packSizes[index]; } } @@ -157,7 +161,9 @@ namespace SharpCompress.Compressor.LZMA IPasswordProvider pass) { if (!folderInfo.CheckStructure()) + { throw new NotSupportedException("Unsupported stream binding structure."); + } Stream[] inStreams = new Stream[folderInfo.PackStreams.Count]; for (int j = 0; j < folderInfo.PackStreams.Count; j++) diff --git a/src/SharpCompress/Compressor/LZMA/ICoder.cs b/src/SharpCompress/Compressor/LZMA/ICoder.cs index 354bd836..61235720 100644 --- a/src/SharpCompress/Compressor/LZMA/ICoder.cs +++ b/src/SharpCompress/Compressor/LZMA/ICoder.cs @@ -1,4 +1,5 @@ using System; +using System.IO; namespace SharpCompress.Compressor.LZMA { @@ -7,7 +8,8 @@ namespace SharpCompress.Compressor.LZMA /// internal class DataErrorException : Exception { - public DataErrorException() : base("Data Error") + public DataErrorException() + : base("Data Error") { } } @@ -17,7 +19,8 @@ namespace SharpCompress.Compressor.LZMA /// internal class InvalidParamException : Exception { - public InvalidParamException() : base("Invalid Parameter") + public InvalidParamException() + : base("Invalid Parameter") { } } @@ -34,7 +37,7 @@ namespace SharpCompress.Compressor.LZMA /// output size. -1 if unknown. /// void SetProgress(Int64 inSize, Int64 outSize); - }; + } internal interface ICoder { @@ -56,9 +59,9 @@ namespace SharpCompress.Compressor.LZMA /// /// callback progress reference. /// - void Code(System.IO.Stream inStream, System.IO.Stream outStream, + void Code(Stream inStream, Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress); - }; + } /* public interface ICoder2 @@ -150,17 +153,16 @@ namespace SharpCompress.Compressor.LZMA /// Specifies mode with end marker. /// EndMarker - }; - + } internal interface ISetCoderProperties { void SetCoderProperties(CoderPropID[] propIDs, object[] properties); - }; + } internal interface IWriteCoderProperties { - void WriteCoderProperties(System.IO.Stream outStream); + void WriteCoderProperties(Stream outStream); } internal interface ISetDecoderProperties diff --git a/src/SharpCompress/Compressor/LZMA/LZ/CRC.cs b/src/SharpCompress/Compressor/LZMA/LZ/CRC.cs index a1775aac..0476c962 100644 --- a/src/SharpCompress/Compressor/LZMA/LZ/CRC.cs +++ b/src/SharpCompress/Compressor/LZMA/LZ/CRC.cs @@ -12,10 +12,16 @@ namespace SharpCompress.Compressor.LZMA.LZ { uint r = i; for (int j = 0; j < 8; j++) + { if ((r & 1) != 0) + { r = (r >> 1) ^ kPoly; + } else + { r >>= 1; + } + } Table[i] = r; } } @@ -29,13 +35,15 @@ namespace SharpCompress.Compressor.LZMA.LZ 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() @@ -46,6 +54,7 @@ namespace SharpCompress.Compressor.LZMA.LZ private static uint CalculateDigest(byte[] data, uint offset, uint size) { CRC crc = new CRC(); + // crc.Init(); crc.Update(data, offset, size); return crc.GetDigest(); diff --git a/src/SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs b/src/SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs index e7d7f38a..8e1a7d5b 100644 --- a/src/SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs +++ b/src/SharpCompress/Compressor/LZMA/LZ/LzBinTree.cs @@ -1,11 +1,12 @@ using System; +using System.IO; namespace SharpCompress.Compressor.LZMA.LZ { internal class BinTree : InWindow { private UInt32 _cyclicBufferPos; - private UInt32 _cyclicBufferSize = 0; + private UInt32 _cyclicBufferSize; private UInt32 _matchMaxLen; private UInt32[] _son; @@ -13,7 +14,7 @@ namespace SharpCompress.Compressor.LZMA.LZ private UInt32 _cutValue = 0xFF; private UInt32 _hashMask; - private UInt32 _hashSizeSum = 0; + private UInt32 _hashSizeSum; private bool HASH_ARRAY = true; @@ -23,9 +24,9 @@ namespace SharpCompress.Compressor.LZMA.LZ private const UInt32 kStartMaxLen = 1; private const UInt32 kHash3Offset = kHash2Size; private const UInt32 kEmptyHashValue = 0; - private const UInt32 kMaxValForNormalize = ((UInt32) 1 << 31) - 1; + private const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1; - private UInt32 kNumHashDirectBytes = 0; + private UInt32 kNumHashDirectBytes; private UInt32 kMinMatchCheck = 4; private UInt32 kFixHashSize = kHash2Size + kHash3Size; @@ -46,7 +47,7 @@ namespace SharpCompress.Compressor.LZMA.LZ } } - public new void SetStream(System.IO.Stream stream) + public new void SetStream(Stream stream) { base.SetStream(stream); } @@ -60,7 +61,9 @@ namespace SharpCompress.Compressor.LZMA.LZ { base.Init(); for (UInt32 i = 0; i < _hashSizeSum; i++) + { _hash[i] = kEmptyHashValue; + } _cyclicBufferPos = 0; ReduceOffsets(-1); } @@ -68,10 +71,14 @@ namespace SharpCompress.Compressor.LZMA.LZ public new void MovePos() { if (++_cyclicBufferPos >= _cyclicBufferSize) + { _cyclicBufferPos = 0; + } base.MovePos(); if (_pos == kMaxValForNormalize) + { Normalize(); + } } public new Byte GetIndexByte(Int32 index) @@ -93,11 +100,13 @@ namespace SharpCompress.Compressor.LZMA.LZ 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); @@ -105,7 +114,9 @@ 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; @@ -119,20 +130,26 @@ namespace SharpCompress.Compressor.LZMA.LZ hs >>= 1; hs |= 0xFFFF; if (hs > (1 << 24)) + { hs >>= 1; + } _hashMask = hs; hs++; hs += kFixHashSize; } if (hs != _hashSizeSum) + { _hash = new UInt32[_hashSizeSum = hs]; + } } public UInt32 GetMatches(UInt32[] distances) { UInt32 lenLimit; if (_pos + _matchMaxLen <= _streamPos) + { lenLimit = _matchMaxLen; + } else { lenLimit = _streamPos - _pos; @@ -153,12 +170,14 @@ 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) @@ -168,20 +187,26 @@ namespace SharpCompress.Compressor.LZMA.LZ _hash[hash2Value] = _pos; _hash[kHash3Offset + hash3Value] = _pos; if (curMatch2 > matchMinPos) + { if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) { distances[offset++] = maxLen = 2; distances[offset++] = _pos - curMatch2 - 1; } + } if (curMatch3 > matchMinPos) + { if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) { if (curMatch3 == curMatch2) + { offset -= 2; + } distances[offset++] = maxLen = 3; distances[offset++] = _pos - curMatch3 - 1; curMatch2 = curMatch3; } + } if (offset != 0 && curMatch2 == curMatch) { offset -= 2; @@ -229,8 +254,12 @@ namespace SharpCompress.Compressor.LZMA.LZ if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) + { if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) + { break; + } + } if (maxLen < len) { distances[offset++] = maxLen = len; @@ -268,7 +297,9 @@ namespace SharpCompress.Compressor.LZMA.LZ { UInt32 lenLimit; if (_pos + _matchMaxLen <= _streamPos) + { lenLimit = _matchMaxLen; + } else { lenLimit = _streamPos - _pos; @@ -289,13 +320,15 @@ 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; @@ -325,8 +358,12 @@ namespace SharpCompress.Compressor.LZMA.LZ if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) + { if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) + { break; + } + } if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; @@ -350,7 +387,8 @@ namespace SharpCompress.Compressor.LZMA.LZ } } MovePos(); - } while (--num != 0); + } + while (--num != 0); } private void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) @@ -359,9 +397,13 @@ namespace SharpCompress.Compressor.LZMA.LZ { UInt32 value = items[i]; if (value <= subValue) + { value = kEmptyHashValue; + } else + { value -= subValue; + } items[i] = value; } } @@ -369,9 +411,9 @@ namespace SharpCompress.Compressor.LZMA.LZ 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) diff --git a/src/SharpCompress/Compressor/LZMA/LZ/LzInWindow.cs b/src/SharpCompress/Compressor/LZMA/LZ/LzInWindow.cs index 7bc83ec8..adb3d53f 100644 --- a/src/SharpCompress/Compressor/LZMA/LZ/LzInWindow.cs +++ b/src/SharpCompress/Compressor/LZMA/LZ/LzInWindow.cs @@ -1,11 +1,12 @@ using System; +using System.IO; namespace SharpCompress.Compressor.LZMA.LZ { internal class InWindow { - public Byte[] _bufferBase = null; // pointer to buffer with data - private System.IO.Stream _stream; + public Byte[] _bufferBase; // pointer to buffer with data + private 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 @@ -21,44 +22,57 @@ namespace SharpCompress.Compressor.LZMA.LZ public void MoveBlock() { - UInt32 offset = (UInt32) (_bufferOffset) + _pos - _keepSizeBefore; + UInt32 offset = _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 = _bufferOffset + _streamPos - offset; // check negative offset ???? for (UInt32 i = 0; i < numBytes; i++) + { _bufferBase[i] = _bufferBase[offset + i]; + } _bufferOffset -= offset; } public virtual void ReadBlock() { if (_streamEndWasReached) + { 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) + ? _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 = _pointerToLastSafePosition - _bufferOffset; + } _streamEndWasReached = true; return; } - _streamPos += (UInt32) numReadBytes; + _streamPos += (UInt32)numReadBytes; if (_streamPos >= _pos + _keepSizeAfter) + { _posLimit = _streamPos - _keepSizeAfter; + } } } @@ -82,14 +96,16 @@ namespace SharpCompress.Compressor.LZMA.LZ _streamEndWasReached = false; } - public void SetStream(System.IO.Stream stream) + public void SetStream(Stream stream) { _stream = stream; if (_streamEndWasReached) { _streamEndWasReached = false; if (IsDataStarved) + { ReadBlock(); + } } } @@ -114,7 +130,9 @@ namespace SharpCompress.Compressor.LZMA.LZ { UInt32 pointerToPostion = _bufferOffset + _pos; if (pointerToPostion > _pointerToLastSafePosition) + { MoveBlock(); + } ReadBlock(); } } @@ -128,14 +146,22 @@ namespace SharpCompress.Compressor.LZMA.LZ 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++) ; + for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++) + { + ; + } return i; } @@ -146,15 +172,12 @@ namespace SharpCompress.Compressor.LZMA.LZ 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; } - } + public bool IsDataStarved { get { return _streamPos - _pos < _keepSizeAfter; } } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/LZMA/LZ/LzOutWindow.cs b/src/SharpCompress/Compressor/LZMA/LZ/LzOutWindow.cs index 4fc6c0cf..c55384d9 100644 --- a/src/SharpCompress/Compressor/LZMA/LZ/LzOutWindow.cs +++ b/src/SharpCompress/Compressor/LZMA/LZ/LzOutWindow.cs @@ -1,14 +1,17 @@ +using System; +using System.IO; + namespace SharpCompress.Compressor.LZMA.LZ { internal class OutWindow { - private byte[] _buffer = null; - private int _windowSize = 0; + private byte[] _buffer; + private int _windowSize; private int _pos; private int _streamPos; private int _pendingLen; private int _pendingDist; - private System.IO.Stream _stream; + private Stream _stream; public long Total; public long Limit; @@ -16,9 +19,13 @@ namespace SharpCompress.Compressor.LZMA.LZ public void Create(int windowSize) { if (_windowSize != windowSize) + { _buffer = new byte[windowSize]; + } else + { _buffer[windowSize - 1] = 0; + } _windowSize = windowSize; _pos = 0; _streamPos = 0; @@ -32,23 +39,25 @@ namespace SharpCompress.Compressor.LZMA.LZ Create(_windowSize); } - public void Init(System.IO.Stream stream) + public void Init(Stream stream) { ReleaseStream(); _stream = stream; } - public void Train(System.IO.Stream stream) + public void Train(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; _pos = _windowSize - size; CopyStream(stream, size); if (_pos == _windowSize) + { _pos = 0; + } _streamPos = _pos; } @@ -61,13 +70,19 @@ namespace SharpCompress.Compressor.LZMA.LZ public void Flush() { if (_stream == null) + { return; + } int size = _pos - _streamPos; if (size == 0) + { return; + } _stream.Write(_buffer, _streamPos, size); if (_pos >= _windowSize) + { _pos = 0; + } _streamPos = _pos; } @@ -76,15 +91,21 @@ namespace SharpCompress.Compressor.LZMA.LZ int size = len; int pos = _pos - distance - 1; if (pos < 0) + { pos += _windowSize; + } for (; size > 0 && _pos < _windowSize && Total < Limit; size--) { if (pos >= _windowSize) + { pos = 0; + } _buffer[_pos++] = _buffer[pos++]; Total++; if (_pos >= _windowSize) + { Flush(); + } } _pendingLen = size; _pendingDist = distance; @@ -95,35 +116,47 @@ namespace SharpCompress.Compressor.LZMA.LZ _buffer[_pos++] = b; Total++; if (_pos >= _windowSize) + { Flush(); + } } public byte GetByte(int distance) { int pos = _pos - distance - 1; if (pos < 0) + { pos += _windowSize; + } return _buffer[pos]; } - public int CopyStream(System.IO.Stream stream, int len) + public int CopyStream(Stream stream, int len) { int size = len; while (size > 0 && _pos < _windowSize && Total < Limit) { 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); if (numReadBytes == 0) + { throw new DataErrorException(); + } size -= numReadBytes; _pos += numReadBytes; Total += numReadBytes; if (_pos >= _windowSize) + { Flush(); + } } return len - size; } @@ -133,25 +166,23 @@ namespace SharpCompress.Compressor.LZMA.LZ Limit = Total + size; } - public bool HasSpace - { - get { return _pos < _windowSize && Total < Limit; } - } + public bool HasSpace { get { return _pos < _windowSize && Total < Limit; } } - public bool HasPending - { - get { return _pendingLen > 0; } - } + public bool HasPending { get { return _pendingLen > 0; } } public int Read(byte[] buffer, int offset, int count) { if (_streamPos >= _pos) + { return 0; + } int size = _pos - _streamPos; if (size > count) + { size = count; - System.Buffer.BlockCopy(_buffer, _streamPos, buffer, offset, size); + } + Buffer.BlockCopy(_buffer, _streamPos, buffer, offset, size); _streamPos += size; if (_streamPos >= _windowSize) { @@ -164,12 +195,11 @@ namespace SharpCompress.Compressor.LZMA.LZ public void CopyPending() { if (_pendingLen > 0) + { CopyBlock(_pendingDist, _pendingLen); + } } - public int AvailableBytes - { - get { return _pos - _streamPos; } - } + public int AvailableBytes { get { return _pos - _streamPos; } } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/LZMA/Log.cs b/src/SharpCompress/Compressor/LZMA/Log.cs index 82a7ae4c..1ec4e27a 100644 --- a/src/SharpCompress/Compressor/LZMA/Log.cs +++ b/src/SharpCompress/Compressor/LZMA/Log.cs @@ -1,11 +1,12 @@ using System; using System.Collections.Generic; +using System.Diagnostics; namespace SharpCompress.Compressor.LZMA { internal static class Log { - private static Stack _indent = new Stack(); + private static readonly Stack _indent = new Stack(); private static bool _needsIndent = true; static Log() @@ -21,7 +22,9 @@ namespace SharpCompress.Compressor.LZMA public static void PopIndent() { if (_indent.Count == 1) + { throw new InvalidOperationException(); + } _indent.Pop(); } @@ -63,28 +66,28 @@ namespace SharpCompress.Compressor.LZMA public static void WriteLine() { - System.Diagnostics.Debug.WriteLine(""); + Debug.WriteLine(""); _needsIndent = true; } public static void WriteLine(object value) { EnsureIndent(); - System.Diagnostics.Debug.WriteLine(value); + Debug.WriteLine(value); _needsIndent = true; } public static void WriteLine(string text) { EnsureIndent(); - System.Diagnostics.Debug.WriteLine(text); + Debug.WriteLine(text); _needsIndent = true; } public static void WriteLine(string format, params object[] args) { EnsureIndent(); - System.Diagnostics.Debug.WriteLine(string.Format(format, args)); + Debug.WriteLine(format, args); _needsIndent = true; } } diff --git a/src/SharpCompress/Compressor/LZMA/LzmaBase.cs b/src/SharpCompress/Compressor/LZMA/LzmaBase.cs index 9d1f78a7..a3a1f033 100644 --- a/src/SharpCompress/Compressor/LZMA/LzmaBase.cs +++ b/src/SharpCompress/Compressor/LZMA/LzmaBase.cs @@ -21,24 +21,33 @@ namespace SharpCompress.Compressor.LZMA public void UpdateChar() { - if (Index < 4) Index = 0; - else if (Index < 10) Index -= 3; - else Index -= 6; + if (Index < 4) + { + Index = 0; + } + else if (Index < 10) + { + Index -= 3; + } + else + { + Index -= 6; + } } public void UpdateMatch() { - Index = (uint) (Index < 7 ? 7 : 10); + Index = (uint)(Index < 7 ? 7 : 10); } public void UpdateRep() { - Index = (uint) (Index < 7 ? 8 : 11); + Index = (uint)(Index < 7 ? 8 : 11); } public void UpdateShortRep() { - Index = (uint) (Index < 7 ? 9 : 11); + Index = (uint)(Index < 7 ? 9 : 11); } public bool IsCharState() @@ -49,6 +58,7 @@ namespace SharpCompress.Compressor.LZMA public const int kNumPosSlotBits = 6; public const int kDicLogSizeMin = 0; + // public const int kDicLogSizeMax = 30; // public const uint kDistTableSizeMax = kDicLogSizeMax * 2; @@ -61,8 +71,10 @@ namespace SharpCompress.Compressor.LZMA { len -= kMatchMinLen; if (len < kNumLenToPosStates) + { return len; - return (uint) (kNumLenToPosStates - 1); + } + return kNumLenToPosStates - 1; } public const int kNumAlignBits = 4; @@ -73,7 +85,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; diff --git a/src/SharpCompress/Compressor/LZMA/LzmaDecoder.cs b/src/SharpCompress/Compressor/LZMA/LzmaDecoder.cs index 5de39f3c..925c8aab 100644 --- a/src/SharpCompress/Compressor/LZMA/LzmaDecoder.cs +++ b/src/SharpCompress/Compressor/LZMA/LzmaDecoder.cs @@ -1,4 +1,6 @@ using System; +using System.IO; +using SharpCompress.Compressor.LZMA.LZ; using SharpCompress.Compressor.LZMA.RangeCoder; namespace SharpCompress.Compressor.LZMA @@ -9,10 +11,10 @@ namespace SharpCompress.Compressor.LZMA { 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 readonly BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; + private readonly BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; private BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); - private uint m_NumPosStates = 0; + private uint m_NumPosStates; public void Create(uint numPosStates) { @@ -39,19 +41,20 @@ namespace SharpCompress.Compressor.LZMA public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) { if (m_Choice.Decode(rangeDecoder) == 0) + { return m_LowCoder[posState].Decode(rangeDecoder); + } + uint symbol = Base.kNumLowLenSymbols; + if (m_Choice2.Decode(rangeDecoder) == 0) + { + symbol += m_MidCoder[posState].Decode(rangeDecoder); + } else { - uint symbol = Base.kNumLowLenSymbols; - if (m_Choice2.Decode(rangeDecoder) == 0) - symbol += m_MidCoder[posState].Decode(rangeDecoder); - else - { - symbol += Base.kNumMidLenSymbols; - symbol += m_HighCoder.Decode(rangeDecoder); - } - return symbol; + symbol += Base.kNumMidLenSymbols; + symbol += m_HighCoder.Decode(rangeDecoder); } + return symbol; } } @@ -68,15 +71,21 @@ namespace SharpCompress.Compressor.LZMA public void Init() { - for (int i = 0; i < 0x300; i++) m_Decoders[i].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) @@ -84,18 +93,21 @@ 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; if (matchBit != bit) { while (symbol < 0x100) + { symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); + } break; } - } while (symbol < 0x100); - return (byte) symbol; + } + while (symbol < 0x100); + return (byte)symbol; } } @@ -108,26 +120,32 @@ namespace SharpCompress.Compressor.LZMA { 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 Decoder2[numStates]; for (uint i = 0; i < numStates; i++) + { m_Coders[i].Create(); + } } 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(); + } } private uint GetState(uint pos, byte prevByte) { - return ((pos & m_PosMask) << m_NumPrevBits) + (uint) (prevByte >> (8 - m_NumPrevBits)); + return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) @@ -139,26 +157,26 @@ namespace SharpCompress.Compressor.LZMA { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } - }; + } - private LZ.OutWindow m_OutWindow; + private OutWindow m_OutWindow; - 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]; + private readonly BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + private readonly BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; + private readonly BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; + private readonly BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; + private readonly BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; + private readonly BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - private BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; - private BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; + private readonly BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; + private readonly BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; private BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); - private LenDecoder m_LenDecoder = new LenDecoder(); - private LenDecoder m_RepLenDecoder = new LenDecoder(); + private readonly LenDecoder m_LenDecoder = new LenDecoder(); + private readonly LenDecoder m_RepLenDecoder = new LenDecoder(); - private LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); + private readonly LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); private int m_DictionarySize; @@ -171,14 +189,18 @@ namespace SharpCompress.Compressor.LZMA { m_DictionarySize = -1; for (int i = 0; i < Base.kNumLenToPosStates; i++) + { m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); + } } private void CreateDictionary() { if (m_DictionarySize < 0) + { throw new InvalidParamException(); - m_OutWindow = new LZ.OutWindow(); + } + m_OutWindow = new OutWindow(); int blockSize = Math.Max(m_DictionarySize, (1 << 12)); m_OutWindow.Create(blockSize); } @@ -186,17 +208,23 @@ namespace SharpCompress.Compressor.LZMA private void SetLiteralProperties(int lp, int lc) { if (lp > 8) + { throw new InvalidParamException(); + } if (lc > 8) + { throw new InvalidParamException(); + } m_LiteralDecoder.Create(lp, lc); } 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; @@ -221,10 +249,15 @@ namespace SharpCompress.Compressor.LZMA m_LiteralDecoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) + { m_PosSlotDecoder[i].Init(); + } + // m_PosSpecDecoder.Init(); for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) + { m_PosDecoders[i].Init(); + } m_LenDecoder.Init(); m_RepLenDecoder.Init(); @@ -237,16 +270,22 @@ namespace SharpCompress.Compressor.LZMA rep3 = 0; } - public void Code(System.IO.Stream inStream, System.IO.Stream outStream, + public void Code(Stream inStream, Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress) { if (m_OutWindow == null) + { CreateDictionary(); + } m_OutWindow.Init(outStream); if (outSize > 0) + { m_OutWindow.SetLimit(outSize); + } else + { m_OutWindow.SetLimit(Int64.MaxValue - m_OutWindow.Total); + } RangeCoder.Decoder rangeDecoder = new RangeCoder.Decoder(); rangeDecoder.Init(inStream); @@ -257,13 +296,17 @@ namespace SharpCompress.Compressor.LZMA rangeDecoder.ReleaseStream(); if (!rangeDecoder.IsFinished || (inSize > 0 && rangeDecoder.Total != inSize)) + { throw new DataErrorException(); + } if (m_OutWindow.HasPending) + { throw new DataErrorException(); + } m_OutWindow = null; } - internal bool Code(int dictionarySize, LZ.OutWindow outWindow, RangeCoder.Decoder rangeDecoder) + internal bool Code(int dictionarySize, OutWindow outWindow, RangeCoder.Decoder rangeDecoder) { int dictionarySizeCheck = Math.Max(dictionarySize, 1); @@ -271,17 +314,21 @@ 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(); } @@ -294,10 +341,10 @@ namespace SharpCompress.Compressor.LZMA { if ( m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode( - rangeDecoder) == 0) + rangeDecoder) == 0) { state.UpdateShortRep(); - outWindow.PutByte(outWindow.GetByte((int) rep0)); + outWindow.PutByte(outWindow.GetByte((int)rep0)); continue; } } @@ -311,7 +358,9 @@ namespace SharpCompress.Compressor.LZMA else { if (m_IsRepG2Decoders[state.Index].Decode(rangeDecoder) == 0) + { distance = rep2; + } else { distance = rep3; @@ -335,28 +384,34 @@ 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); + } else { rep0 += (rangeDecoder.DecodeDirectBits( - numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); + numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(rangeDecoder); } } else + { rep0 = posSlot; + } } if (rep0 >= outWindow.Total || rep0 >= dictionarySizeCheck) { if (rep0 == 0xFFFFFFFF) + { return true; + } throw new DataErrorException(); } - outWindow.CopyBlock((int) rep0, (int) len); + outWindow.CopyBlock((int)rep0, (int)len); } } return false; @@ -365,13 +420,17 @@ namespace SharpCompress.Compressor.LZMA public void SetDecoderProperties(byte[] properties) { 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); SetPosBitsProperties(pb); Init(); @@ -379,14 +438,18 @@ 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); + } } } - public void Train(System.IO.Stream stream) + public void Train(Stream stream) { if (m_OutWindow == null) + { CreateDictionary(); + } m_OutWindow.Train(stream); } diff --git a/src/SharpCompress/Compressor/LZMA/LzmaEncoder.cs b/src/SharpCompress/Compressor/LZMA/LzmaEncoder.cs index 4cd528ba..830a9b99 100644 --- a/src/SharpCompress/Compressor/LZMA/LzmaEncoder.cs +++ b/src/SharpCompress/Compressor/LZMA/LzmaEncoder.cs @@ -1,4 +1,6 @@ using System; +using System.IO; +using SharpCompress.Compressor.LZMA.LZ; using SharpCompress.Compressor.LZMA.RangeCoder; namespace SharpCompress.Compressor.LZMA @@ -8,12 +10,12 @@ namespace SharpCompress.Compressor.LZMA private enum EMatchFinderType { BT2, - BT4, - }; + BT4 + } private const UInt32 kIfinityPrice = 0xFFFFFFF; - private static Byte[] g_FastPos = new Byte[1 << 11]; + private static readonly Byte[] g_FastPos = new Byte[1 << 11]; static Encoder() { @@ -23,40 +25,52 @@ 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; + } } } 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); } 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); } private Base.State _state = new Base.State(); private Byte _previousByte; - private UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; + private readonly UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; private void BaseInit() { _state.Init(); _previousByte = 0; for (UInt32 i = 0; i < Base.kNumRepDistances; i++) + { _repDistances[i] = 0; + } } private const int kDefaultDictionaryLogSize = 22; @@ -75,7 +89,10 @@ namespace SharpCompress.Compressor.LZMA public void Init() { - for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); + for (int i = 0; i < 0x300; i++) + { + m_Encoders[i].Init(); + } } public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol) @@ -83,7 +100,7 @@ namespace SharpCompress.Compressor.LZMA 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; } @@ -95,11 +112,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); } @@ -117,8 +134,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) @@ -130,7 +147,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; } @@ -146,43 +163,49 @@ namespace SharpCompress.Compressor.LZMA 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(); + } } 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))]; } } private class LenEncoder { - 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); + private BitEncoder _choice = new BitEncoder(); + private BitEncoder _choice2 = new BitEncoder(); + private readonly BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; + private readonly BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; + private BitTreeEncoder _highCoder = new BitTreeEncoder(Base.kNumHighLenBits); public LenEncoder() { for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) { - _lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits); - _midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits); + _lowCoder[posState] = new BitTreeEncoder(Base.kNumLowLenBits); + _midCoder[posState] = new BitTreeEncoder(Base.kNumMidLenBits); } } @@ -232,27 +255,33 @@ namespace SharpCompress.Compressor.LZMA for (i = 0; i < Base.kNumLowLenSymbols; i++) { if (i >= numSymbols) + { return; + } prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); } for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) { if (i >= numSymbols) + { return; + } prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); } for (; i < numSymbols; i++) + { prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); + } } - }; + } private const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; private class LenPriceTableEncoder : LenEncoder { - private UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; + private readonly UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; private UInt32 _tableSize; - private UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; + private readonly UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; public void SetTableSize(UInt32 tableSize) { @@ -261,26 +290,30 @@ namespace SharpCompress.Compressor.LZMA public UInt32 GetPrice(UInt32 symbol, UInt32 posState) { - return _prices[posState*Base.kNumLenSymbols + symbol]; + return _prices[posState * Base.kNumLenSymbols + symbol]; } private void UpdateTable(UInt32 posState) { - SetPrices(posState, _tableSize, _prices, posState*Base.kNumLenSymbols); + SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); _counters[posState] = _tableSize; } public void UpdateTables(UInt32 numPosStates) { for (UInt32 posState = 0; posState < numPosStates; posState++) + { UpdateTable(posState); + } } public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) { base.Encode(rangeEncoder, symbol, posState); if (--_counters[posState] == 0) + { UpdateTable(posState); + } } } @@ -322,36 +355,36 @@ namespace SharpCompress.Compressor.LZMA { return (BackPrev == 0); } - }; + } - private Optimal[] _optimum = new Optimal[kNumOpts]; - private LZ.BinTree _matchFinder = null; - private RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); + private readonly Optimal[] _optimum = new Optimal[kNumOpts]; + private BinTree _matchFinder; + private readonly RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); - private RangeCoder.BitEncoder[] _isMatch = - new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + private readonly BitEncoder[] _isMatch = + new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - 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]; + private readonly BitEncoder[] _isRep = new BitEncoder[Base.kNumStates]; + private readonly BitEncoder[] _isRepG0 = new BitEncoder[Base.kNumStates]; + private readonly BitEncoder[] _isRepG1 = new BitEncoder[Base.kNumStates]; + private readonly BitEncoder[] _isRepG2 = new BitEncoder[Base.kNumStates]; - private RangeCoder.BitEncoder[] _isRep0Long = - new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + private readonly BitEncoder[] _isRep0Long = + new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - private RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates]; + private readonly BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[Base.kNumLenToPosStates]; - private RangeCoder.BitEncoder[] _posEncoders = - new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; + private readonly BitEncoder[] _posEncoders = + new BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - private RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits); + private BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.kNumAlignBits); - private LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); - private LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); + private readonly LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); + private readonly LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); - private LiteralEncoder _literalEncoder = new LiteralEncoder(); + private readonly LiteralEncoder _literalEncoder = new LiteralEncoder(); - private UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen*2 + 2]; + private readonly UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2]; private UInt32 _numFastBytes = kNumFastBytesDefault; private UInt32 _longestMatchLength; @@ -364,16 +397,16 @@ namespace SharpCompress.Compressor.LZMA private bool _longestMatchWasFound; - 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 readonly UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; + private readonly UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; + private readonly UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; private UInt32 _alignPriceCount; - private UInt32 _distTableSize = (kDefaultDictionaryLogSize*2); + private UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2); private int _posStateBits = 2; private UInt32 _posStateMask = (4 - 1); - private int _numLiteralPosStateBits = 0; + private int _numLiteralPosStateBits; private int _numLiteralContextBits = 3; private UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); @@ -382,10 +415,10 @@ namespace SharpCompress.Compressor.LZMA private Int64 nowPos64; private bool _finished; - private System.IO.Stream _inStream; + private Stream _inStream; private EMatchFinderType _matchFinderType = EMatchFinderType.BT4; - private bool _writeEndMark = false; + private bool _writeEndMark; private bool _needReleaseMFStream; private bool _processingMode; @@ -394,17 +427,21 @@ namespace SharpCompress.Compressor.LZMA { if (_matchFinder == null) { - LZ.BinTree bt = new LZ.BinTree(); + BinTree bt = new BinTree(); int numHashBytes = 4; if (_matchFinderType == EMatchFinderType.BT2) + { numHashBytes = 2; + } bt.SetType(numHashBytes); _matchFinder = bt; } _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) + { return; + } _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1 + kNumOpts); _dictionarySizePrev = _dictionarySize; _numFastBytesPrev = _numFastBytes; @@ -413,9 +450,13 @@ namespace SharpCompress.Compressor.LZMA public Encoder() { for (int i = 0; i < kNumOpts; i++) + { _optimum[i] = new Optimal(); + } for (int i = 0; i < Base.kNumLenToPosStates; i++) - _posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits); + { + _posSlotEncoder[i] = new BitTreeEncoder(Base.kNumPosSlotBits); + } } private void SetWriteEndMarkerMode(bool writeEndMarker) @@ -444,12 +485,16 @@ namespace SharpCompress.Compressor.LZMA } _literalEncoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) + { _posSlotEncoder[i].Init(); + } 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(); @@ -467,13 +512,14 @@ namespace SharpCompress.Compressor.LZMA { lenRes = _matchDistances[numDistancePairs - 2]; if (lenRes == _numFastBytes) - lenRes += _matchFinder.GetMatchLen((int) lenRes - 1, _matchDistances[numDistancePairs - 1], + { + lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1], Base.kMatchMaxLen - lenRes); + } } _additionalOffset++; } - private void MovePos(UInt32 num) { if (num > 0) @@ -501,7 +547,9 @@ namespace SharpCompress.Compressor.LZMA { price = _isRepG0[state.Index].GetPrice1(); if (repIndex == 1) + { price += _isRepG1[state.Index].GetPrice0(); + } else { price += _isRepG1[state.Index].GetPrice1(); @@ -522,10 +570,14 @@ namespace SharpCompress.Compressor.LZMA 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]; + } return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); } @@ -556,15 +608,15 @@ 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; } - private UInt32[] reps = new UInt32[Base.kNumRepDistances]; - private UInt32[] repLens = new UInt32[Base.kNumRepDistances]; - + private readonly UInt32[] reps = new UInt32[Base.kNumRepDistances]; + private readonly UInt32[] repLens = new UInt32[Base.kNumRepDistances]; private UInt32 GetOptimum(UInt32 position, out UInt32 backRes) { @@ -596,7 +648,9 @@ namespace SharpCompress.Compressor.LZMA return 1; } if (numAvailableBytes > Base.kMatchMaxLen) + { numAvailableBytes = Base.kMatchMaxLen; + } UInt32 repMaxIndex = 0; UInt32 i; @@ -605,7 +659,9 @@ namespace SharpCompress.Compressor.LZMA reps[i] = _repDistances[i]; repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); if (repLens[i] > repLens[repMaxIndex]) + { repMaxIndex = i; + } } if (repLens[repMaxIndex] >= _numFastBytes) { @@ -623,11 +679,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 = 0xFFFFFFFF; return 1; } @@ -670,13 +726,18 @@ 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++) { UInt32 repLen = repLens[i]; if (repLen < 2) + { continue; + } UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState); do { @@ -689,7 +750,8 @@ namespace SharpCompress.Compressor.LZMA optimum.BackPrev = i; optimum.Prev1IsChar = false; } - } while (--repLen >= 2); + } + while (--repLen >= 2); } UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); @@ -699,7 +761,9 @@ namespace SharpCompress.Compressor.LZMA { UInt32 offs = 0; while (len > _matchDistances[offs]) + { offs += 2; + } for (;; len++) { UInt32 distance = _matchDistances[offs + 1]; @@ -716,7 +780,9 @@ namespace SharpCompress.Compressor.LZMA { offs += 2; if (offs == numDistancePairs) + { break; + } } } } @@ -727,7 +793,9 @@ namespace SharpCompress.Compressor.LZMA { cur++; if (cur == lenEnd) + { return Backward(out backRes, cur); + } UInt32 newLen; ReadMatchDistances(out newLen, out numDistancePairs); if (newLen >= _numFastBytes) @@ -747,22 +815,34 @@ namespace SharpCompress.Compressor.LZMA { state = _optimum[_optimum[cur].PosPrev2].State; if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) + { state.UpdateRep(); + } else + { state.UpdateMatch(); + } } else + { state = _optimum[posPrev].State; + } state.UpdateChar(); } else + { state = _optimum[posPrev].State; + } if (posPrev == cur - 1) { if (_optimum[cur].IsShortRep()) + { state.UpdateShortRep(); + } else + { state.UpdateChar(); + } } else { @@ -777,9 +857,13 @@ namespace SharpCompress.Compressor.LZMA { pos = _optimum[cur].BackPrev; if (pos < Base.kNumRepDistances) + { state.UpdateRep(); + } else + { state.UpdateMatch(); + } } Optimal opt = _optimum[posPrev]; if (pos < Base.kNumRepDistances) @@ -829,14 +913,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); + GetPrice(!state.IsCharState(), matchByte, currentByte); Optimal nextOptimum = _optimum[cur + 1]; @@ -870,9 +954,13 @@ namespace SharpCompress.Compressor.LZMA numAvailableBytes = numAvailableBytesFull; if (numAvailableBytes < 2) + { continue; + } if (numAvailableBytes > _numFastBytes) + { numAvailableBytes = _numFastBytes; + } if (!nextIsChar && matchByte != currentByte) { // try Literal + rep0 @@ -890,9 +978,11 @@ namespace SharpCompress.Compressor.LZMA { UInt32 offset = cur + 1 + lenTest2; while (lenEnd < offset) + { _optimum[++lenEnd].Price = kIfinityPrice; + } UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( - 0, lenTest2, state2, posStateNext); + 0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[offset]; if (curAndLenPrice < optimum.Price) { @@ -912,12 +1002,16 @@ namespace SharpCompress.Compressor.LZMA { UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); if (lenTest < 2) + { continue; + } UInt32 lenTestTemp = lenTest; do { while (lenEnd < cur + lenTest) + { _optimum[++lenEnd].Price = kIfinityPrice; + } UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) @@ -927,17 +1021,20 @@ namespace SharpCompress.Compressor.LZMA optimum.BackPrev = repIndex; optimum.Prev1IsChar = false; } - } while (--lenTest >= 2); + } + while (--lenTest >= 2); lenTest = lenTestTemp; if (repIndex == 0) + { startLen = lenTest + 1; + } // if (_maxMode) 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; @@ -947,12 +1044,11 @@ namespace SharpCompress.Compressor.LZMA repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte((Int32) lenTest - 1 - 1)) + _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)) .GetPrice(true, _matchFinder.GetIndexByte( - (Int32) - ((Int32) lenTest - 1 - (Int32) (reps[repIndex] + 1))), - _matchFinder.GetIndexByte((Int32) lenTest - 1)); + (Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1)), + _matchFinder.GetIndexByte((Int32)lenTest - 1)); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; UInt32 nextMatchPrice = curAndLenCharPrice + @@ -964,7 +1060,9 @@ 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); Optimal optimum = _optimum[cur + offset]; @@ -986,7 +1084,10 @@ namespace SharpCompress.Compressor.LZMA if (newLen > numAvailableBytes) { newLen = numAvailableBytes; - for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; + for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) + { + ; + } _matchDistances[numDistancePairs] = newLen; numDistancePairs += 2; } @@ -994,11 +1095,15 @@ namespace SharpCompress.Compressor.LZMA { normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0(); while (lenEnd < cur + newLen) + { _optimum[++lenEnd].Price = kIfinityPrice; + } UInt32 offs = 0; while (startLen > _matchDistances[offs]) + { offs += 2; + } for (UInt32 lenTest = startLen;; lenTest++) { @@ -1018,7 +1123,7 @@ 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; @@ -1026,29 +1131,31 @@ namespace SharpCompress.Compressor.LZMA UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = curAndLenPrice + _isMatch[ - (state2.Index << Base.kNumPosStatesBitsMax) + - posStateNext].GetPrice0() + + (state2.Index << Base.kNumPosStatesBitsMax) + + posStateNext].GetPrice0() + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte( - (Int32) lenTest - 1 - 1)) + (Int32)lenTest - 1 - 1)) . - GetPrice(true, - _matchFinder.GetIndexByte( - (Int32) lenTest - - (Int32) (curBack + 1) - 1), - _matchFinder.GetIndexByte( - (Int32) lenTest - 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(); + (state2.Index << Base.kNumPosStatesBitsMax) + + posStateNext].GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); UInt32 offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) + { _optimum[++lenEnd].Price = kIfinityPrice; + } curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) @@ -1065,7 +1172,9 @@ namespace SharpCompress.Compressor.LZMA } offs += 2; if (offs == numDistancePairs) + { break; + } } } } @@ -1075,13 +1184,15 @@ namespace SharpCompress.Compressor.LZMA 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)); } private void WriteEndMarker(UInt32 posState) { if (!_writeEndMark) + { return; + } _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1); _isRep[_state.Index].Encode(_rangeEncoder, 0); @@ -1092,7 +1203,7 @@ 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); } @@ -1119,19 +1230,24 @@ namespace SharpCompress.Compressor.LZMA } if (_finished) + { return; + } _finished = true; - Int64 progressPosValuePrev = nowPos64; if (nowPos64 == 0) { if (_trainSize > 0) { for (; _trainSize > 0 && (!_processingMode || !_matchFinder.IsDataStarved); _trainSize--) + { _matchFinder.Skip(1); + } if (_trainSize == 0) + { _previousByte = _matchFinder.GetIndexByte(-1); + } } if (_processingMode && _matchFinder.IsDataStarved) { @@ -1140,16 +1256,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++; @@ -1161,7 +1277,7 @@ namespace SharpCompress.Compressor.LZMA } if (_matchFinder.GetNumAvailableBytes() == 0) { - Flush((UInt32) nowPos64); + Flush((UInt32)nowPos64); return; } while (true) @@ -1173,23 +1289,25 @@ 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)); + _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset)); subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); } else + { subCoder.Encode(_rangeEncoder, curByte); + } _previousByte = curByte; _state.UpdateChar(); } @@ -1203,15 +1321,21 @@ namespace SharpCompress.Compressor.LZMA { _isRepG0[_state.Index].Encode(_rangeEncoder, 0); if (len == 1) + { _isRep0Long[complexState].Encode(_rangeEncoder, 0); + } else + { _isRep0Long[complexState].Encode(_rangeEncoder, 1); + } } else { _isRepG0[_state.Index].Encode(_rangeEncoder, 1); if (pos == 1) + { _isRepG1[_state.Index].Encode(_rangeEncoder, 0); + } else { _isRepG1[_state.Index].Encode(_rangeEncoder, 1); @@ -1219,7 +1343,9 @@ namespace SharpCompress.Compressor.LZMA } } if (len == 1) + { _state.UpdateShortRep(); + } else { _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); @@ -1229,7 +1355,9 @@ namespace SharpCompress.Compressor.LZMA if (pos != 0) { for (UInt32 i = pos; i >= 1; i--) + { _repDistances[i] = _repDistances[i - 1]; + } _repDistances[0] = distance; } } @@ -1245,14 +1373,16 @@ 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); + { + BitTreeEncoder.ReverseEncode(_posEncoders, + baseVal - posSlot - 1, _rangeEncoder, footerBits, + posReduced); + } else { _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, @@ -1263,11 +1393,13 @@ namespace SharpCompress.Compressor.LZMA } UInt32 distance = pos; for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--) + { _repDistances[i] = _repDistances[i - 1]; + } _repDistances[0] = distance; _matchPriceCount++; } - _previousByte = _matchFinder.GetIndexByte((Int32) (len - 1 - _additionalOffset)); + _previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset)); } _additionalOffset -= len; nowPos64 += len; @@ -1275,9 +1407,13 @@ namespace SharpCompress.Compressor.LZMA { // if (!_fastMode) if (_matchPriceCount >= (1 << 7)) + { FillDistancesPrices(); + } if (_alignPriceCount >= Base.kAlignTableSize) + { FillAlignPrices(); + } inSize = nowPos64; outSize = _rangeEncoder.GetProcessedSizeAdd(); if (_processingMode && _matchFinder.IsDataStarved) @@ -1287,7 +1423,7 @@ namespace SharpCompress.Compressor.LZMA } if (_matchFinder.GetNumAvailableBytes() == 0) { - Flush((UInt32) nowPos64); + Flush((UInt32)nowPos64); return; } @@ -1310,7 +1446,7 @@ namespace SharpCompress.Compressor.LZMA } } - private void SetOutStream(System.IO.Stream outStream) + private void SetOutStream(Stream outStream) { _rangeEncoder.SetStream(outStream); } @@ -1326,7 +1462,7 @@ namespace SharpCompress.Compressor.LZMA ReleaseOutStream(); } - public void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream, + public void SetStreams(Stream inStream, Stream outStream, Int64 inSize, Int64 outSize) { _inStream = inStream; @@ -1343,15 +1479,14 @@ 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, + public void Code(Stream inStream, Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress) { _needReleaseMFStream = false; @@ -1366,7 +1501,9 @@ namespace SharpCompress.Compressor.LZMA bool finished; CodeOneBlock(out processedInSize, out processedOutSize, out finished); if (finished) + { return; + } if (progress != null) { progress.SetProgress(processedInSize, processedOutSize); @@ -1379,7 +1516,7 @@ namespace SharpCompress.Compressor.LZMA } } - public long Code(System.IO.Stream inStream, bool final) + public long Code(Stream inStream, bool final) { _matchFinder.SetStream(inStream); _processingMode = !final; @@ -1392,45 +1529,57 @@ namespace SharpCompress.Compressor.LZMA bool finished; CodeOneBlock(out processedInSize, out processedOutSize, out finished); if (finished) + { return processedInSize; + } } } finally { _matchFinder.ReleaseStream(); if (final) + { ReleaseStreams(); + } } } - public void Train(System.IO.Stream trainStream) + public void Train(Stream trainStream) { if (nowPos64 > 0) + { throw new InvalidOperationException(); - _trainSize = (uint) trainStream.Length; + } + _trainSize = (uint)trainStream.Length; if (_trainSize > 0) { _matchFinder.SetStream(trainStream); for (; _trainSize > 0 && !_matchFinder.IsDataStarved; _trainSize--) + { _matchFinder.Skip(1); + } if (_trainSize == 0) + { _previousByte = _matchFinder.GetIndexByte(-1); + } _matchFinder.ReleaseStream(); } } private const int kPropSize = 5; - private Byte[] properties = new Byte[kPropSize]; + private readonly Byte[] properties = new Byte[kPropSize]; - public void WriteCoderProperties(System.IO.Stream outStream) + public void WriteCoderProperties(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); } - private UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; + private readonly UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; private UInt32 _matchPriceCount; private void FillDistancesPrices() @@ -1438,7 +1587,7 @@ namespace SharpCompress.Compressor.LZMA 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); @@ -1447,21 +1596,29 @@ namespace SharpCompress.Compressor.LZMA for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) { UInt32 posSlot; - RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; + BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; UInt32 st = (lenToPosState << Base.kNumPosSlotBits); 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); + 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]; + } for (; i < Base.kNumFullDistances; i++) + { _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; + } } _matchPriceCount = 0; } @@ -1469,22 +1626,27 @@ namespace SharpCompress.Compressor.LZMA private void FillAlignPrices() { for (UInt32 i = 0; i < Base.kAlignTableSize; i++) + { _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); + } _alignPriceCount = 0; } - - private static string[] kMatchFinderIDs = - { - "BT2", - "BT4", - }; + private static readonly string[] kMatchFinderIDs = + { + "BT2", + "BT4" + }; private static int FindMatchFinder(string s) { for (int m = 0; m < kMatchFinderIDs.Length; m++) + { if (s == kMatchFinderIDs[m]) + { return m; + } + } return -1; } @@ -1496,106 +1658,136 @@ namespace SharpCompress.Compressor.LZMA switch (propIDs[i]) { case CoderPropID.NumFastBytes: + { + if (!(prop is Int32)) { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 numFastBytes = (Int32) prop; - if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) - throw new InvalidParamException(); - _numFastBytes = (UInt32) numFastBytes; - break; + throw new InvalidParamException(); } + Int32 numFastBytes = (Int32)prop; + if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) + { + throw new InvalidParamException(); + } + _numFastBytes = (UInt32)numFastBytes; + break; + } case CoderPropID.Algorithm: - { - /* - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 maximize = (Int32)prop; - _fastMode = (maximize == 0); - _maxMode = (maximize >= 2); - */ - break; - } + { + /* + if (!(prop is Int32)) + throw new InvalidParamException(); + Int32 maximize = (Int32)prop; + _fastMode = (maximize == 0); + _maxMode = (maximize >= 2); + */ + break; + } case CoderPropID.MatchFinder: + { + if (!(prop is String)) { - if (!(prop is String)) - throw new InvalidParamException(); - EMatchFinderType matchFinderIndexPrev = _matchFinderType; - int m = FindMatchFinder(((string) prop).ToUpper()); - if (m < 0) - throw new InvalidParamException(); - _matchFinderType = (EMatchFinderType) m; - if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) - { - _dictionarySizePrev = 0xFFFFFFFF; - _matchFinder = null; - } - break; + throw new InvalidParamException(); } + EMatchFinderType matchFinderIndexPrev = _matchFinderType; + int m = FindMatchFinder(((string)prop).ToUpper()); + if (m < 0) + { + throw new InvalidParamException(); + } + _matchFinderType = (EMatchFinderType)m; + if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) + { + _dictionarySizePrev = 0xFFFFFFFF; + _matchFinder = null; + } + break; + } case CoderPropID.DictionarySize: + { + const int kDicLogSizeMaxCompress = 30; + if (!(prop is Int32)) { - 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; - int dicLogSize; - for (dicLogSize = 0; dicLogSize < (UInt32) kDicLogSizeMaxCompress; dicLogSize++) - if (dictionarySize <= ((UInt32) (1) << dicLogSize)) - break; - _distTableSize = (UInt32) dicLogSize*2; - break; + throw new InvalidParamException(); } + ; + 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)) + { + break; + } + } + _distTableSize = (UInt32)dicLogSize * 2; + break; + } case CoderPropID.PosStateBits: + { + if (!(prop is Int32)) { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32) prop; - if (v < 0 || v > (UInt32) Base.kNumPosStatesBitsEncodingMax) - throw new InvalidParamException(); - _posStateBits = (int) v; - _posStateMask = (((UInt32) 1) << (int) _posStateBits) - 1; - break; + throw new InvalidParamException(); } + Int32 v = (Int32)prop; + if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax) + { + throw new InvalidParamException(); + } + _posStateBits = v; + _posStateMask = (((UInt32)1) << _posStateBits) - 1; + break; + } case CoderPropID.LitPosBits: + { + if (!(prop is Int32)) { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32) prop; - if (v < 0 || v > (UInt32) Base.kNumLitPosStatesBitsEncodingMax) - throw new InvalidParamException(); - _numLiteralPosStateBits = (int) v; - break; + throw new InvalidParamException(); } + Int32 v = (Int32)prop; + if (v < 0 || v > Base.kNumLitPosStatesBitsEncodingMax) + { + throw new InvalidParamException(); + } + _numLiteralPosStateBits = v; + break; + } case CoderPropID.LitContextBits: + { + if (!(prop is Int32)) { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32) prop; - if (v < 0 || v > (UInt32) Base.kNumLitContextBitsMax) - throw new InvalidParamException(); - ; - _numLiteralContextBits = (int) v; - break; + throw new InvalidParamException(); } + Int32 v = (Int32)prop; + if (v < 0 || v > Base.kNumLitContextBitsMax) + { + throw new InvalidParamException(); + } + ; + _numLiteralContextBits = v; + break; + } case CoderPropID.EndMarker: + { + if (!(prop is Boolean)) { - if (!(prop is Boolean)) - throw new InvalidParamException(); - SetWriteEndMarkerMode((Boolean) prop); - break; + throw new InvalidParamException(); } + SetWriteEndMarkerMode((Boolean)prop); + break; + } default: throw new InvalidParamException(); } } } - private uint _trainSize = 0; + private uint _trainSize; public void SetTrainSize(uint trainSize) { diff --git a/src/SharpCompress/Compressor/LZMA/LzmaEncoderProperties.cs b/src/SharpCompress/Compressor/LZMA/LzmaEncoderProperties.cs index a34c3e9d..2cd2c26d 100644 --- a/src/SharpCompress/Compressor/LZMA/LzmaEncoderProperties.cs +++ b/src/SharpCompress/Compressor/LZMA/LzmaEncoderProperties.cs @@ -28,28 +28,28 @@ int algorithm = 2; string mf = "bt4"; - propIDs = new CoderPropID[] - { - CoderPropID.DictionarySize, - CoderPropID.PosStateBits, - CoderPropID.LitContextBits, - CoderPropID.LitPosBits, - CoderPropID.Algorithm, - CoderPropID.NumFastBytes, - CoderPropID.MatchFinder, - CoderPropID.EndMarker - }; + propIDs = new[] + { + 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/src/SharpCompress/Compressor/LZMA/LzmaStream.cs b/src/SharpCompress/Compressor/LZMA/LzmaStream.cs index 0b622321..ab434163 100644 --- a/src/SharpCompress/Compressor/LZMA/LzmaStream.cs +++ b/src/SharpCompress/Compressor/LZMA/LzmaStream.cs @@ -7,29 +7,28 @@ namespace SharpCompress.Compressor.LZMA { public class LzmaStream : Stream { - private Stream inputStream; - private long inputSize; - private long outputSize; + private readonly Stream inputStream; + private readonly long inputSize; + private readonly long outputSize; - private int dictionarySize; - private OutWindow outWindow = new OutWindow(); - private RangeCoder.Decoder rangeDecoder = new RangeCoder.Decoder(); + private readonly int dictionarySize; + private readonly OutWindow outWindow = new OutWindow(); + private readonly RangeCoder.Decoder rangeDecoder = new RangeCoder.Decoder(); private Decoder decoder; - private long position = 0; - private bool endReached = false; + private long position; + private bool endReached; private long availableBytes; private long rangeDecoderLimit; - private long inputPosition = 0; + private long inputPosition; // LZMA2 - private bool isLZMA2; - private bool uncompressedChunk = false; + private readonly bool isLZMA2; + private bool uncompressedChunk; private bool needDictReset = true; private bool needProps = true; - private byte[] props = new byte[5]; - private Encoder encoder; + private readonly Encoder encoder; private bool isDisposed; public LzmaStream(byte[] properties, Stream inputStream) @@ -60,13 +59,15 @@ namespace SharpCompress.Compressor.LZMA dictionarySize = DataConverter.LittleEndian.GetInt32(properties, 1); outWindow.Create(dictionarySize); if (presetDictionary != null) + { outWindow.Train(presetDictionary); + } rangeDecoder.Init(inputStream); decoder = new Decoder(); decoder.SetDecoderProperties(properties); - props = properties; + Properties = properties; availableBytes = outputSize < 0 ? long.MaxValue : outputSize; rangeDecoderLimit = inputSize; @@ -83,7 +84,7 @@ namespace SharpCompress.Compressor.LZMA needDictReset = false; } - props = new byte[1]; + Properties = new byte[1]; availableBytes = 0; } } @@ -100,33 +101,28 @@ namespace SharpCompress.Compressor.LZMA endReached = true; if (isLZMA2) + { throw new NotImplementedException(); + } encoder = new Encoder(); encoder.SetCoderProperties(properties.propIDs, properties.properties); MemoryStream propStream = new MemoryStream(5); encoder.WriteCoderProperties(propStream); - props = propStream.ToArray(); + Properties = propStream.ToArray(); encoder.SetStreams(null, outputStream, -1, -1); if (presetDictionary != null) + { encoder.Train(presetDictionary); + } } - public override bool CanRead - { - get { return encoder == null; } - } + public override bool CanRead { get { return encoder == null; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return encoder != null; } - } + public override bool CanWrite { get { return encoder != null; } } public override void Flush() { @@ -153,21 +149,16 @@ namespace SharpCompress.Compressor.LZMA base.Dispose(disposing); } - public override long Length - { - get { return position + availableBytes; } - } + public override long Length { get { return position + availableBytes; } } - public override long Position - { - get { return position; } - set { throw new NotSupportedException(); } - } + public override long Position { get { return position; } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { if (endReached) + { return 0; + } int total = 0; while (total < count) @@ -175,16 +166,24 @@ namespace SharpCompress.Compressor.LZMA if (availableBytes == 0) { if (isLZMA2) + { decodeChunkHeader(); + } else + { endReached = true; + } if (endReached) + { break; + } } int toProcess = count - total; if (toProcess > availableBytes) + { toProcess = (int)availableBytes; + } outWindow.SetLimit(toProcess); if (uncompressedChunk) @@ -207,19 +206,27 @@ namespace SharpCompress.Compressor.LZMA { rangeDecoder.ReleaseStream(); if (!rangeDecoder.IsFinished || (rangeDecoderLimit >= 0 && rangeDecoder.Total != rangeDecoderLimit)) + { throw new DataErrorException(); + } inputPosition += rangeDecoder.Total; if (outWindow.HasPending) + { throw new DataErrorException(); + } } } if (endReached) { if (inputSize >= 0 && inputPosition != inputSize) + { throw new DataErrorException(); + } if (outputSize >= 0 && position != outputSize) + { throw new DataErrorException(); + } } return total; @@ -243,7 +250,9 @@ namespace SharpCompress.Compressor.LZMA outWindow.Reset(); } else if (needDictReset) + { throw new DataErrorException(); + } if (control >= 0x80) { @@ -259,24 +268,28 @@ namespace SharpCompress.Compressor.LZMA if (control >= 0xC0) { needProps = false; - props[0] = (byte)inputStream.ReadByte(); + Properties[0] = (byte)inputStream.ReadByte(); inputPosition++; decoder = new Decoder(); - decoder.SetDecoderProperties(props); + decoder.SetDecoderProperties(Properties); } else if (needProps) + { throw new DataErrorException(); + } else if (control >= 0xA0) { decoder = new Decoder(); - decoder.SetDecoderProperties(props); + decoder.SetDecoderProperties(Properties); } rangeDecoder.Init(inputStream); } else if (control > 0x02) + { throw new DataErrorException(); + } else { uncompressedChunk = true; @@ -298,12 +311,11 @@ namespace SharpCompress.Compressor.LZMA public override void Write(byte[] buffer, int offset, int count) { if (encoder != null) + { position = encoder.Code(new MemoryStream(buffer, offset, count), false); + } } - public byte[] Properties - { - get { return props; } - } + public byte[] Properties { get; } = new byte[5]; } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoder.cs b/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoder.cs index 77e401c7..eb74cd31 100644 --- a/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoder.cs +++ b/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoder.cs @@ -1,4 +1,5 @@ using System; +using System.IO; namespace SharpCompress.Compressor.LZMA.RangeCoder { @@ -6,7 +7,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { public const uint kTopValue = (1 << 24); - private System.IO.Stream Stream; + private Stream Stream; public UInt64 Low; public uint Range; @@ -15,7 +16,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder //long StartPosition; - public void SetStream(System.IO.Stream stream) + public void SetStream(Stream stream) { Stream = stream; } @@ -38,7 +39,9 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void FlushData() { for (int i = 0; i < 5; i++) + { ShiftLow(); + } } public void FlushStream() @@ -53,7 +56,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,18 +67,19 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void ShiftLow() { - if ((uint) Low < (uint) 0xFF000000 || (uint) (Low >> 32) == 1) + if ((uint)Low < 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) @@ -84,7 +88,9 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { Range >>= 1; if (((v >> i) & 1) == 1) + { Low += Range; + } if (Range < kTopValue) { Range <<= 8; @@ -95,9 +101,11 @@ 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 { Low += newBound; @@ -113,6 +121,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public long GetProcessedSizeAdd() { return -1; + //return _cacheSize + Stream.Position - StartPosition + 4; // (long)Stream.GetProcessedSize(); } @@ -122,12 +131,13 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { public const uint kTopValue = (1 << 24); public uint Range; - public uint Code = 0; + public uint Code; + // public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16); - public System.IO.Stream Stream; + public Stream Stream; public long Total; - public void Init(System.IO.Stream stream) + public void Init(Stream stream) { // Stream.Init(stream); Stream = stream; @@ -135,7 +145,9 @@ 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; } @@ -154,7 +166,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { while (Range < kTopValue) { - Code = (Code << 8) | (byte) Stream.ReadByte(); + Code = (Code << 8) | (byte)Stream.ReadByte(); Range <<= 8; Total++; } @@ -164,7 +176,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { if (Range < kTopValue) { - Code = (Code << 8) | (byte) Stream.ReadByte(); + Code = (Code << 8) | (byte)Stream.ReadByte(); Range <<= 8; Total++; } @@ -172,12 +184,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(); } @@ -204,7 +216,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder if (range < kTopValue) { - code = (code << 8) | (byte) Stream.ReadByte(); + code = (code << 8) | (byte)Stream.ReadByte(); range <<= 8; Total++; } @@ -216,7 +228,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) { @@ -233,10 +245,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder return symbol; } - public bool IsFinished - { - get { return Code == 0; } - } + public bool IsFinished { get { return Code == 0; } } // ulong GetProcessedSize() {return Stream.GetProcessedSize(); } } diff --git a/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBit.cs b/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBit.cs index 8af6185d..4a961118 100644 --- a/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBit.cs +++ b/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBit.cs @@ -20,16 +20,20 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void UpdateModel(uint symbol) { if (symbol == 0) + { Prob += (kBitModelTotal - Prob) >> kNumMoveBits; + } else + { Prob -= (Prob) >> kNumMoveBits; + } } public void Encode(Encoder encoder, uint symbol) { // 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; @@ -48,24 +52,26 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder } } - private static UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits]; + private static readonly UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits]; static BitEncoder() { 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) + + { + 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() @@ -90,9 +96,13 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void UpdateModel(int numMoveBits, uint symbol) { if (symbol == 0) + { Prob += (kBitModelTotal - Prob) >> numMoveBits; + } else + { Prob -= (Prob) >> numMoveBits; + } } public void Init() @@ -100,34 +110,31 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder Prob = kBitModelTotal >> 1; } - public uint Decode(RangeCoder.Decoder rangeDecoder) + public uint Decode(Decoder rangeDecoder) { - uint newBound = (uint) (rangeDecoder.Range >> kNumBitModelTotalBits)*(uint) Prob; + uint newBound = (rangeDecoder.Range >> kNumBitModelTotalBits) * 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++; } return 0; } - else + rangeDecoder.Range -= newBound; + rangeDecoder.Code -= newBound; + Prob -= (Prob) >> kNumMoveBits; + if (rangeDecoder.Range < Decoder.kTopValue) { - rangeDecoder.Range -= newBound; - rangeDecoder.Code -= newBound; - Prob -= (Prob) >> kNumMoveBits; - if (rangeDecoder.Range < Decoder.kTopValue) - { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte) rangeDecoder.Stream.ReadByte(); - rangeDecoder.Range <<= 8; - rangeDecoder.Total++; - } - return 1; + rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); + rangeDecoder.Range <<= 8; + rangeDecoder.Total++; } + return 1; } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBitTree.cs b/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBitTree.cs index a1856b94..de02f472 100644 --- a/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBitTree.cs +++ b/src/SharpCompress/Compressor/LZMA/RangeCoder/RangeCoderBitTree.cs @@ -4,8 +4,8 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder { internal struct BitTreeEncoder { - private BitEncoder[] Models; - private int NumBitLevels; + private readonly BitEncoder[] Models; + private readonly int NumBitLevels; public BitTreeEncoder(int numBitLevels) { @@ -16,7 +16,9 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void Init() { for (uint i = 1; i < (1 << NumBitLevels); i++) + { Models[i].Init(); + } } public void Encode(Encoder rangeEncoder, UInt32 symbol) @@ -102,8 +104,8 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder internal struct BitTreeDecoder { - private BitDecoder[] Models; - private int NumBitLevels; + private readonly BitDecoder[] Models; + private readonly int NumBitLevels; public BitTreeDecoder(int numBitLevels) { @@ -114,18 +116,22 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder public void Init() { for (uint i = 1; i < (1 << NumBitLevels); i++) + { Models[i].Init(); + } } - public uint Decode(RangeCoder.Decoder rangeDecoder) + public uint Decode(Decoder rangeDecoder) { 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) + public uint ReverseDecode(Decoder rangeDecoder) { uint m = 1; uint symbol = 0; @@ -140,7 +146,7 @@ namespace SharpCompress.Compressor.LZMA.RangeCoder } public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, - RangeCoder.Decoder rangeDecoder, int NumBitLevels) + Decoder rangeDecoder, int NumBitLevels) { uint m = 1; uint symbol = 0; diff --git a/src/SharpCompress/Compressor/LZMA/Registry.cs b/src/SharpCompress/Compressor/LZMA/Registry.cs index 9f0c6723..72aac872 100644 --- a/src/SharpCompress/Compressor/LZMA/Registry.cs +++ b/src/SharpCompress/Compressor/LZMA/Registry.cs @@ -28,7 +28,9 @@ namespace SharpCompress.Compressor.LZMA { case k_Copy: if (info != null) + { throw new NotSupportedException(); + } return inStreams.Single(); case k_LZMA: case k_LZMA2: diff --git a/src/SharpCompress/Compressor/LZMA/Utilites/CrcBuilderStream.cs b/src/SharpCompress/Compressor/LZMA/Utilites/CrcBuilderStream.cs index 37fcce80..ff6ed899 100644 --- a/src/SharpCompress/Compressor/LZMA/Utilites/CrcBuilderStream.cs +++ b/src/SharpCompress/Compressor/LZMA/Utilites/CrcBuilderStream.cs @@ -5,8 +5,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites { internal class CrcBuilderStream : Stream { - private long mProcessed; - private Stream mTarget; + private readonly Stream mTarget; private uint mCRC; private bool mFinished; private bool isDisposed; @@ -28,10 +27,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites base.Dispose(disposing); } - public long Processed - { - get { return mProcessed; } - } + public long Processed { get; private set; } public uint Finish() { @@ -44,35 +40,19 @@ namespace SharpCompress.Compressor.LZMA.Utilites return mCRC; } - public override bool CanRead - { - get { return false; } - } + public override bool CanRead { get { return false; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return true; } - } + public override bool CanWrite { get { return true; } } public override void Flush() { } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -92,9 +72,11 @@ namespace SharpCompress.Compressor.LZMA.Utilites public override void Write(byte[] buffer, int offset, int count) { if (mFinished) + { throw new InvalidOperationException("CRC calculation has been finished."); + } - mProcessed += count; + Processed += count; mCRC = CRC.Update(mCRC, buffer, offset, count); mTarget.Write(buffer, offset, count); } @@ -102,8 +84,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites internal class ReadingCrcBuilderStream : Stream { - private long mProcessed; - private Stream mSource; + private readonly Stream mSource; private uint mCRC; private bool mFinished; @@ -118,7 +99,9 @@ namespace SharpCompress.Compressor.LZMA.Utilites try { if (disposing) + { mSource.Dispose(); + } } finally { @@ -126,10 +109,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites } } - public long Processed - { - get { return mProcessed; } - } + public long Processed { get; private set; } public uint Finish() { @@ -142,36 +122,20 @@ namespace SharpCompress.Compressor.LZMA.Utilites return mCRC; } - public override bool CanRead - { - get { return mSource.CanRead; } - } + public override bool CanRead { get { return mSource.CanRead; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { throw new NotSupportedException(); } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -180,7 +144,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites int read = mSource.Read(buffer, offset, count); if (read > 0) { - mProcessed += read; + Processed += read; mCRC = CRC.Update(mCRC, buffer, offset, read); return read; } diff --git a/src/SharpCompress/Compressor/LZMA/Utilites/CrcCheckStream.cs b/src/SharpCompress/Compressor/LZMA/Utilites/CrcCheckStream.cs index 2f641175..693cba8e 100644 --- a/src/SharpCompress/Compressor/LZMA/Utilites/CrcCheckStream.cs +++ b/src/SharpCompress/Compressor/LZMA/Utilites/CrcCheckStream.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.IO; namespace SharpCompress.Compressor.LZMA.Utilites @@ -9,7 +10,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites private uint mCurrentCRC; private bool mClosed; - private long[] mBytes = new long[256]; + private readonly long[] mBytes = new long[256]; private long mLength; public CrcCheckStream(uint crc) @@ -21,7 +22,9 @@ namespace SharpCompress.Compressor.LZMA.Utilites protected override void Dispose(bool disposing) { if (mCurrentCRC != mExpectedCRC) + { throw new InvalidOperationException(); + } try { if (disposing && !mClosed) @@ -30,24 +33,26 @@ namespace SharpCompress.Compressor.LZMA.Utilites mCurrentCRC = CRC.Finish(mCurrentCRC); #if DEBUG if (mCurrentCRC == mExpectedCRC) - System.Diagnostics.Debug.WriteLine("CRC ok: " + mExpectedCRC.ToString("x8")); + { + Debug.WriteLine("CRC ok: " + mExpectedCRC.ToString("x8")); + } else { - System.Diagnostics.Debugger.Break(); - System.Diagnostics.Debug.WriteLine("bad CRC"); + Debugger.Break(); + Debug.WriteLine("bad CRC"); } - double lengthInv = 1.0/mLength; + double lengthInv = 1.0 / mLength; double entropy = 0; for (int i = 0; i < 256; i++) { 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) + "%"); + Debug.WriteLine("entropy: " + (int)(entropy * 100) + "%"); #endif } } @@ -57,35 +62,19 @@ namespace SharpCompress.Compressor.LZMA.Utilites } } - public override bool CanRead - { - get { return false; } - } + public override bool CanRead { get { return false; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return true; } - } + public override bool CanWrite { get { return true; } } public override void Flush() { } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -106,7 +95,9 @@ namespace SharpCompress.Compressor.LZMA.Utilites { mLength += count; for (int i = 0; i < count; i++) + { mBytes[buffer[offset + i]]++; + } mCurrentCRC = CRC.Update(mCurrentCRC, buffer, offset, count); } diff --git a/src/SharpCompress/Compressor/LZMA/Utilites/Utils.cs b/src/SharpCompress/Compressor/LZMA/Utilites/Utils.cs index 36fb2d09..4b8dac76 100644 --- a/src/SharpCompress/Compressor/LZMA/Utilites/Utils.cs +++ b/src/SharpCompress/Compressor/LZMA/Utilites/Utils.cs @@ -33,7 +33,7 @@ namespace SharpCompress.Compressor.LZMA.Utilites Comment = 22, EncodedHeader = 23, StartPos = 24, - Dummy = 25, + Dummy = 25 #endregion } @@ -46,7 +46,9 @@ namespace SharpCompress.Compressor.LZMA.Utilites if (!expression) { if (Debugger.IsAttached) + { Debugger.Break(); + } throw new Exception("Assertion failed."); } @@ -55,22 +57,32 @@ namespace SharpCompress.Compressor.LZMA.Utilites public static void ReadExact(this Stream stream, byte[] buffer, int offset, int length) { if (stream == null) + { throw new ArgumentNullException("stream"); + } if (buffer == null) + { throw new ArgumentNullException("buffer"); + } if (offset < 0 || offset > buffer.Length) + { throw new ArgumentOutOfRangeException("offset"); + } if (length < 0 || length > buffer.Length - offset) + { throw new ArgumentOutOfRangeException("length"); + } while (length > 0) { int fetched = stream.Read(buffer, offset, length); if (fetched <= 0) + { throw new EndOfStreamException(); + } offset += fetched; length -= fetched; diff --git a/src/SharpCompress/Compressor/PPMd/H/FreqData.cs b/src/SharpCompress/Compressor/PPMd/H/FreqData.cs index c31dfc3b..7fa6d006 100644 --- a/src/SharpCompress/Compressor/PPMd/H/FreqData.cs +++ b/src/SharpCompress/Compressor/PPMd/H/FreqData.cs @@ -1,3 +1,4 @@ +using System; using System.Text; using SharpCompress.Converter; @@ -18,12 +19,7 @@ namespace SharpCompress.Compressor.PPMd.H { } - internal int SummFreq - { - get { return DataConverter.LittleEndian.GetInt16(Memory, Address) & 0xffff; } - - set { DataConverter.LittleEndian.PutBytes(Memory, Address, (short)value); } - } + internal int SummFreq { get { return DataConverter.LittleEndian.GetInt16(Memory, Address) & 0xffff; } set { DataConverter.LittleEndian.PutBytes(Memory, Address, (short)value); } } internal FreqData Initialize(byte[] mem) { @@ -52,7 +48,7 @@ namespace SharpCompress.Compressor.PPMd.H DataConverter.LittleEndian.PutBytes(Memory, Address + 2, state); } - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("FreqData["); diff --git a/src/SharpCompress/Compressor/PPMd/H/ModelPPM.cs b/src/SharpCompress/Compressor/PPMd/H/ModelPPM.cs index 4d2b76f5..82a9804f 100644 --- a/src/SharpCompress/Compressor/PPMd/H/ModelPPM.cs +++ b/src/SharpCompress/Compressor/PPMd/H/ModelPPM.cs @@ -1,6 +1,8 @@ -using System.Text; +using System; using System.IO; +using System.Text; using SharpCompress.Compressor.Rar; +using Decoder = SharpCompress.Compressor.LZMA.RangeCoder.Decoder; namespace SharpCompress.Compressor.PPMd.H { @@ -18,92 +20,35 @@ namespace SharpCompress.Compressor.PPMd.H } } - public SubAllocator SubAlloc - { - get { return subAlloc; } - } + public SubAllocator SubAlloc { get; } = new SubAllocator(); - public virtual SEE2Context DummySEE2Cont - { - get { return dummySEE2Cont; } - } + public virtual SEE2Context DummySEE2Cont { get { return dummySEE2Cont; } } - public virtual int InitRL - { - get { return initRL; } - } + public virtual int InitRL { get { return initRL; } } - public virtual int EscCount - { - get { return escCount; } + public virtual int EscCount { get { return escCount; } set { escCount = value & 0xff; } } - set { this.escCount = value & 0xff; } - } + public virtual int[] CharMask { get { return charMask; } } - public virtual int[] CharMask - { - get { return charMask; } - } + public virtual int NumMasked { get { return numMasked; } set { numMasked = value; } } - public virtual int NumMasked - { - get { return numMasked; } + public virtual int PrevSuccess { get { return prevSuccess; } set { prevSuccess = value & 0xff; } } - set { this.numMasked = value; } - } + public virtual int InitEsc { get { return initEsc; } set { initEsc = value; } } - public virtual int PrevSuccess - { - get { return prevSuccess; } + public virtual int RunLength { get { return runLength; } set { runLength = value; } } - set { this.prevSuccess = value & 0xff; } - } + public virtual int HiBitsFlag { get { return hiBitsFlag; } set { hiBitsFlag = value & 0xff; } } - public virtual int InitEsc - { - get { return initEsc; } + public virtual int[][] BinSumm { get { return binSumm; } } - set { this.initEsc = value; } - } + internal RangeCoder Coder { get; private set; } - public virtual int RunLength - { - get { return runLength; } + internal State FoundState { get; private set; } - set { this.runLength = value; } - } + public virtual byte[] Heap { get { return SubAlloc.Heap; } } - public virtual int HiBitsFlag - { - get { return hiBitsFlag; } - - set { this.hiBitsFlag = value & 0xff; } - } - - public virtual int[][] BinSumm - { - get { return binSumm; } - } - - internal RangeCoder Coder - { - get { return coder; } - } - - internal State FoundState - { - get { return foundState; } - } - - public virtual byte[] Heap - { - get { return subAlloc.Heap; } - } - - public virtual int OrderFall - { - get { return orderFall; } - } + public virtual int OrderFall { get { return orderFall; } } public const int MAX_O = 64; /* maximum allowed model order */ @@ -122,7 +67,7 @@ namespace SharpCompress.Compressor.PPMd.H public const int MAX_FREQ = 124; - private SEE2Context[][] SEE2Cont = new SEE2Context[25][]; + private readonly SEE2Context[][] SEE2Cont = new SEE2Context[25][]; private SEE2Context dummySEE2Cont; @@ -130,67 +75,72 @@ namespace SharpCompress.Compressor.PPMd.H private PPMContext maxContext; - private State foundState; // found next state transition - private int numMasked, initEsc, orderFall, maxOrder, runLength, initRL; - private int[] charMask = new int[256]; + private readonly int[] charMask = new int[256]; - private int[] NS2Indx = new int[256]; + private readonly int[] NS2Indx = new int[256]; - private int[] NS2BSIndx = new int[256]; + private readonly int[] NS2BSIndx = new int[256]; - private int[] HB2Flag = new int[256]; + private readonly int[] HB2Flag = new int[256]; // byte EscCount, PrevSuccess, HiBitsFlag; private int escCount, prevSuccess, hiBitsFlag; - private int[][] binSumm = new int[128][]; // binary SEE-contexts + private readonly int[][] binSumm = new int[128][]; // binary SEE-contexts - private RangeCoder coder; - - private SubAllocator subAlloc = new SubAllocator(); - - private static int[] InitBinEsc = new int[] {0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; + private static readonly int[] InitBinEsc = {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'" - private State tempState1 = new State(null); + private readonly State tempState1 = new State(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempState2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private State tempState2 = new State(null); + private readonly State tempState2 = new State(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempState3 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private State tempState3 = new State(null); + private readonly State tempState3 = new State(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempState4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private State tempState4 = new State(null); + private readonly State tempState4 = new State(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempStateRef1 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private StateRef tempStateRef1 = new StateRef(); + private readonly StateRef tempStateRef1 = new StateRef(); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempStateRef2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private StateRef tempStateRef2 = new StateRef(); + private readonly StateRef tempStateRef2 = new StateRef(); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempPPMContext1 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private PPMContext tempPPMContext1 = new PPMContext(null); + private readonly PPMContext tempPPMContext1 = new PPMContext(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempPPMContext2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private PPMContext tempPPMContext2 = new PPMContext(null); + private readonly PPMContext tempPPMContext2 = new PPMContext(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempPPMContext3 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private PPMContext tempPPMContext3 = new PPMContext(null); + private readonly PPMContext tempPPMContext3 = new PPMContext(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempPPMContext4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private PPMContext tempPPMContext4 = new PPMContext(null); + private readonly PPMContext tempPPMContext4 = new PPMContext(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'ps '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] ps = new int[MAX_O]; + private readonly int[] ps = new int[MAX_O]; public ModelPPM() { InitBlock(); minContext = null; maxContext = null; + //medContext = null; } private void restartModelRare() { Utility.Fill(charMask, 0); - subAlloc.initSubAllocator(); + SubAlloc.initSubAllocator(); initRL = -(maxOrder < 12 ? maxOrder : 12) - 1; - int addr = subAlloc.allocContext(); + int addr = SubAlloc.allocContext(); minContext.Address = addr; maxContext.Address = addr; minContext.setSuffix(0); @@ -198,17 +148,17 @@ namespace SharpCompress.Compressor.PPMd.H minContext.NumStats = 256; minContext.FreqData.SummFreq = minContext.NumStats + 1; - addr = subAlloc.allocUnits(256/2); - foundState.Address = addr; + addr = SubAlloc.allocUnits(256 / 2); + FoundState.Address = addr; minContext.FreqData.SetStats(addr); - State state = new State(subAlloc.Heap); + State state = new State(SubAlloc.Heap); addr = minContext.FreqData.GetStats(); runLength = initRL; 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); @@ -220,7 +170,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); } } } @@ -228,7 +178,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); } } } @@ -237,8 +187,9 @@ namespace SharpCompress.Compressor.PPMd.H { int i, k, m, Step; escCount = 1; - this.maxOrder = MaxOrder; + maxOrder = MaxOrder; restartModelRare(); + // Bug Fixed NS2BSIndx[0] = 0; NS2BSIndx[1] = 2; @@ -292,7 +243,7 @@ namespace SharpCompress.Compressor.PPMd.H } else { - if (subAlloc.GetAllocatedMemory() == 0) + if (SubAlloc.GetAllocatedMemory() == 0) { return (false); } @@ -302,24 +253,25 @@ namespace SharpCompress.Compressor.PPMd.H escChar = unpackRead.Char; unpackRead.PpmEscChar = escChar; } - coder = new RangeCoder(unpackRead); + Coder = new RangeCoder(unpackRead); if (reset) { MaxOrder = (MaxOrder & 0x1f) + 1; if (MaxOrder > 16) { - MaxOrder = 16 + (MaxOrder - 16)*3; + MaxOrder = 16 + (MaxOrder - 16) * 3; } if (MaxOrder == 1) { - subAlloc.stopSubAllocator(); + SubAlloc.stopSubAllocator(); return (false); } - subAlloc.startSubAllocator((MaxMB + 1) << 20); + SubAlloc.startSubAllocator((MaxMB + 1) << 20); minContext = new PPMContext(Heap); + //medContext = new PPMContext(Heap); maxContext = new PPMContext(Heap); - foundState = new State(Heap); + FoundState = new State(Heap); dummySEE2Cont = new SEE2Context(); for (int i = 0; i < 25; i++) { @@ -338,15 +290,15 @@ namespace SharpCompress.Compressor.PPMd.H // Debug //subAlloc.dumpHeap(); - if (minContext.Address <= subAlloc.PText || minContext.Address > subAlloc.HeapEnd) + if (minContext.Address <= SubAlloc.PText || minContext.Address > SubAlloc.HeapEnd) { return (-1); } 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); } @@ -359,43 +311,45 @@ namespace SharpCompress.Compressor.PPMd.H { minContext.decodeBinSymbol(this); } - coder.Decode(); - while (foundState.Address == 0) + Coder.Decode(); + while (FoundState.Address == 0) { - coder.AriDecNormalize(); + Coder.AriDecNormalize(); do { orderFall++; minContext.Address = minContext.getSuffix(); // =MinContext->Suffix; - if (minContext.Address <= subAlloc.PText || minContext.Address > subAlloc.HeapEnd) + if (minContext.Address <= SubAlloc.PText || minContext.Address > SubAlloc.HeapEnd) { return (-1); } - } while (minContext.NumStats == numMasked); + } + while (minContext.NumStats == numMasked); if (!minContext.decodeSymbol2(this)) { return (-1); } - coder.Decode(); + Coder.Decode(); } - int Symbol = foundState.Symbol; - if ((orderFall == 0) && foundState.GetSuccessor() > subAlloc.PText) + int Symbol = FoundState.Symbol; + if ((orderFall == 0) && FoundState.GetSuccessor() > SubAlloc.PText) { // MinContext=MaxContext=FoundState->Successor; - int addr = foundState.GetSuccessor(); + int addr = FoundState.GetSuccessor(); minContext.Address = addr; maxContext.Address = addr; } else { updateModel(); + //this.foundState.Address=foundState.Address);//TODO just 4 debugging if (escCount == 0) { clearMask(); } } - coder.AriDecNormalize(); // ARI_DEC_NORMALIZE(Coder.code,Coder.low,Coder.range,Coder.UnpackRead); + Coder.AriDecNormalize(); // ARI_DEC_NORMALIZE(Coder.code,Coder.low,Coder.range,Coder.UnpackRead); return (Symbol); } @@ -439,7 +393,7 @@ namespace SharpCompress.Compressor.PPMd.H PPMContext pc = tempPPMContext1.Initialize(Heap); pc.Address = minContext.Address; PPMContext upBranch = tempPPMContext2.Initialize(Heap); - upBranch.Address = foundState.GetSuccessor(); + upBranch.Address = FoundState.GetSuccessor(); // STATE * p, * ps[MAX_O], ** pps=ps; State p = tempState2.Initialize(Heap); @@ -449,7 +403,7 @@ namespace SharpCompress.Compressor.PPMd.H if (!Skip) { - ps[pps++] = foundState.Address; // *pps++ = FoundState; + ps[pps++] = FoundState.Address; // *pps++ = FoundState; if (pc.getSuffix() == 0) { noLoop = true; @@ -472,12 +426,13 @@ namespace SharpCompress.Compressor.PPMd.H if (pc.NumStats != 1) { p.Address = pc.FreqData.GetStats(); // p=pc->U.Stats - if (p.Symbol != foundState.Symbol) + if (p.Symbol != FoundState.Symbol) { do { p.IncrementAddress(); - } while (p.Symbol != foundState.Symbol); + } + while (p.Symbol != FoundState.Symbol); } } else @@ -492,19 +447,21 @@ namespace SharpCompress.Compressor.PPMd.H break; } ps[pps++] = p.Address; - } while (pc.getSuffix() != 0); + } + while (pc.getSuffix() != 0); } // NO_LOOP: if (pps == 0) { return pc.Address; } upState.Symbol = Heap[upBranch.Address]; // UpState.Symbol=*(byte*) + // UpBranch; // UpState.Successor=(PPM_CONTEXT*) (((byte*) UpBranch)+1); upState.SetSuccessor(upBranch.Address + 1); //TODO check if +1 necessary if (pc.NumStats != 1) { - if (pc.Address <= subAlloc.PText) + if (pc.Address <= SubAlloc.PText) { return (0); } @@ -514,12 +471,14 @@ 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 { @@ -534,7 +493,8 @@ namespace SharpCompress.Compressor.PPMd.H { return 0; } - } while (pps != 0); + } + while (pps != 0); return pc.Address; } @@ -549,7 +509,7 @@ namespace SharpCompress.Compressor.PPMd.H //System.out.println("ModelPPM.updateModel()"); // STATE fs = *FoundState, *p = NULL; StateRef fs = tempStateRef1; - fs.Values = foundState; + fs.Values = FoundState; State p = tempState3.Initialize(Heap); State tempState = tempState4.Initialize(Heap); @@ -558,7 +518,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) { @@ -568,7 +528,8 @@ 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) { @@ -593,9 +554,9 @@ namespace SharpCompress.Compressor.PPMd.H } if (orderFall == 0) { - foundState.SetSuccessor(createSuccessors(true, p)); - minContext.Address = foundState.GetSuccessor(); - maxContext.Address = foundState.GetSuccessor(); + FoundState.SetSuccessor(createSuccessors(true, p)); + minContext.Address = FoundState.GetSuccessor(); + maxContext.Address = FoundState.GetSuccessor(); if (minContext.Address == 0) { updateModelRestart(); @@ -603,19 +564,20 @@ namespace SharpCompress.Compressor.PPMd.H } return; } - subAlloc.Heap[subAlloc.PText] = (byte) fs.Symbol; - subAlloc.incPText(); - successor.Address = subAlloc.PText; - if (subAlloc.PText >= subAlloc.FakeUnitsStart) + SubAlloc.Heap[SubAlloc.PText] = (byte)fs.Symbol; + SubAlloc.incPText(); + successor.Address = SubAlloc.PText; + if (SubAlloc.PText >= SubAlloc.FakeUnitsStart) { updateModelRestart(); return; } + // // Debug // subAlloc.dumpHeap(); if (fs.GetSuccessor() != 0) { - if (fs.GetSuccessor() <= subAlloc.PText) + if (fs.GetSuccessor() <= SubAlloc.PText) { fs.SetSuccessor(createSuccessors(false, p)); if (fs.GetSuccessor() == 0) @@ -629,15 +591,16 @@ namespace SharpCompress.Compressor.PPMd.H successor.Address = fs.GetSuccessor(); if (maxContext.Address != minContext.Address) { - subAlloc.decPText(1); + SubAlloc.decPText(1); } } } else { - foundState.SetSuccessor(successor.Address); + FoundState.SetSuccessor(successor.Address); fs.SetSuccessor(minContext); } + // // Debug // subAlloc.dumpHeap(); ns = minContext.NumStats; @@ -649,24 +612,25 @@ namespace SharpCompress.Compressor.PPMd.H if ((ns1 & 1) == 0) { //System.out.println(ns1); - pc.FreqData.SetStats(subAlloc.expandUnits(pc.FreqData.GetStats(), Utility.URShift(ns1, 1))); + pc.FreqData.SetStats(SubAlloc.expandUnits(pc.FreqData.GetStats(), Utility.URShift(ns1, 1))); if (pc.FreqData.GetStats() == 0) { updateModelRestart(); return; } } + // bug fixed // 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 { - p.Address = subAlloc.allocUnits(1); + p.Address = SubAlloc.allocUnits(1); if (p.Address == 0) { updateModelRestart(); @@ -674,7 +638,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); } @@ -684,19 +648,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; @@ -706,6 +670,7 @@ namespace SharpCompress.Compressor.PPMd.H int address = fs.GetSuccessor(); maxContext.Address = address; minContext.Address = address; + //TODO-----debug // int pos = minContext.getFreqData().getStats(); // State a = new State(getHeap()); @@ -713,11 +678,10 @@ namespace SharpCompress.Compressor.PPMd.H // pos+=State.size; // a.Address=pos); //--dbg end - return; } // Debug - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("ModelPPM["); @@ -738,11 +702,11 @@ namespace SharpCompress.Compressor.PPMd.H buffer.Append("\n prevSuccess="); buffer.Append(prevSuccess); buffer.Append("\n foundState="); - buffer.Append(foundState); + buffer.Append(FoundState); buffer.Append("\n coder="); - buffer.Append(coder); + buffer.Append(Coder); buffer.Append("\n subAlloc="); - buffer.Append(subAlloc); + buffer.Append(SubAlloc); buffer.Append("\n]"); return buffer.ToString(); } @@ -755,18 +719,21 @@ namespace SharpCompress.Compressor.PPMd.H internal bool decodeInit(Stream stream, int maxOrder, int maxMemory) { if (stream != null) - coder = new RangeCoder(stream); + { + Coder = new RangeCoder(stream); + } if (maxOrder == 1) { - subAlloc.stopSubAllocator(); + SubAlloc.stopSubAllocator(); return (false); } - subAlloc.startSubAllocator(maxMemory); + SubAlloc.startSubAllocator(maxMemory); minContext = new PPMContext(Heap); + //medContext = new PPMContext(Heap); maxContext = new PPMContext(Heap); - foundState = new State(Heap); + FoundState = new State(Heap); dummySEE2Cont = new SEE2Context(); for (int i = 0; i < 25; i++) { @@ -782,17 +749,19 @@ namespace SharpCompress.Compressor.PPMd.H internal void nextContext() { - int addr = foundState.GetSuccessor(); - if (orderFall == 0 && addr > subAlloc.PText) + int addr = FoundState.GetSuccessor(); + if (orderFall == 0 && addr > SubAlloc.PText) { minContext.Address = addr; maxContext.Address = addr; } else + { updateModel(); + } } - public int decodeChar(LZMA.RangeCoder.Decoder decoder) + public int decodeChar(Decoder decoder) { if (minContext.NumStats != 1) { @@ -800,11 +769,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; @@ -817,41 +786,47 @@ 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)); + } + hiBitsFlag = HB2Flag[FoundState.Symbol]; + decoder.Decode((uint)hiCnt, (uint)(minContext.FreqData.SummFreq - hiCnt)); for (i = 0; i < 256; i++) + { charMask[i] = -1; + } charMask[s.Symbol] = 0; i = minContext.NumStats - 1; do { s.DecrementAddress(); charMask[s.Symbol] = 0; - } while (--i > 0); + } + while (--i > 0); } else { State rs = tempState1.Initialize(Heap); rs.Address = minContext.getOneState().Address; - hiBitsFlag = getHB2Flag()[foundState.Symbol]; + hiBitsFlag = getHB2Flag()[FoundState.Symbol]; 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; + FoundState.Address = rs.Address; + symbol = (byte)rs.Symbol; rs.IncrementFreq((rs.Freq < 128) ? 1 : 0); prevSuccess = 1; incRunLength(1); @@ -863,7 +838,9 @@ namespace SharpCompress.Compressor.PPMd.H initEsc = PPMContext.ExpEscape[Utility.URShift(bs, 10)]; int i; for (i = 0; i < 256; i++) + { charMask[i] = -1; + } charMask[rs.Symbol] = 0; prevSuccess = 0; } @@ -878,9 +855,12 @@ namespace SharpCompress.Compressor.PPMd.H { orderFall++; minContext.Address = minContext.getSuffix(); - if (minContext.Address <= subAlloc.PText || minContext.Address > subAlloc.HeapEnd) + 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; @@ -892,11 +872,12 @@ 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) { @@ -904,24 +885,30 @@ namespace SharpCompress.Compressor.PPMd.H 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]) ; + 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/src/SharpCompress/Compressor/PPMd/H/PPMContext.cs b/src/SharpCompress/Compressor/PPMd/H/PPMContext.cs index bdcadc87..94a0b7db 100644 --- a/src/SharpCompress/Compressor/PPMd/H/PPMContext.cs +++ b/src/SharpCompress/Compressor/PPMd/H/PPMContext.cs @@ -1,3 +1,4 @@ +using System; using System.Text; using SharpCompress.Converter; @@ -11,8 +12,8 @@ namespace SharpCompress.Compressor.PPMd.H set { - this.freqData.SummFreq = value.SummFreq; - this.freqData.SetStats(value.GetStats()); + freqData.SummFreq = value.SummFreq; + freqData.SetStats(value.GetStats()); } } @@ -29,10 +30,10 @@ namespace SharpCompress.Compressor.PPMd.H set { - this.numStats = value & 0xffff; + numStats = value & 0xffff; if (Memory != null) { - DataConverter.LittleEndian.PutBytes(Memory, Address, (short) value); + DataConverter.LittleEndian.PutBytes(Memory, Address, (short)value); } } } @@ -50,29 +51,34 @@ namespace SharpCompress.Compressor.PPMd.H // (1==onestate) //UPGRADE_NOTE: Final was removed from the declaration of 'freqData '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private FreqData freqData; // -\ + private readonly FreqData freqData; // -\ // |-> union //UPGRADE_NOTE: Final was removed from the declaration of 'oneState '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private State oneState; // -/ + private readonly State oneState; // -/ 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 = {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'" - private State tempState1 = new State(null); + private readonly State tempState1 = new State(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempState2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private State tempState2 = new State(null); + private readonly State tempState2 = new State(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempState3 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private State tempState3 = new State(null); + private readonly State tempState3 = new State(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempState4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private State tempState4 = new State(null); + private readonly State tempState4 = new State(null); + //UPGRADE_NOTE: Final was removed from the declaration of 'tempState5 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private State tempState5 = new State(null); - private PPMContext tempPPMContext = null; + private readonly State tempState5 = new State(null); + private PPMContext tempPPMContext; + //UPGRADE_NOTE: Final was removed from the declaration of 'ps '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal int[] ps = new int[256]; @@ -160,6 +166,7 @@ namespace SharpCompress.Compressor.PPMd.H internal void rescale(ModelPPM model) { int OldNS = NumStats, i = NumStats - 1, Adder, EscFreq; + // STATE* p1, * p; State p1 = new State(model.Heap); State p = new State(model.Heap); @@ -198,17 +205,20 @@ 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) @@ -216,13 +226,15 @@ namespace SharpCompress.Compressor.PPMd.H StateRef tmp = new StateRef(); temp.Address = freqData.GetStats(); tmp.Values = temp; + // STATE tmp=*U.Stats; do { // 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; @@ -246,7 +258,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; } @@ -287,6 +299,7 @@ namespace SharpCompress.Compressor.PPMd.H model.PrevSuccess = 0; model.FoundState.Address = 0; } + //int a = 0;//TODO just 4 debugging } @@ -319,19 +332,23 @@ namespace SharpCompress.Compressor.PPMd.H State.PPMDSwap(p0, p1); model.FoundState.Address = p1.Address; if (p1.Freq > ModelPPM.MAX_FREQ) + { rescale(model); + } } } 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); if (model.FoundState.Freq > ModelPPM.MAX_FREQ) + { rescale(model); + } } internal bool decodeSymbol2(ModelPPM model) @@ -340,6 +357,7 @@ namespace SharpCompress.Compressor.PPMd.H int hiCnt, i = NumStats - model.NumMasked; SEE2Context psee2c = makeEscFreq2(model, i); RangeCoder coder = model.Coder; + // STATE* ps[256], ** pps=ps, * p=U.Stats-1; State p = tempState1.Initialize(model.Heap); State temp = tempState2.Initialize(model.Heap); @@ -352,10 +370,12 @@ 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) @@ -386,8 +406,9 @@ 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); @@ -419,8 +440,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; @@ -445,8 +466,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; @@ -474,7 +495,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; @@ -487,12 +508,9 @@ namespace SharpCompress.Compressor.PPMd.H coder.SubRange.LowCount = 0; return true; } - else + if (model.FoundState.Address == 0) { - if (model.FoundState.Address == 0) - { - return (false); - } + return (false); } model.PrevSuccess = 0; int numStats = NumStats; @@ -510,7 +528,8 @@ 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); } @@ -521,7 +540,7 @@ namespace SharpCompress.Compressor.PPMd.H return (true); } - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("PPMContext["); @@ -543,7 +562,7 @@ namespace SharpCompress.Compressor.PPMd.H static PPMContext() { - unionSize = System.Math.Max(FreqData.Size, State.Size); + unionSize = Math.Max(FreqData.Size, State.Size); } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/PPMd/H/RangeCoder.cs b/src/SharpCompress/Compressor/PPMd/H/RangeCoder.cs index 39c11897..ffb8c1fc 100644 --- a/src/SharpCompress/Compressor/PPMd/H/RangeCoder.cs +++ b/src/SharpCompress/Compressor/PPMd/H/RangeCoder.cs @@ -1,5 +1,6 @@ -using System.Text; +using System; using System.IO; +using System.Text; using SharpCompress.Compressor.Rar; namespace SharpCompress.Compressor.PPMd.H @@ -12,8 +13,8 @@ namespace SharpCompress.Compressor.PPMd.H // uint low, code, range; private long low, code, range; - private Unpack unpackRead; - private Stream stream; + private readonly Unpack unpackRead; + private readonly Stream stream; internal RangeCoder(Unpack unpackRead) { @@ -29,7 +30,7 @@ namespace SharpCompress.Compressor.PPMd.H private void Init() { - this.SubRange = new SubRange(); + SubRange = new SubRange(); low = code = 0L; range = 0xFFFFffffL; @@ -43,8 +44,8 @@ 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)); } } @@ -53,26 +54,29 @@ namespace SharpCompress.Compressor.PPMd.H get { if (unpackRead != null) + { return (unpackRead.Char); + } if (stream != null) + { return stream.ReadByte(); + } return -1; } } 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() @@ -100,7 +104,7 @@ namespace SharpCompress.Compressor.PPMd.H } // Debug - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("RangeCoder["); @@ -127,29 +131,14 @@ namespace SharpCompress.Compressor.PPMd.H Scale = Scale + dScale; } - internal long HighCount - { - get { return highCount; } + internal long HighCount { get { return highCount; } set { highCount = value & RangeCoder.UintMask; } } - set { this.highCount = value & RangeCoder.UintMask; } - } + internal long LowCount { get { return lowCount & RangeCoder.UintMask; } set { lowCount = value & RangeCoder.UintMask; } } - internal long LowCount - { - get { return lowCount & RangeCoder.UintMask; } - - set { this.lowCount = value & RangeCoder.UintMask; } - } - - internal long Scale - { - get { return scale; } - - set { this.scale = value & RangeCoder.UintMask; } - } + internal long Scale { get { return scale; } set { scale = value & RangeCoder.UintMask; } } // Debug - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("SubRange["); diff --git a/src/SharpCompress/Compressor/PPMd/H/RarMemBlock.cs b/src/SharpCompress/Compressor/PPMd/H/RarMemBlock.cs index 09ced607..74ef5b95 100644 --- a/src/SharpCompress/Compressor/PPMd/H/RarMemBlock.cs +++ b/src/SharpCompress/Compressor/PPMd/H/RarMemBlock.cs @@ -28,7 +28,7 @@ namespace SharpCompress.Compressor.PPMd.H set { - this.stamp = value; + stamp = value; if (Memory != null) { DataConverter.LittleEndian.PutBytes(Memory, Address, (short)value); @@ -54,6 +54,7 @@ namespace SharpCompress.Compressor.PPMd.H temp.SetNext(GetNext()); // prev.setNext(next); temp.Address = GetNext(); temp.SetPrev(GetPrev()); // next.setPrev(prev); + // next = -1; // prev = -1; } diff --git a/src/SharpCompress/Compressor/PPMd/H/SEE2Context.cs b/src/SharpCompress/Compressor/PPMd/H/SEE2Context.cs index a5aabe10..c3d2f861 100644 --- a/src/SharpCompress/Compressor/PPMd/H/SEE2Context.cs +++ b/src/SharpCompress/Compressor/PPMd/H/SEE2Context.cs @@ -1,3 +1,4 @@ +using System; using System.Text; namespace SharpCompress.Compressor.PPMd.H @@ -14,26 +15,11 @@ namespace SharpCompress.Compressor.PPMd.H } } - public virtual int Count - { - get { return count; } + public virtual int Count { get { return count; } set { count = value & 0xff; } } - set { this.count = value & 0xff; } - } + public virtual int Shift { get { return shift; } set { shift = value & 0xff; } } - public virtual int Shift - { - get { return shift; } - - set { this.shift = value & 0xff; } - } - - public virtual int Summ - { - get { return summ; } - - set { this.summ = value & 0xffff; } - } + public virtual int Summ { get { return summ; } set { summ = value & 0xffff; } } public const int size = 4; @@ -70,7 +56,7 @@ namespace SharpCompress.Compressor.PPMd.H Summ = Summ + dSumm; } - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("SEE2Context["); diff --git a/src/SharpCompress/Compressor/PPMd/H/State.cs b/src/SharpCompress/Compressor/PPMd/H/State.cs index 56d71d2e..ee10071a 100644 --- a/src/SharpCompress/Compressor/PPMd/H/State.cs +++ b/src/SharpCompress/Compressor/PPMd/H/State.cs @@ -13,19 +13,9 @@ namespace SharpCompress.Compressor.PPMd.H { } - internal int Symbol - { - get { return Memory[Address] & 0xff; } + internal int Symbol { get { return Memory[Address] & 0xff; } set { Memory[Address] = (byte)value; } } - set { Memory[Address] = (byte) value; } - } - - internal int Freq - { - get { return Memory[Address + 1] & 0xff; } - - set { Memory[Address + 1] = (byte) value; } - } + internal int Freq { get { return Memory[Address + 1] & 0xff; } set { Memory[Address + 1] = (byte)value; } } internal State Initialize(byte[] mem) { @@ -34,7 +24,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() @@ -87,7 +77,7 @@ namespace SharpCompress.Compressor.PPMd.H } } - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("State["); diff --git a/src/SharpCompress/Compressor/PPMd/H/StateRef.cs b/src/SharpCompress/Compressor/PPMd/H/StateRef.cs index 4f9b9d75..3c2f1ae1 100644 --- a/src/SharpCompress/Compressor/PPMd/H/StateRef.cs +++ b/src/SharpCompress/Compressor/PPMd/H/StateRef.cs @@ -1,3 +1,4 @@ +using System; using System.Text; namespace SharpCompress.Compressor.PPMd.H @@ -10,19 +11,9 @@ namespace SharpCompress.Compressor.PPMd.H private int successor; // pointer ppmcontext - internal int Symbol - { - get { return symbol; } + internal int Symbol { get { return symbol; } set { symbol = value & 0xff; } } - set { this.symbol = value & 0xff; } - } - - internal int Freq - { - get { return freq; } - - set { this.freq = value & 0xff; } - } + internal int Freq { get { return freq; } set { freq = value & 0xff; } } internal State Values { @@ -34,7 +25,6 @@ namespace SharpCompress.Compressor.PPMd.H } } - public virtual void IncrementFreq(int dFreq) { freq = (freq + dFreq) & 0xff; @@ -60,7 +50,7 @@ namespace SharpCompress.Compressor.PPMd.H this.successor = successor; } - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("State["); diff --git a/src/SharpCompress/Compressor/PPMd/H/SubAllocator.cs b/src/SharpCompress/Compressor/PPMd/H/SubAllocator.cs index 8b5c6e57..360d2277 100644 --- a/src/SharpCompress/Compressor/PPMd/H/SubAllocator.cs +++ b/src/SharpCompress/Compressor/PPMd/H/SubAllocator.cs @@ -5,42 +5,21 @@ namespace SharpCompress.Compressor.PPMd.H { internal class SubAllocator { - public virtual int FakeUnitsStart - { - get { return fakeUnitsStart; } + public virtual int FakeUnitsStart { get { return fakeUnitsStart; } set { fakeUnitsStart = value; } } - set { this.fakeUnitsStart = value; } - } + public virtual int HeapEnd { get { return heapEnd; } } - public virtual int HeapEnd - { - get { return heapEnd; } - } + public virtual int PText { get { return pText; } set { pText = value; } } - public virtual int PText - { - get { return pText; } + public virtual int UnitsStart { get { return unitsStart; } set { unitsStart = value; } } - set { pText = value; } - } - - public virtual int UnitsStart - { - get { return unitsStart; } - - set { this.unitsStart = value; } - } - - public virtual byte[] Heap - { - get { return heap; } - } + public virtual byte[] 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; @@ -54,15 +33,15 @@ namespace SharpCompress.Compressor.PPMd.H private int subAllocatorSize; // byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount; - private int[] indx2Units = new int[N_INDEXES]; - private int[] units2Indx = new int[128]; + private readonly int[] indx2Units = new int[N_INDEXES]; + private readonly int[] units2Indx = new int[128]; private int glueCount; // byte *HeapStart,*LoUnit, *HiUnit; private int heapStart, loUnit, hiUnit; //UPGRADE_NOTE: Final was removed from the declaration of 'freeList '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private RarNode[] freeList = new RarNode[N_INDEXES]; + private readonly RarNode[] freeList = new RarNode[N_INDEXES]; // byte *pText, *UnitsStart,*HeapEnd,*FakeUnitsStart; private int pText, unitsStart, heapEnd, fakeUnitsStart; @@ -74,10 +53,10 @@ namespace SharpCompress.Compressor.PPMd.H private int tempMemBlockPos; // Temp fields - private RarNode tempRarNode = null; - private RarMemBlock tempRarMemBlock1 = null; - private RarMemBlock tempRarMemBlock2 = null; - private RarMemBlock tempRarMemBlock3 = null; + private RarNode tempRarNode; + private RarMemBlock tempRarMemBlock1; + private RarMemBlock tempRarMemBlock2; + private RarMemBlock tempRarMemBlock3; public SubAllocator() { @@ -113,7 +92,7 @@ namespace SharpCompress.Compressor.PPMd.H private int U2B(int NU) { - return UNIT_SIZE*NU; + return UNIT_SIZE * NU; } /* memblockptr */ @@ -141,9 +120,11 @@ namespace SharpCompress.Compressor.PPMd.H if (subAllocatorSize != 0) { subAllocatorSize = 0; + //ArrayFactory.BYTES_FACTORY.recycle(heap); heap = null; heapStart = 1; + // rarfree(HeapStart); // Free temp fields tempRarNode = null; @@ -158,7 +139,6 @@ namespace SharpCompress.Compressor.PPMd.H return subAllocatorSize; } - public virtual bool startSubAllocator(int SASize) { int t = SASize; @@ -167,11 +147,12 @@ 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; @@ -180,8 +161,10 @@ namespace SharpCompress.Compressor.PPMd.H heapStart = 1; heapEnd = heapStart + allocSize - UNIT_SIZE; subAllocatorSize = t; + // Bug fixed freeListPos = heapStart + allocSize; + //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'" //assert(realAllocSize - tempMemBlockPos == RarMemBlock.size): realAllocSize //+ + tempMemBlockPos + + RarMemBlock.size; @@ -236,6 +219,7 @@ namespace SharpCompress.Compressor.PPMd.H p1.Address = MBPtr(p.Address, p.GetNU()); } } + // while ((p=s0.next) != &s0) // Bug fixed p.Address = s0.GetNext(); @@ -273,7 +257,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; @@ -282,7 +266,8 @@ 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; @@ -308,7 +293,9 @@ namespace SharpCompress.Compressor.PPMd.H public virtual int allocContext() { if (hiUnit != loUnit) + { return (hiUnit -= UNIT_SIZE); + } if (freeList[0].GetNext() != 0) { return removeNode(0); @@ -347,6 +334,7 @@ namespace SharpCompress.Compressor.PPMd.H if (freeList[i1].GetNext() != 0) { int ptr = removeNode(i1); + // memcpy(ptr,OldPtr,U2B(NewNU)); // for (int i = 0; i < U2B(NewNU); i++) { // heap[ptr + i] = heap[OldPtr + i]; @@ -355,11 +343,8 @@ namespace SharpCompress.Compressor.PPMd.H insertNode(oldPtr, i0); return ptr; } - else - { - splitBlock(oldPtr, i0, i1); - return oldPtr; - } + splitBlock(oldPtr, i0, i1); + return oldPtr; } public virtual void freeUnits(int ptr, int OldNU) @@ -375,14 +360,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; @@ -414,7 +399,7 @@ namespace SharpCompress.Compressor.PPMd.H private int sizeOfFreeList() { - return freeList.Length*RarNode.size; + return freeList.Length * RarNode.size; } // Debug @@ -436,7 +421,7 @@ namespace SharpCompress.Compressor.PPMd.H // } // Debug - public override System.String ToString() + public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("SubAllocator["); @@ -460,7 +445,7 @@ namespace SharpCompress.Compressor.PPMd.H static SubAllocator() { - UNIT_SIZE = System.Math.Max(PPMContext.size, RarMemBlock.size); + UNIT_SIZE = Math.Max(PPMContext.size, RarMemBlock.size); } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/PPMd/I1/Allocator.cs b/src/SharpCompress/Compressor/PPMd/I1/Allocator.cs index ff50a7bd..5b01956b 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/Allocator.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/Allocator.cs @@ -1,7 +1,3 @@ -#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 @@ -14,13 +10,14 @@ namespace SharpCompress.Compressor.PPMd.I1 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 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 +50,24 @@ 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 +80,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 +100,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 +108,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,7 +126,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public void Start(int allocatorSize) { - uint size = (uint) allocatorSize; + uint size = (uint)allocatorSize; if (AllocatorSize != size) { Stop(); @@ -156,7 +161,9 @@ 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; } @@ -170,14 +177,18 @@ namespace SharpCompress.Compressor.PPMd.I1 { uint index = unitsToIndex[unitCount - 1]; if (MemoryNodes[index].Available) + { 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); } @@ -188,11 +199,14 @@ namespace SharpCompress.Compressor.PPMd.I1 public Pointer AllocateContext() { if (HighUnit != LowUnit) + { return (HighUnit -= UnitSize); - else if (MemoryNodes[0].Available) + } + if (MemoryNodes[0].Available) + { return MemoryNodes[0].Remove(); - else - return AllocateUnitsRare(0); + } + return AllocateUnitsRare(0); } /// @@ -207,7 +221,9 @@ namespace SharpCompress.Compressor.PPMd.I1 uint newIndex = unitsToIndex[oldUnitCount]; if (oldIndex == newIndex) + { return oldPointer; + } Pointer pointer = AllocateUnits(oldUnitCount + 1); @@ -233,7 +249,9 @@ namespace SharpCompress.Compressor.PPMd.I1 uint newIndex = unitsToIndex[newUnitCount - 1]; if (oldIndex == newIndex) + { return oldPointer; + } if (MemoryNodes[newIndex].Available) { @@ -242,11 +260,8 @@ namespace SharpCompress.Compressor.PPMd.I1 MemoryNodes[oldIndex].Insert(oldPointer, indexToUnits[oldIndex]); return pointer; } - else - { - SplitBlock(oldPointer, oldIndex, newIndex); - return oldPointer; - } + SplitBlock(oldPointer, oldIndex, newIndex); + return oldPointer; } /// @@ -279,17 +294,23 @@ 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(); CopyUnits(pointer, oldPointer, unitCount); unitCount = indexToUnits[index]; if (oldPointer != BaseUnit) + { MemoryNodes[index].Insert(oldPointer, unitCount); + } else - BaseUnit += unitCount*UnitSize; + { + BaseUnit += unitCount * UnitSize; + } return pointer; } @@ -319,7 +340,9 @@ namespace SharpCompress.Compressor.PPMd.I1 memoryNode.Unlink(); MemoryNodes[index].Stamp--; if (--counts[index] == 0) + { break; + } } } } @@ -335,7 +358,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { GlueFreeBlocks(); if (MemoryNodes[index].Available) + { return MemoryNodes[index].Remove(); + } } uint oldIndex = index; @@ -344,10 +369,11 @@ 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); + } + while (!MemoryNodes[oldIndex].Available); Pointer allocatedBlock = MemoryNodes[oldIndex].Remove(); SplitBlock(allocatedBlock, oldIndex, index); @@ -356,15 +382,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; } @@ -383,7 +409,9 @@ namespace SharpCompress.Compressor.PPMd.I1 MemoryNode memoryNode2; if (LowUnit != HighUnit) + { LowUnit[0] = 0; + } // Find all unused memory nodes. @@ -415,7 +443,9 @@ namespace SharpCompress.Compressor.PPMd.I1 if (unitCount != 0) { for (; unitCount > 128; unitCount -= 128, memoryNode0 += 128) + { MemoryNodes[IndexCount - 1].Insert(memoryNode0, 128); + } uint index = unitsToIndex[unitCount - 1]; if (indexToUnits[index] != unitCount) @@ -450,7 +480,8 @@ namespace SharpCompress.Compressor.PPMd.I1 target[11] = source[11]; target += UnitSize; source += UnitSize; - } while (--unitCount != 0); + } + while (--unitCount != 0); } #endregion diff --git a/src/SharpCompress/Compressor/PPMd/I1/Coder.cs b/src/SharpCompress/Compressor/PPMd/I1/Coder.cs index 90adb6a8..fe33b205 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/Coder.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/Coder.cs @@ -1,6 +1,5 @@ #region Using -using System; using System.IO; #endregion @@ -35,9 +34,9 @@ namespace SharpCompress.Compressor.PPMd.I1 public void RangeEncoderNormalize(Stream stream) { while ((low ^ (low + range)) < RangeTop || - range < RangeBottom && ((range = (uint) -low & (RangeBottom - 1)) != 0 || true)) + range < RangeBottom && ((range = (uint)-low & (RangeBottom - 1)) != 0 || true)) { - stream.WriteByte((byte) (low >> 24)); + stream.WriteByte((byte)(low >> 24)); range <<= 8; low <<= 8; } @@ -45,13 +44,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; } @@ -59,7 +58,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { for (uint index = 0; index < 4; index++) { - stream.WriteByte((byte) (low >> 24)); + stream.WriteByte((byte)(low >> 24)); low <<= 8; } } @@ -70,15 +69,17 @@ namespace SharpCompress.Compressor.PPMd.I1 code = 0; range = uint.MaxValue; for (uint index = 0; index < 4; index++) - code = (code << 8) | (byte) stream.ReadByte(); + { + code = (code << 8) | (byte)stream.ReadByte(); + } } public void RangeDecoderNormalize(Stream stream) { while ((low ^ (low + range)) < RangeTop || - range < RangeBottom && ((range = (uint) -low & (RangeBottom - 1)) != 0 || true)) + range < RangeBottom && ((range = (uint)-low & (RangeBottom - 1)) != 0 || true)) { - code = (code << 8) | (byte) stream.ReadByte(); + code = (code << 8) | (byte)stream.ReadByte(); range <<= 8; low <<= 8; } @@ -86,17 +87,17 @@ 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; } } diff --git a/src/SharpCompress/Compressor/PPMd/I1/MemoryNode.cs b/src/SharpCompress/Compressor/PPMd/I1/MemoryNode.cs index 8aa440d2..b26d0f79 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/MemoryNode.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/MemoryNode.cs @@ -1,6 +1,6 @@ #region Using -using System; + #endregion @@ -50,15 +50,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { get { - return ((uint) Memory[Address]) | ((uint) Memory[Address + 1]) << 8 | ((uint) Memory[Address + 2]) << 16 | - ((uint) Memory[Address + 3]) << 24; + return Memory[Address] | ((uint)Memory[Address + 1]) << 8 | ((uint)Memory[Address + 2]) << 16 | + ((uint)Memory[Address + 3]) << 24; } set { - Memory[Address] = (byte) value; - Memory[Address + 1] = (byte) (value >> 8); - Memory[Address + 2] = (byte) (value >> 16); - Memory[Address + 3] = (byte) (value >> 24); + Memory[Address] = (byte)value; + Memory[Address + 1] = (byte)(value >> 8); + Memory[Address + 2] = (byte)(value >> 16); + Memory[Address + 3] = (byte)(value >> 24); } } @@ -71,15 +71,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { return new MemoryNode( - ((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | - ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); + 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); } } @@ -90,25 +90,22 @@ namespace SharpCompress.Compressor.PPMd.I1 { get { - return ((uint) Memory[Address + 8]) | ((uint) Memory[Address + 9]) << 8 | - ((uint) Memory[Address + 10]) << 16 | ((uint) Memory[Address + 11]) << 24; + return Memory[Address + 8] | ((uint)Memory[Address + 9]) << 8 | + ((uint)Memory[Address + 10]) << 16 | ((uint)Memory[Address + 11]) << 24; } set { - Memory[Address + 8] = (byte) value; - Memory[Address + 9] = (byte) (value >> 8); - Memory[Address + 10] = (byte) (value >> 16); - Memory[Address + 11] = (byte) (value >> 24); + Memory[Address + 8] = (byte)value; + Memory[Address + 9] = (byte)(value >> 8); + Memory[Address + 10] = (byte)(value >> 16); + Memory[Address + 11] = (byte)(value >> 24); } } /// /// Gets whether there is a next memory node available. /// - public bool Available - { - get { return Next.Address != 0; } - } + public bool Available { get { return Next.Address != 0; } } /// /// Link in the provided memory node. @@ -171,7 +168,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; } @@ -183,7 +180,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static MemoryNode operator +(MemoryNode memoryNode, uint offset) { - memoryNode.Address += offset*Size; + memoryNode.Address += offset * Size; return memoryNode; } @@ -195,7 +192,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; } @@ -207,7 +204,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// public static MemoryNode operator -(MemoryNode memoryNode, uint offset) { - memoryNode.Address -= offset*Size; + memoryNode.Address -= offset * Size; return memoryNode; } @@ -242,7 +239,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { if (obj is MemoryNode) { - MemoryNode memoryNode = (MemoryNode) obj; + MemoryNode memoryNode = (MemoryNode)obj; return memoryNode.Address == Address; } return base.Equals(obj); diff --git a/src/SharpCompress/Compressor/PPMd/I1/Model.cs b/src/SharpCompress/Compressor/PPMd/I1/Model.cs index bffd15c5..cceb7823 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/Model.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/Model.cs @@ -28,13 +28,13 @@ namespace SharpCompress.Compressor.PPMd.I1 private const uint MaximumFrequency = 124; private const uint OrderBound = 9; - private See2Context[,] see2Contexts; - private See2Context emptySee2Context; + private readonly See2Context[,] see2Contexts; + private readonly See2Context emptySee2Context; private PpmContext maximumContext; - 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]; + private readonly ushort[,] binarySummary = new ushort[25, 64]; // binary SEE-contexts + private readonly byte[] numberStatisticsToBinarySummaryIndex = new byte[256]; + private readonly byte[] probabilities = new byte[260]; + private readonly byte[] characterMask = new byte[256]; private byte escapeCount; private int modelOrder; private int orderFall; @@ -50,13 +50,13 @@ namespace SharpCompress.Compressor.PPMd.I1 private Coder Coder; private PpmContext minimumContext; private byte numberStatistics; - private PpmState[] decodeStates = new PpmState[256]; + private readonly PpmState[] decodeStates = new PpmState[256]; private static readonly ushort[] InitialBinaryEscapes = - { - 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, - 0x6051 - }; + { + 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}; @@ -75,12 +75,16 @@ 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). @@ -100,11 +104,13 @@ 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) { @@ -116,17 +122,21 @@ 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(); + } + } // 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); } /// @@ -135,10 +145,14 @@ namespace SharpCompress.Compressor.PPMd.I1 public void Encode(Stream target, Stream source, PpmdProperties properties) { if (target == null) + { throw new ArgumentNullException("target"); + } if (source == null) + { throw new ArgumentNullException("source"); + } EncodeStart(properties); EncodeBlock(target, source, true); @@ -162,7 +176,9 @@ namespace SharpCompress.Compressor.PPMd.I1 int c = source.ReadByte(); if (c < 0 && !final) + { return; + } if (numberStatistics != 0) { @@ -183,13 +199,16 @@ namespace SharpCompress.Compressor.PPMd.I1 orderFall++; minimumContext = minimumContext.Suffix; if (minimumContext == PpmContext.Zero) + { goto StopEncoding; - } while (minimumContext.NumberStatistics == numberMasked); + } + } + while (minimumContext.NumberStatistics == numberMasked); EncodeSymbol2(c, minimumContext); Coder.RangeEncodeSymbol(); } - if (orderFall == 0 && (Pointer) foundState.Successor >= Allocator.BaseUnit) + if (orderFall == 0 && (Pointer)foundState.Successor >= Allocator.BaseUnit) { maximumContext = foundState.Successor; } @@ -197,7 +216,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { UpdateModel(minimumContext); if (escapeCount == 0) + { ClearMask(); + } } Coder.RangeEncoderNormalize(target); @@ -207,25 +228,28 @@ namespace SharpCompress.Compressor.PPMd.I1 Coder.RangeEncoderFlush(target); } - /// /// Dencode (ie. decompress) a given source stream, writing the decoded result to the target stream. /// public void Decode(Stream target, Stream source, PpmdProperties properties) { if (target == null) + { throw new ArgumentNullException("target"); + } if (source == null) + { throw new ArgumentNullException("source"); + } DecodeStart(source, properties); byte[] buffer = new byte[65536]; int read; while ((read = DecodeBlock(source, buffer, 0, buffer.Length)) != 0) + { target.Write(buffer, 0, read); - - return; + } } internal Coder DecodeStart(Stream source, PpmdProperties properties) @@ -242,15 +266,21 @@ namespace SharpCompress.Compressor.PPMd.I1 internal int DecodeBlock(Stream source, byte[] buffer, int offset, int count) { if (minimumContext == PpmContext.Zero) + { return 0; + } int total = 0; while (total < count) { if (numberStatistics != 0) + { DecodeSymbol1(minimumContext); + } else + { DecodeBinarySymbol(minimumContext); + } Coder.RangeRemoveSubrange(); @@ -262,8 +292,11 @@ namespace SharpCompress.Compressor.PPMd.I1 orderFall++; minimumContext = minimumContext.Suffix; if (minimumContext == PpmContext.Zero) + { goto StopDecoding; - } while (minimumContext.NumberStatistics == numberMasked); + } + } + while (minimumContext.NumberStatistics == numberMasked); DecodeSymbol2(minimumContext); Coder.RangeRemoveSubrange(); } @@ -272,7 +305,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; } @@ -280,7 +313,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { UpdateModel(minimumContext); if (escapeCount == 0) + { ClearMask(); + } } minimumContext = maximumContext; @@ -312,7 +347,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { orderFall = this.modelOrder; for (PpmContext context = maximumContext; context.Suffix != PpmContext.Zero; context = context.Suffix) + { orderFall--; + } return; } @@ -328,15 +365,16 @@ 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; } @@ -345,22 +383,34 @@ namespace SharpCompress.Compressor.PPMd.I1 for (int index1 = 0; probability < 25; probability++) { while (probabilities[index1] == probability) + { index1++; + } for (int index2 = 0; index2 < 8; index2++) + { binarySummary[probability, index2] = - (ushort) (BinaryScale - InitialBinaryEscapes[index2]/(index1 + 1)); + (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]; + } + } } probability = 0; for (uint index1 = 0; probability < 24; probability++) { 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); + } } } @@ -382,7 +432,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) { @@ -393,21 +443,22 @@ namespace SharpCompress.Compressor.PPMd.I1 { symbol = state[1].Symbol; state++; - } while (symbol != foundStateSymbol); + } + while (symbol != foundStateSymbol); if (state[0].Frequency >= state[-1].Frequency) { Swap(state[0], state[-1]); 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); } } @@ -415,7 +466,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { foundState.Successor = CreateSuccessors(true, state, minimumContext); if (foundState.Successor == PpmContext.Zero) + { goto RestartModel; + } maximumContext = foundState.Successor; return; } @@ -425,12 +478,16 @@ namespace SharpCompress.Compressor.PPMd.I1 Successor = Allocator.Text; if (Allocator.Text >= Allocator.BaseUnit) + { goto RestartModel; + } if (foundStateSuccessor != PpmContext.Zero) { if (foundStateSuccessor < Allocator.BaseUnit) + { foundStateSuccessor = CreateSuccessors(false, state, minimumContext); + } } else { @@ -438,7 +495,9 @@ namespace SharpCompress.Compressor.PPMd.I1 } if (foundStateSuccessor == PpmContext.Zero) + { goto RestartModel; + } if (--orderFall == 0) { @@ -454,7 +513,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; @@ -464,44 +523,52 @@ namespace SharpCompress.Compressor.PPMd.I1 { state = Allocator.ExpandUnits(currentContext.Statistics, (ns1 + 1) >> 1); if (state == PpmState.Zero) + { goto RestartModel; + } currentContext.Statistics = state; } - currentContext.SummaryFrequency += (ushort) ((3*ns1 + 1 < numberStatistics) ? 1 : 0); + currentContext.SummaryFrequency += (ushort)((3 * ns1 + 1 < numberStatistics) ? 1 : 0); } else { state = Allocator.AllocateUnits(1); if (state == PpmState.Zero) + { 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); + { + state.Frequency = (byte)(MaximumFrequency - 4); + } currentContext.SummaryFrequency = - (ushort) (state.Frequency + initialEscape + ((numberStatistics > 2) ? 1 : 0)); + (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; } @@ -523,7 +590,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { states[stateIndex++] = foundState; if (context.Suffix == PpmContext.Zero) + { goto NoLoop; + } } bool gotoLoopEntry = false; @@ -552,9 +621,10 @@ namespace SharpCompress.Compressor.PPMd.I1 { temporary = state[1].Symbol; state++; - } while (temporary != symbol); + } + 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; } @@ -562,7 +632,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { state = context.FirstState; state.Frequency += - (byte) (((context.Suffix.NumberStatistics == 0) ? 1 : 0) & ((state.Frequency < 24) ? 1 : 0)); + (byte)(((context.Suffix.NumberStatistics == 0) ? 1 : 0) & ((state.Frequency < 24) ? 1 : 0)); } LoopEntry: @@ -572,19 +642,22 @@ namespace SharpCompress.Compressor.PPMd.I1 break; } states[stateIndex++] = state; - } while (context.Suffix != PpmContext.Zero); + } + while (context.Suffix != PpmContext.Zero); 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) { @@ -596,11 +669,12 @@ namespace SharpCompress.Compressor.PPMd.I1 { temporary = state[1].Symbol; state++; - } while (temporary != symbol); + } + 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 { @@ -611,7 +685,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { PpmContext currentContext = Allocator.AllocateContext(); if (currentContext == PpmContext.Zero) + { return PpmContext.Zero; + } currentContext.NumberStatistics = localNumberStatistics; currentContext.Flags = localFlags; currentContext.FirstStateSymbol = localSymbol; @@ -620,7 +696,8 @@ namespace SharpCompress.Compressor.PPMd.I1 currentContext.Suffix = context; context = currentContext; states[--stateIndex].Successor = context; - } while (stateIndex != 0); + } + while (stateIndex != 0); return context; } @@ -661,7 +738,8 @@ namespace SharpCompress.Compressor.PPMd.I1 do { states[--stateIndex].Successor = context; - } while (stateIndex != 0); + } + while (stateIndex != 0); Allocator.Text = Allocator.Heap + 1; orderFall = 1; } @@ -678,21 +756,24 @@ namespace SharpCompress.Compressor.PPMd.I1 { temporary = state[1].Symbol; state++; - } while (temporary != symbol); + } + 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: if (state.Successor != PpmContext.Zero) + { break; + } states[stateIndex++] = state; state.Successor = UpBranch; orderFall++; @@ -704,12 +785,13 @@ namespace SharpCompress.Compressor.PPMd.I1 do { states[--stateIndex].Successor = context; - } while (stateIndex != 0); + } + while (stateIndex != 0); Allocator.Text = Allocator.Heap + 1; orderFall = 1; return context; } - else if (state.Successor <= UpBranch) + if (state.Successor <= UpBranch) { currentState = foundState; foundState = state; @@ -741,34 +823,40 @@ namespace SharpCompress.Compressor.PPMd.I1 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) { while (maximumContext.Suffix != PpmContext.Zero) + { maximumContext = maximumContext.Suffix; + } RemoveBinaryContexts(0, maximumContext); - method = (ModelRestorationMethod) (method + 1); + method = method + 1; Allocator.GlueCount = 0; orderFall = modelOrder; } @@ -781,13 +869,16 @@ namespace SharpCompress.Compressor.PPMd.I1 else { while (maximumContext.Suffix != PpmContext.Zero) + { maximumContext = maximumContext.Suffix; + } do { CutOff(0, maximumContext); Allocator.ExpandText(); - } while (Allocator.GetMemoryUsed() > 3*(Allocator.AllocatorSize >> 2)); + } + while (Allocator.GetMemoryUsed() > 3 * (Allocator.AllocatorSize >> 2)); Allocator.GlueCount = 0; orderFall = modelOrder; diff --git a/src/SharpCompress/Compressor/PPMd/I1/ModelRestorationMethod.cs b/src/SharpCompress/Compressor/PPMd/I1/ModelRestorationMethod.cs index cfcd6465..d3d9f86f 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/ModelRestorationMethod.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/ModelRestorationMethod.cs @@ -1,6 +1,6 @@ #region Using -using System; + #endregion diff --git a/src/SharpCompress/Compressor/PPMd/I1/Pointer.cs b/src/SharpCompress/Compressor/PPMd/I1/Pointer.cs index 6e43e902..ce38da9a 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/Pointer.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/Pointer.cs @@ -47,7 +47,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (Address == 0) + { throw new InvalidOperationException("The pointer being indexed is a null pointer."); + } #endif return Memory[Address + offset]; } @@ -55,7 +57,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (Address == 0) + { throw new InvalidOperationException("The pointer being indexed is a null pointer."); + } #endif Memory[Address + offset] = value; } @@ -101,9 +105,11 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer.Address == 0) + { throw new InvalidOperationException("The pointer is a null pointer."); + } #endif - pointer.Address = (uint) (pointer.Address + offset); + pointer.Address = (uint)(pointer.Address + offset); return pointer; } @@ -117,7 +123,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer.Address == 0) + { throw new InvalidOperationException("The pointer is a null pointer."); + } #endif pointer.Address += offset; return pointer; @@ -132,7 +140,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer.Address == 0) + { throw new InvalidOperationException("The pointer being incremented is a null pointer."); + } #endif pointer.Address++; return pointer; @@ -148,9 +158,11 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer.Address == 0) + { throw new InvalidOperationException("The pointer is a null pointer."); + } #endif - pointer.Address = (uint) (pointer.Address - offset); + pointer.Address = (uint)(pointer.Address - offset); return pointer; } @@ -164,7 +176,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer.Address == 0) + { throw new InvalidOperationException("The pointer is a null pointer."); + } #endif pointer.Address -= offset; return pointer; @@ -179,7 +193,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer.Address == 0) + { throw new InvalidOperationException("The pointer being decremented is a null pointer."); + } #endif pointer.Address--; return pointer; @@ -195,11 +211,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer1.Address == 0) + { throw new InvalidOperationException( - "The pointer to the left of the subtraction operator is a null pointer."); + "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."); + "The pointer to the right of the subtraction operator is a null pointer."); + } #endif return pointer1.Address - pointer2.Address; } @@ -214,11 +234,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer1.Address == 0) + { throw new InvalidOperationException( - "The pointer to the left of the less than operator is a null pointer."); + "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."); + "The pointer to the right of the less than operator is a null pointer."); + } #endif return pointer1.Address < pointer2.Address; } @@ -233,11 +257,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { #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."); + "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."); + "The pointer to the right of the less than or equal to operator is a null pointer."); + } #endif return pointer1.Address <= pointer2.Address; } @@ -252,11 +280,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { #if DEBUG if (pointer1.Address == 0) + { throw new InvalidOperationException( - "The pointer to the left of the greater than operator is a null pointer."); + "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."); + "The pointer to the right of the greater than operator is a null pointer."); + } #endif return pointer1.Address > pointer2.Address; } @@ -271,11 +303,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { #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."); + "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."); + "The pointer to the right of the greater than or equal to operator is a null pointer."); + } #endif return pointer1.Address >= pointer2.Address; } @@ -311,7 +347,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { if (obj is Pointer) { - Pointer pointer = (Pointer) obj; + Pointer pointer = (Pointer)obj; return pointer.Address == Address; } return base.Equals(obj); diff --git a/src/SharpCompress/Compressor/PPMd/I1/PpmContext.cs b/src/SharpCompress/Compressor/PPMd/I1/PpmContext.cs index d4625600..f0616bb2 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/PpmContext.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/PpmContext.cs @@ -1,7 +1,3 @@ -#region Using - -#endregion - namespace SharpCompress.Compressor.PPMd.I1 { /// @@ -38,31 +34,23 @@ namespace SharpCompress.Compressor.PPMd.I1 /// /// Gets or sets the number statistics. /// - public byte NumberStatistics - { - get { return Memory[Address]; } - set { Memory[Address] = value; } - } + public byte NumberStatistics { get { return Memory[Address]; } set { Memory[Address] = value; } } /// /// Gets or sets the flags. /// - public byte Flags - { - get { return Memory[Address + 1]; } - set { Memory[Address + 1] = value; } - } + public byte Flags { get { return Memory[Address + 1]; } set { Memory[Address + 1] = value; } } /// /// Gets or sets the summary frequency. /// public ushort SummaryFrequency { - get { return (ushort) (((ushort) Memory[Address + 2]) | ((ushort) Memory[Address + 3]) << 8); } + get { return (ushort)(Memory[Address + 2] | 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); } } @@ -75,15 +63,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { return new PpmState( - ((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | - ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); + 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); } } @@ -96,15 +84,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { return new PpmContext( - ((uint) Memory[Address + 8]) | ((uint) Memory[Address + 9]) << 8 | - ((uint) Memory[Address + 10]) << 16 | ((uint) Memory[Address + 11]) << 24, Memory); + 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,32 +121,21 @@ namespace SharpCompress.Compressor.PPMd.I1 /// /// /// - public PpmState FirstState - { - get { return new PpmState(Address + 2, Memory); } - } + public PpmState FirstState { get { return new PpmState(Address + 2, Memory); } } /// /// Gets or sets the symbol of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Symbol property on the PPM state provided by the /// property. /// - public byte FirstStateSymbol - { - get { return Memory[Address + 2]; } - set { Memory[Address + 2] = value; } - } + public byte FirstStateSymbol { get { return Memory[Address + 2]; } set { Memory[Address + 2] = value; } } /// /// Gets or sets the frequency of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Frequency property on the PPM state provided by the ///context.FirstState property. /// - public byte FirstStateFrequency - { - get { return Memory[Address + 3]; } - set { Memory[Address + 3] = value; } - } + public byte FirstStateFrequency { get { return Memory[Address + 3]; } set { Memory[Address + 3] = value; } } /// /// Gets or sets the successor of the first PPM state. This is provided for convenience. The same @@ -170,15 +147,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { return new PpmContext( - ((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | - ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); + 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); } } @@ -200,7 +177,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; } @@ -212,7 +189,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; } @@ -269,7 +246,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); @@ -295,18 +272,18 @@ namespace SharpCompress.Compressor.PPMd.I1 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)); + (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; @@ -325,13 +302,15 @@ 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; runLength += previousSuccess; if (state.Frequency > MaximumFrequency) + { Rescale(context); + } Coder.LowCount = 0; return; } @@ -352,7 +331,8 @@ namespace SharpCompress.Compressor.PPMd.I1 do { characterMask[(--state).Symbol] = escapeCount; - } while (--index != 0); + } + while (--index != 0); Coder.HighCount = Coder.Scale; return; } @@ -366,7 +346,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 @@ -375,17 +355,21 @@ namespace SharpCompress.Compressor.PPMd.I1 { currentSymbol = state[1].Symbol; state++; - } while (characterMask[currentSymbol] == escapeCount); + } + while (characterMask[currentSymbol] == escapeCount); characterMask[currentSymbol] = escapeCount; if (currentSymbol == symbol) + { goto SymbolFound; + } lowCount += state.Frequency; - } while (--index != 0); + } + while (--index != 0); 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; @@ -399,7 +383,8 @@ namespace SharpCompress.Compressor.PPMd.I1 { currentSymbol = p1[1].Symbol; p1++; - } while (characterMask[currentSymbol] == escapeCount); + } + while (characterMask[currentSymbol] == escapeCount); lowCount += p1.Frequency; } Coder.Scale += lowCount; @@ -417,18 +402,18 @@ namespace SharpCompress.Compressor.PPMd.I1 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)); + (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; @@ -450,14 +435,16 @@ 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) + { Rescale(context); + } Coder.LowCount = 0; return; } @@ -476,7 +463,8 @@ namespace SharpCompress.Compressor.PPMd.I1 do { characterMask[(--state).Symbol] = escapeCount; - } while (--index != 0); + } + while (--index != 0); Coder.HighCount = Coder.Scale; return; } @@ -492,7 +480,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; @@ -502,11 +490,14 @@ namespace SharpCompress.Compressor.PPMd.I1 { currentSymbol = state[1].Symbol; state++; - } while (characterMask[currentSymbol] == escapeCount); + } + 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) - } while (--index != 0); + + // 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; count = Coder.RangeGetCurrentCount(); @@ -516,7 +507,9 @@ namespace SharpCompress.Compressor.PPMd.I1 { highCount = 0; while ((highCount += state.Frequency) <= count) + { state = decodeStates[++stateIndex]; + } Coder.HighCount = highCount; Coder.LowCount = Coder.HighCount - state.Frequency; see2Context.Update(); @@ -526,14 +519,15 @@ 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; + } + while (--index != 0); + see2Context.Summary += (ushort)Coder.Scale; } } @@ -547,7 +541,9 @@ namespace SharpCompress.Compressor.PPMd.I1 Swap(state[0], state[-1]); foundState = --state; if (state.Frequency > MaximumFrequency) + { Rescale(context); + } } } @@ -557,14 +553,16 @@ namespace SharpCompress.Compressor.PPMd.I1 foundState.Frequency += 4; context.SummaryFrequency += 4; if (state.Frequency > MaximumFrequency) + { Rescale(context); + } escapeCount++; runLength = initialRunLength; } private See2Context MakeEscapeFrequency(PpmContext context) { - uint numberStatistics = (uint) 2*context.NumberStatistics; + uint numberStatistics = (uint)2 * context.NumberStatistics; See2Context see2Context; if (context.NumberStatistics != 0xff) @@ -574,8 +572,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(); } @@ -602,19 +600,21 @@ namespace SharpCompress.Compressor.PPMd.I1 PpmState state; for (state = foundState; state != context.Statistics; state--) + { Swap(state[0], state[-1]); + } 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) { @@ -625,54 +625,60 @@ namespace SharpCompress.Compressor.PPMd.I1 do { Copy(p1[0], p1[-1]); - } while (localFrequency > (--p1)[-1].Frequency); + } + while (localFrequency > (--p1)[-1].Frequency); p1.Symbol = localSymbol; p1.Frequency = localFrequency; p1.Successor = localSuccessor; } - } while (--index != 0); + } + while (--index != 0); if (state.Frequency == 0) { do { index++; - } while ((--state).Frequency == 0); + } + 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)); + (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); - } while (--index != 0); + 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; } @@ -683,24 +689,25 @@ 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)); + (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); - } while (--index != 0); + 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) @@ -711,12 +718,16 @@ 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); + } else + { state.Successor = PpmContext.Zero; + } if (state.Successor == PpmContext.Zero && order > OrderBound) { @@ -726,14 +737,11 @@ namespace SharpCompress.Compressor.PPMd.I1 return context; } - else - { - Allocator.SpecialFreeUnits(context); - return PpmContext.Zero; - } + Allocator.SpecialFreeUnits(context); + return PpmContext.Zero; } - 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--) @@ -744,14 +752,18 @@ namespace SharpCompress.Compressor.PPMd.I1 Swap(state, context.Statistics[index--]); } else if (order < modelOrder) + { state.Successor = CutOff(order + 1, state.Successor); + } else + { state.Successor = PpmContext.Zero; + } } if (index != context.NumberStatistics && order != 0) { - context.NumberStatistics = (byte) index; + context.NumberStatistics = (byte)index; state = context.Statistics; if (index < 0) { @@ -759,16 +771,16 @@ namespace SharpCompress.Compressor.PPMd.I1 Allocator.SpecialFreeUnits(context); return PpmContext.Zero; } - else if (index == 0) + 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); } } @@ -780,28 +792,33 @@ 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)) { Allocator.FreeUnits(context, 1); return PpmContext.Zero; } - else - { - return context; - } + return context; } 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; + } } return context; diff --git a/src/SharpCompress/Compressor/PPMd/I1/PpmState.cs b/src/SharpCompress/Compressor/PPMd/I1/PpmState.cs index 08c0173f..579777a6 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/PpmState.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/PpmState.cs @@ -1,6 +1,6 @@ #region Using -using System; + #endregion @@ -38,20 +38,12 @@ namespace SharpCompress.Compressor.PPMd.I1 /// /// Gets or sets the symbol. /// - public byte Symbol - { - get { return Memory[Address]; } - set { Memory[Address] = value; } - } + public byte Symbol { get { return Memory[Address]; } set { Memory[Address] = value; } } /// /// Gets or sets the frequency. /// - public byte Frequency - { - get { return Memory[Address + 1]; } - set { Memory[Address + 1] = value; } - } + public byte Frequency { get { return Memory[Address + 1]; } set { Memory[Address + 1] = value; } } /// /// Gets or sets the successor. @@ -62,15 +54,15 @@ namespace SharpCompress.Compressor.PPMd.I1 { return new Model.PpmContext( - ((uint) Memory[Address + 2]) | ((uint) Memory[Address + 3]) << 8 | - ((uint) Memory[Address + 4]) << 16 | ((uint) Memory[Address + 5]) << 24, Memory); + 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; - Memory[Address + 3] = (byte) (value.Address >> 8); - Memory[Address + 4] = (byte) (value.Address >> 16); - Memory[Address + 5] = (byte) (value.Address >> 24); + Memory[Address + 2] = (byte)value.Address; + Memory[Address + 3] = (byte)(value.Address >> 8); + Memory[Address + 4] = (byte)(value.Address >> 16); + Memory[Address + 5] = (byte)(value.Address >> 24); } } @@ -80,10 +72,7 @@ namespace SharpCompress.Compressor.PPMd.I1 /// /// /// - public PpmState this[int offset] - { - get { return new PpmState((uint) (Address + offset*Size), Memory); } - } + public PpmState this[int offset] { get { return new PpmState((uint)(Address + offset * Size), Memory); } } /// /// Allow a pointer to be implicitly converted to a PPM state. @@ -103,7 +92,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; } @@ -126,7 +115,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; } @@ -194,7 +183,7 @@ namespace SharpCompress.Compressor.PPMd.I1 { if (obj is PpmState) { - PpmState state = (PpmState) obj; + PpmState state = (PpmState)obj; return state.Address == Address; } return base.Equals(obj); diff --git a/src/SharpCompress/Compressor/PPMd/I1/See2Context.cs b/src/SharpCompress/Compressor/PPMd/I1/See2Context.cs index 7eec77e7..9f56e9b5 100644 --- a/src/SharpCompress/Compressor/PPMd/I1/See2Context.cs +++ b/src/SharpCompress/Compressor/PPMd/I1/See2Context.cs @@ -1,6 +1,6 @@ #region Using -using System; + #endregion @@ -32,15 +32,15 @@ namespace SharpCompress.Compressor.PPMd.I1 public void Initialize(uint initialValue) { Shift = PeriodBitCount - 4; - Summary = (ushort) (initialValue << Shift); + Summary = (ushort)(initialValue << Shift); Count = 7; } public uint Mean() { - uint value = (uint) (Summary >> Shift); - Summary = (ushort) (Summary - value); - return (uint) (value + ((value == 0) ? 1 : 0)); + uint value = (uint)(Summary >> Shift); + Summary = (ushort)(Summary - value); + return (uint)(value + ((value == 0) ? 1 : 0)); } public void Update() @@ -48,7 +48,7 @@ namespace SharpCompress.Compressor.PPMd.I1 if (Shift < PeriodBitCount && --Count == 0) { Summary += Summary; - Count = (byte) (3 << Shift++); + Count = (byte)(3 << Shift++); } } } diff --git a/src/SharpCompress/Compressor/PPMd/PpmdProperties.cs b/src/SharpCompress/Compressor/PPMd/PpmdProperties.cs index eeb082fe..4daa3074 100644 --- a/src/SharpCompress/Compressor/PPMd/PpmdProperties.cs +++ b/src/SharpCompress/Compressor/PPMd/PpmdProperties.cs @@ -1,4 +1,4 @@ -using System; +using SharpCompress.Compressor.PPMd.I1; using SharpCompress.Converter; namespace SharpCompress.Compressor.PPMd @@ -7,17 +7,17 @@ namespace SharpCompress.Compressor.PPMd { H, H7z, - I1, + I1 } public class PpmdProperties { public PpmdVersion Version = PpmdVersion.I1; public int ModelOrder; - internal I1.ModelRestorationMethod ModelRestorationMethod; + internal ModelRestorationMethod ModelRestorationMethod; private int allocatorSize; - internal I1.Allocator Allocator; + internal Allocator Allocator; public PpmdProperties() : this(16 << 20, 6) @@ -25,11 +25,11 @@ namespace SharpCompress.Compressor.PPMd } public PpmdProperties(int allocatorSize, int modelOrder) - : this(allocatorSize, modelOrder, I1.ModelRestorationMethod.Restart) + : this(allocatorSize, modelOrder, ModelRestorationMethod.Restart) { } - internal PpmdProperties(int allocatorSize, int modelOrder, I1.ModelRestorationMethod modelRestorationMethod) + internal PpmdProperties(int allocatorSize, int modelOrder, ModelRestorationMethod modelRestorationMethod) { AllocatorSize = allocatorSize; ModelOrder = modelOrder; @@ -43,7 +43,7 @@ namespace SharpCompress.Compressor.PPMd ushort props = DataConverter.LittleEndian.GetUInt16(properties, 0); AllocatorSize = (((props >> 4) & 0xff) + 1) << 20; ModelOrder = (props & 0x0f) + 1; - ModelRestorationMethod = (I1.ModelRestorationMethod) (props >> 12); + ModelRestorationMethod = (ModelRestorationMethod)(props >> 12); } else if (properties.Length == 5) { @@ -62,7 +62,9 @@ namespace SharpCompress.Compressor.PPMd if (Version == PpmdVersion.I1) { if (Allocator == null) - Allocator = new I1.Allocator(); + { + Allocator = new Allocator(); + } Allocator.Start(allocatorSize); } } @@ -74,8 +76,8 @@ namespace SharpCompress.Compressor.PPMd { return DataConverter.LittleEndian.GetBytes( - (ushort) - ((ModelOrder - 1) + (((AllocatorSize >> 20) - 1) << 4) + ((ushort) ModelRestorationMethod << 12))); + (ushort) + ((ModelOrder - 1) + (((AllocatorSize >> 20) - 1) << 4) + ((ushort)ModelRestorationMethod << 12))); } } } diff --git a/src/SharpCompress/Compressor/PPMd/PpmdStream.cs b/src/SharpCompress/Compressor/PPMd/PpmdStream.cs index efe29b56..c5982bf0 100644 --- a/src/SharpCompress/Compressor/PPMd/PpmdStream.cs +++ b/src/SharpCompress/Compressor/PPMd/PpmdStream.cs @@ -1,18 +1,20 @@ using System; using System.IO; -using SharpCompress.Compressor.Rar.PPM; +using SharpCompress.Compressor.LZMA.RangeCoder; +using SharpCompress.Compressor.PPMd.H; +using SharpCompress.Compressor.PPMd.I1; namespace SharpCompress.Compressor.PPMd { public class PpmdStream : Stream { - private PpmdProperties properties; - private Stream stream; - private bool compress; - private I1.Model model; - private H.ModelPPM modelH; - private LZMA.RangeCoder.Decoder decoder; - private long position = 0; + private readonly PpmdProperties properties; + private readonly Stream stream; + private readonly bool compress; + private readonly Model model; + private readonly ModelPPM modelH; + private readonly Decoder decoder; + private long position; private bool isDisposed; public PpmdStream(PpmdProperties properties, Stream stream, bool compress) @@ -23,46 +25,43 @@ namespace SharpCompress.Compressor.PPMd if (properties.Version == PpmdVersion.I1) { - model = new I1.Model(); + model = new Model(); if (compress) + { model.EncodeStart(properties); + } else + { model.DecodeStart(stream, properties); + } } if (properties.Version == PpmdVersion.H) { - modelH = new H.ModelPPM(); + modelH = new ModelPPM(); if (compress) + { throw new NotImplementedException(); - else - modelH.decodeInit(stream, properties.ModelOrder, properties.AllocatorSize); + } + modelH.decodeInit(stream, properties.ModelOrder, properties.AllocatorSize); } if (properties.Version == PpmdVersion.H7z) { - modelH = new H.ModelPPM(); + modelH = new ModelPPM(); if (compress) + { throw new NotImplementedException(); - else - modelH.decodeInit(null, properties.ModelOrder, properties.AllocatorSize); - decoder = new LZMA.RangeCoder.Decoder(); + } + modelH.decodeInit(null, properties.ModelOrder, properties.AllocatorSize); + decoder = new Decoder(); decoder.Init(stream); } } - public override bool CanRead - { - get { return !compress; } - } + public override bool CanRead { get { return !compress; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return compress; } - } + public override bool CanWrite { get { return compress; } } public override void Flush() { @@ -78,35 +77,34 @@ namespace SharpCompress.Compressor.PPMd if (isDisposing) { if (compress) + { model.EncodeBlock(stream, new MemoryStream(), true); + } } base.Dispose(isDisposing); } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { return position; } - set { throw new NotSupportedException(); } - } + public override long Position { get { return position; } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { if (compress) + { return 0; + } int size = 0; if (properties.Version == PpmdVersion.I1) + { size = model.DecodeBlock(stream, buffer, offset, count); + } if (properties.Version == PpmdVersion.H) { int c; while (size < count && (c = modelH.decodeChar()) >= 0) { - buffer[offset++] = (byte) c; + buffer[offset++] = (byte)c; size++; } } @@ -115,7 +113,7 @@ namespace SharpCompress.Compressor.PPMd int c; while (size < count && (c = modelH.decodeChar(decoder)) >= 0) { - buffer[offset++] = (byte) c; + buffer[offset++] = (byte)c; size++; } } @@ -136,7 +134,9 @@ namespace SharpCompress.Compressor.PPMd public override void Write(byte[] buffer, int offset, int count) { if (compress) + { model.EncodeBlock(stream, new MemoryStream(buffer, offset, count), false); + } } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Rar/Decode/Compress.cs b/src/SharpCompress/Compressor/Rar/Decode/Compress.cs index 8a23c7d0..3508a8ff 100644 --- a/src/SharpCompress/Compressor/Rar/Decode/Compress.cs +++ b/src/SharpCompress/Compressor/Rar/Decode/Compress.cs @@ -4,6 +4,7 @@ namespace SharpCompress.Compressor.Rar.decode { public const int CODEBUFSIZE = 0x4000; public const int MAXWINSIZE = 0x400000; + //UPGRADE_NOTE: Final was removed from the declaration of 'MAXWINMASK '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public static readonly int MAXWINMASK = (MAXWINSIZE - 1); @@ -13,6 +14,7 @@ namespace SharpCompress.Compressor.Rar.decode public const int DC = 60; public const int LDC = 17; public const int RC = 28; + //UPGRADE_NOTE: Final was removed from the declaration of 'HUFF_TABLE_SIZE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public static readonly int HUFF_TABLE_SIZE = (NC + DC + RC + LDC); public const int BC = 20; diff --git a/src/SharpCompress/Compressor/Rar/Decode/FilterType.cs b/src/SharpCompress/Compressor/Rar/Decode/FilterType.cs index 23966e4f..ad2a7b32 100644 --- a/src/SharpCompress/Compressor/Rar/Decode/FilterType.cs +++ b/src/SharpCompress/Compressor/Rar/Decode/FilterType.cs @@ -11,6 +11,6 @@ namespace SharpCompress.Compressor.Rar.decode FILTER_RGB, FILTER_DELTA, FILTER_ITANIUM, - FILTER_E8E9V2, + FILTER_E8E9V2 } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Rar/MultiVolumeReadOnlyStream.cs b/src/SharpCompress/Compressor/Rar/MultiVolumeReadOnlyStream.cs index 374fdcef..a7338539 100644 --- a/src/SharpCompress/Compressor/Rar/MultiVolumeReadOnlyStream.cs +++ b/src/SharpCompress/Compressor/Rar/MultiVolumeReadOnlyStream.cs @@ -74,7 +74,7 @@ namespace SharpCompress.Compressor.Rar int readSize = currentCount; if (currentCount > maxPosition - currentPosition) { - readSize = (int) (maxPosition - currentPosition); + readSize = (int)(maxPosition - currentPosition); } int read = currentStream.Read(buffer, currentOffset, readSize); @@ -98,7 +98,7 @@ namespace SharpCompress.Compressor.Rar if (!filePartEnumerator.MoveNext()) { throw new InvalidFormatException( - "Multi-part rar file is incomplete. Entry expects a new volume: " + fileName); + "Multi-part rar file is incomplete. Entry expects a new volume: " + fileName); } InitializeNextFilePart(); } @@ -113,36 +113,20 @@ namespace SharpCompress.Compressor.Rar return totalRead; } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { throw new NotSupportedException(); } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { diff --git a/src/SharpCompress/Compressor/Rar/PPM/BlockTypes.cs b/src/SharpCompress/Compressor/Rar/PPM/BlockTypes.cs index cf3c4889..eb9fa15c 100644 --- a/src/SharpCompress/Compressor/Rar/PPM/BlockTypes.cs +++ b/src/SharpCompress/Compressor/Rar/PPM/BlockTypes.cs @@ -3,6 +3,6 @@ namespace SharpCompress.Compressor.Rar.PPM internal enum BlockTypes { BLOCK_LZ = 0, - BLOCK_PPM = 1, + BLOCK_PPM = 1 } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Rar/RarCRC.cs b/src/SharpCompress/Compressor/Rar/RarCRC.cs index 1870bb85..34bdfac6 100644 --- a/src/SharpCompress/Compressor/Rar/RarCRC.cs +++ b/src/SharpCompress/Compressor/Rar/RarCRC.cs @@ -4,7 +4,7 @@ namespace SharpCompress.Compressor.Rar { internal static class RarCRC { - private static uint[] crcTab; + private static readonly uint[] crcTab; public static uint CheckCrc(uint startCrc, byte[] data, int offset, int count) { @@ -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)startCrc ^ data[offset + i]) & 0xff] ^ (startCrc >> 8)); } return (startCrc); } diff --git a/src/SharpCompress/Compressor/Rar/RarStream.cs b/src/SharpCompress/Compressor/Rar/RarStream.cs index fefabc1a..a41b8d3f 100644 --- a/src/SharpCompress/Compressor/Rar/RarStream.cs +++ b/src/SharpCompress/Compressor/Rar/RarStream.cs @@ -10,15 +10,15 @@ namespace SharpCompress.Compressor.Rar private readonly FileHeader fileHeader; private readonly Stream readStream; - private bool fetch = false; + private bool fetch; private byte[] tmpBuffer = new byte[65536]; - private int tmpOffset = 0; - private int tmpCount = 0; + private int tmpOffset; + private int tmpCount; private byte[] outBuffer; private int outOffset; - private int outCount = 0; + private int outCount; private int outTotal; private bool isDisposed; @@ -43,44 +43,19 @@ namespace SharpCompress.Compressor.Rar readStream.Dispose(); } - public override bool CanRead - { - get - { - return true; - } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get - { - return false; - } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get - { - return false; - } - } + public override bool CanWrite { get { return false; } } public override void Flush() { } - public override long Length - { - get { return fileHeader.UncompressedSize; } - } + public override long Length { get { return fileHeader.UncompressedSize; } } - public override long Position - { - get { return fileHeader.UncompressedSize - unpack.DestSize; } - set { throw new NotSupportedException(); } - } + public override long Position { get { return fileHeader.UncompressedSize - unpack.DestSize; } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -148,7 +123,9 @@ namespace SharpCompress.Compressor.Rar unpack.Suspended = true; } else + { unpack.Suspended = false; + } } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Rar/Unpack.cs b/src/SharpCompress/Compressor/Rar/Unpack.cs index 4b6ebd9d..a3dbf3ac 100644 --- a/src/SharpCompress/Compressor/Rar/Unpack.cs +++ b/src/SharpCompress/Compressor/Rar/Unpack.cs @@ -12,9 +12,7 @@ namespace SharpCompress.Compressor.Rar { internal sealed class Unpack : Unpack20 { - public bool FileExtracted - { - // Duplicate method + public bool FileExtracted { // Duplicate method // private boolean ReadEndOfBlock() throws IOException, RarException // { // int BitField = getbits(); @@ -30,29 +28,25 @@ namespace SharpCompress.Compressor.Rar // tablesRead = !NewTable; // return !(NewFile || NewTable && !readTables()); // } - get { return fileExtracted; } - } + get; private set; } public long DestSize { get { return destUnpSize; } set { - this.destUnpSize = value; - this.fileExtracted = false; + destUnpSize = value; + FileExtracted = false; } } - public bool Suspended - { - set { this.suspended = value; } - } + public bool Suspended { set { suspended = value; } } public int Char { get { - if (inAddr > BitInput.MAX_SIZE - 30) + if (inAddr > MAX_SIZE - 30) { unpReadBuf(); } @@ -60,34 +54,27 @@ namespace SharpCompress.Compressor.Rar } } - public int PpmEscChar - { - get { return ppmEscChar; } - - set { this.ppmEscChar = value; } - } + public int PpmEscChar { get; set; } //UPGRADE_NOTE: Final was removed from the declaration of 'ppm '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ModelPPM ppm = new ModelPPM(); + private readonly ModelPPM ppm = new ModelPPM(); - private int ppmEscChar; - - private RarVM rarVM = new RarVM(); + private readonly RarVM rarVM = new RarVM(); /* Filters code, one entry per filter */ //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'" - private List filters = new List(); + private readonly List filters = new List(); /* Filters stack, several entrances of same filter are possible */ //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'" - private List prgStack = new List(); + private readonly List prgStack = new List(); /* * lengths of preceding blocks, one length per filter. Used to reduce size * required to write block length if lengths are repeating */ //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'" - private List oldFilterLengths = new List(); + private readonly List oldFilterLengths = new List(); private int lastFilter; @@ -95,7 +82,7 @@ namespace SharpCompress.Compressor.Rar //UPGRADE_NOTE: The initialization of 'unpOldTable' was moved to method 'InitBlock'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" - private byte[] unpOldTable = new byte[Compress.HUFF_TABLE_SIZE]; + private readonly byte[] unpOldTable = new byte[Compress.HUFF_TABLE_SIZE]; private BlockTypes unpBlockType; @@ -103,21 +90,20 @@ namespace SharpCompress.Compressor.Rar private long writtenFileSize; - private bool fileExtracted; - private bool ppmError; private int prevLowDist; 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 = {4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 14, 0, 12}; private FileHeader fileHeader; public Unpack() { window = null; + //externalWindow = false; suspended = false; unpAllBuf = false; @@ -133,6 +119,7 @@ namespace SharpCompress.Compressor.Rar else { this.window = window; + //externalWindow = true; } inAddr = 0; @@ -143,8 +130,8 @@ namespace SharpCompress.Compressor.Rar { destUnpSize = fileHeader.UncompressedSize; this.fileHeader = fileHeader; - base.writeStream = writeStream; - base.readStream = readStream; + this.writeStream = writeStream; + this.readStream = readStream; bool solid = FlagUtility.HasFlag(fileHeader.FileFlags, FileFlags.SOLID); if (!solid) { @@ -169,13 +156,15 @@ namespace SharpCompress.Compressor.Rar break; case 20: - // rar 2.x compression + + // rar 2.x compression case 26: // files larger than 2GB unpack20(solid); break; case 29: - // rar 3.x compression + + // rar 3.x compression case 36: // alternative hash unpack29(solid); break; @@ -187,15 +176,21 @@ 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)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; + } if (suspended) + { return; + } } } @@ -215,12 +210,12 @@ 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; } } } - fileExtracted = true; + FileExtracted = true; if (!suspended) { @@ -251,6 +246,7 @@ namespace SharpCompress.Compressor.Rar break; } } + // System.out.println(((wrPtr - unpPtr) & // Compress.MAXWINMASK)+":"+wrPtr+":"+unpPtr); if (((wrPtr - unpPtr) & Compress.MAXWINMASK) < 260 && wrPtr != unpPtr) @@ -262,7 +258,7 @@ namespace SharpCompress.Compressor.Rar } if (suspended) { - fileExtracted = false; + FileExtracted = false; return; } } @@ -274,7 +270,7 @@ namespace SharpCompress.Compressor.Rar ppmError = true; break; } - if (Ch == ppmEscChar) + if (Ch == PpmEscChar) { int NextCh = ppm.decodeChar(); if (NextCh == 0) @@ -340,14 +336,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) @@ -468,7 +464,6 @@ namespace SharpCompress.Compressor.Rar insertOldDist(Distance); insertLastMatch(2, Distance); copyString(2, Distance); - continue; } } UnpWriteBuf(); @@ -511,8 +506,10 @@ namespace SharpCompress.Compressor.Rar else { int FirstPartLength = Compress.MAXWINSIZE - BlockStart; + // VM.SetMemory(0,Window+BlockStart,FirstPartLength); rarVM.setMemory(0, window, BlockStart, FirstPartLength); + // VM.SetMemory(FirstPartLength,Window,BlockEnd); rarVM.setMemory(FirstPartLength, window, 0, BlockEnd); } @@ -544,6 +541,7 @@ namespace SharpCompress.Compressor.Rar //ParentPrg.GlobalData.Clear(); // ->GlobalData.Alloc(Prg->GlobalData.Size()); ParentPrg.GlobalData.SetSize(Prg.GlobalData.Count); } + // 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++) { @@ -563,7 +561,8 @@ namespace SharpCompress.Compressor.Rar for (int i = 0; i < FilteredDataSize; i++) { FilteredData[i] = rarVM.Mem[FilteredDataOffset + i]; - // Prg.GlobalData.get(FilteredDataOffset + + // Prg.GlobalData.get(FilteredDataOffset // + // i); } @@ -577,10 +576,12 @@ namespace SharpCompress.Compressor.Rar { break; } + // apply several filters to same data block rarVM.setMemory(0, FilteredData, 0, FilteredDataSize); - // .SetMemory(0,FilteredData,FilteredDataSize); + + // .SetMemory(0,FilteredData,FilteredDataSize); VMPreparedProgram pPrg = filters[NextFilter.ParentFilter].Program; VMPreparedProgram NextPrg = NextFilter.Program; @@ -591,6 +592,7 @@ namespace SharpCompress.Compressor.Rar // if any // NextPrg->GlobalData.Alloc(ParentPrg->GlobalData.Size()); NextPrg.GlobalData.SetSize(pPrg.GlobalData.Count); + // 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++) { @@ -608,6 +610,7 @@ namespace SharpCompress.Compressor.Rar { pPrg.GlobalData.SetSize(NextPrg.GlobalData.Count); } + // 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++) { @@ -685,7 +688,7 @@ namespace SharpCompress.Compressor.Rar int writeSize = size; if (writeSize > destUnpSize) { - writeSize = (int) destUnpSize; + writeSize = (int)destUnpSize; } writeStream.Write(data, offset, writeSize); @@ -712,20 +715,25 @@ namespace SharpCompress.Compressor.Rar // System.out.println("copyString(" + length + ", " + distance + ")"); int destPtr = unpPtr - distance; + // System.out.println(unpPtr+":"+distance); if (destPtr >= 0 && destPtr < Compress.MAXWINSIZE - 260 && unpPtr < Compress.MAXWINSIZE - 260) { window[unpPtr++] = window[destPtr++]; while (--length > 0) + { window[unpPtr++] = window[destPtr++]; + } } else + { while (length-- != 0) { window[unpPtr] = window[destPtr++ & Compress.MAXWINMASK]; unpPtr = (unpPtr + 1) & Compress.MAXWINMASK; } + } } protected internal override void unpInitData(bool solid) @@ -739,11 +747,11 @@ 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; - ppmEscChar = 2; + PpmEscChar = 2; initFilters(); } @@ -797,11 +805,11 @@ 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; - return (ppm.decodeInit(this, ppmEscChar)); + return (ppm.decodeInit(this, PpmEscChar)); } unpBlockType = BlockTypes.BLOCK_LZ; @@ -810,7 +818,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); @@ -838,7 +846,7 @@ namespace SharpCompress.Compressor.Rar } else { - bitLength[i] = (byte) length; + bitLength[i] = (byte)length; } } @@ -858,7 +866,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) @@ -930,6 +938,7 @@ namespace SharpCompress.Compressor.Rar Length = GetBits(); AddBits(16); } + //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(); for (int I = 0; I < Length; I++) @@ -938,7 +947,7 @@ namespace SharpCompress.Compressor.Rar { return (false); } - vmCode.Add((byte) (GetBits() >> 8)); + vmCode.Add((byte)(GetBits() >> 8)); AddBits(8); } return (addVMCode(FirstByte, vmCode, Length)); @@ -947,7 +956,7 @@ namespace SharpCompress.Compressor.Rar private bool readVMCodePPM() { int FirstByte = ppm.decodeChar(); - if ((int) FirstByte == -1) + if (FirstByte == -1) { return (false); } @@ -973,8 +982,9 @@ 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(); for (int I = 0; I < Length; I++) @@ -984,7 +994,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)); } @@ -993,8 +1003,9 @@ namespace SharpCompress.Compressor.Rar { BitInput Inp = new BitInput(); Inp.InitBitInput(); + // memcpy(Inp.InBuf,Code,Min(BitInput::MAX_SIZE,CodeSize)); - for (int i = 0; i < Math.Min(BitInput.MAX_SIZE, vmCode.Count); i++) + for (int i = 0; i < Math.Min(MAX_SIZE, vmCode.Count); i++) { Inp.InBuf[i] = vmCode[i]; } @@ -1014,7 +1025,9 @@ namespace SharpCompress.Compressor.Rar } } else + { FiltPos = lastFilter; // use the same filter as last time + } if (FiltPos > filters.Count || FiltPos > oldFilterLengths.Count) { @@ -1024,10 +1037,12 @@ namespace SharpCompress.Compressor.Rar bool NewFilter = (FiltPos == filters.Count); UnpackFilter StackFilter = new UnpackFilter(); // new filter for + // PrgStack UnpackFilter Filter; if (NewFilter) + // new filter code, never used before since VM reset { // too many different filters, corrupt archive @@ -1043,7 +1058,8 @@ 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]; @@ -1079,10 +1095,12 @@ namespace SharpCompress.Compressor.Rar 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->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 { @@ -1112,15 +1130,17 @@ 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->Prg.CmdCount=Filter->Prg.CmdCount; int StaticDataSize = Filter.Program.StaticData.Count; if (StaticDataSize > 0 && StaticDataSize < RarVM.VM_GLOBALMEMSIZE) @@ -1128,6 +1148,7 @@ namespace SharpCompress.Compressor.Rar // read statically defined data contained in DB commands // StackFilter->Prg.StaticData.Add(StaticDataSize); StackFilter.Program.StaticData = Filter.Program.StaticData; + // memcpy(&StackFilter->Prg.StaticData[0],&Filter->Prg.StaticData[0],StaticDataSize); } @@ -1144,12 +1165,13 @@ 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 // *)&GlobalData[0x1c],StackFilter->BlockLength); rarVM.SetLowEndianValue(globalData, 0x1c, StackFilter.BlockLength); + // VM.SetLowEndianValue((uint *)&GlobalData[0x20],0); rarVM.SetLowEndianValue(globalData, 0x20, 0); rarVM.SetLowEndianValue(globalData, 0x24, 0); @@ -1158,12 +1180,14 @@ namespace SharpCompress.Compressor.Rar // VM.SetLowEndianValue((uint // *)&GlobalData[0x2c],StackFilter->ExecCount); rarVM.SetLowEndianValue(globalData, 0x2c, StackFilter.ExecCount); + // memset(&GlobalData[0x30],0,16); for (int i = 0; i < 16; i++) { globalData[0x30 + i] = 0x0; } if ((firstByte & 8) != 0) + // put data block passed as parameter if any { if (Inp.Overflow(3)) @@ -1189,26 +1213,27 @@ 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); } } return (true); } - private void ExecuteCode(VMPreparedProgram Prg) { 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/src/SharpCompress/Compressor/Rar/Unpack15.cs b/src/SharpCompress/Compressor/Rar/Unpack15.cs index e25e4ed3..4498f5e9 100644 --- a/src/SharpCompress/Compressor/Rar/Unpack15.cs +++ b/src/SharpCompress/Compressor/Rar/Unpack15.cs @@ -79,68 +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 readonly int[] DecL1 = + { + 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 readonly int[] PosL1 = {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 readonly int[] DecL2 = + { + 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 readonly int[] PosL2 = {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 readonly int[] DecHf0 = {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 readonly int[] PosHf0 = {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 readonly int[] DecHf1 = {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 readonly int[] PosHf1 = {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 readonly int[] DecHf2 = {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 readonly int[] PosHf2 = {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 readonly int[] DecHf3 = {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 readonly int[] PosHf3 = {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 readonly int[] DecHf4 = {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 readonly int[] PosHf4 = {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 = {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 = + { + 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 = {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 = + { + 0, 0x40, 0x60, 0xa0, 0xd0, 0xe0, 0xf0, 0xf8, 0xfc, 0xc0, 0x80, 0x90, 0x98 + , 0x9c, 0xb0 + }; protected internal abstract void unpInitData(bool solid); @@ -242,7 +242,6 @@ namespace SharpCompress.Compressor.Rar oldUnpWriteBuf(); } - protected bool unpReadBuf() { int dataSize = readTop - inAddr; @@ -250,7 +249,7 @@ namespace SharpCompress.Compressor.Rar { return (false); } - if (inAddr > BitInput.MAX_SIZE/2) + if (inAddr > MAX_SIZE / 2) { if (dataSize > 0) { @@ -267,8 +266,9 @@ namespace SharpCompress.Compressor.Rar { dataSize = readTop; } + //int readCode=UnpIO->UnpRead(InBuf+DataSize,(BitInput::MAX_SIZE-DataSize)&~0xf); - int readCode = readStream.Read(InBuf, dataSize, (BitInput.MAX_SIZE - dataSize) & ~0xf); + int readCode = readStream.Read(InBuf, dataSize, (MAX_SIZE - dataSize) & ~0xf); if (readCode > 0) { readTop += readCode; @@ -361,9 +361,13 @@ namespace SharpCompress.Compressor.Rar return; } if (Distance > 256) + { Length++; + } if (Distance >= MaxDist3) + { Length++; + } oldDist[oldDistPtr++] = Distance; oldDistPtr = oldDistPtr & 3; @@ -574,16 +578,13 @@ namespace SharpCompress.Compressor.Rar NumHuf = StMode = 0; return; } - else - { - Length = (BitField & 0x4000) != 0 ? 4 : 3; - AddBits(1); - Distance = decodeNum(GetBits(), STARTHF2, DecHf2, PosHf2); - Distance = (Distance << 5) | (Utility.URShift(GetBits(), 11)); - AddBits(5); - oldCopyString(Distance, Length); - return; - } + Length = (BitField & 0x4000) != 0 ? 4 : 3; + AddBits(1); + Distance = decodeNum(GetBits(), STARTHF2, DecHf2, PosHf2); + Distance = (Distance << 5) | (Utility.URShift(GetBits(), 11)); + AddBits(5); + oldCopyString(Distance, Length); + return; } } else @@ -602,7 +603,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) @@ -685,13 +686,14 @@ namespace SharpCompress.Compressor.Rar for (J = 0; J < 32; J++, pos++) { CharSet[pos] = ((CharSet[pos] & ~0xff) | I); // *CharSet=(*CharSet + // & ~0xff) | I; } } 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/src/SharpCompress/Compressor/Rar/Unpack20.cs b/src/SharpCompress/Compressor/Rar/Unpack20.cs index b264ceaa..7cb0b2b8 100644 --- a/src/SharpCompress/Compressor/Rar/Unpack20.cs +++ b/src/SharpCompress/Compressor/Rar/Unpack20.cs @@ -36,7 +36,7 @@ namespace SharpCompress.Compressor.Rar private void InitBlock() { - UnpOldTable20 = new byte[Compress.MC20*4]; + UnpOldTable20 = new byte[Compress.MC20 * 4]; } protected internal MultDecode[] MD = new MultDecode[4]; @@ -59,42 +59,42 @@ 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 = + { + 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 = + { + 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 = + { + 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 = + { + 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 = {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 = {2, 2, 3, 4, 5, 6, 6, 6}; internal void unpack20(bool solid) { @@ -126,13 +126,19 @@ namespace SharpCompress.Compressor.Rar unpPtr &= Compress.MAXWINMASK; if (inAddr > readTop - 30) + { if (!unpReadBuf()) + { break; + } + } if (((wrPtr - unpPtr) & Compress.MAXWINMASK) < 270 && wrPtr != unpPtr) { oldUnpWriteBuf(); if (suspended) + { return; + } } if (UnpAudioBlock != 0) { @@ -141,12 +147,16 @@ namespace SharpCompress.Compressor.Rar if (AudioNumber == 256) { if (!ReadTables20()) + { break; + } continue; } window[unpPtr++] = DecodeAudio(AudioNumber); if (++UnpCurChannel == UnpChannels) + { UnpCurChannel = 0; + } --destUnpSize; continue; } @@ -154,7 +164,7 @@ namespace SharpCompress.Compressor.Rar int Number = this.decodeNumber(LD); if (Number < 256) { - window[unpPtr++] = (byte) Number; + window[unpPtr++] = (byte)Number; --destUnpSize; continue; } @@ -179,7 +189,9 @@ namespace SharpCompress.Compressor.Rar { Length++; if (Distance >= 0x40000L) + { Length++; + } } CopyString20(Length, Distance); @@ -188,7 +200,9 @@ namespace SharpCompress.Compressor.Rar if (Number == 269) { if (!ReadTables20()) + { break; + } continue; } if (Number == 256) @@ -213,7 +227,9 @@ namespace SharpCompress.Compressor.Rar { Length++; if (Distance >= 0x40000) + { Length++; + } } } CopyString20(Length, Distance); @@ -228,7 +244,6 @@ namespace SharpCompress.Compressor.Rar AddBits(Bits); } CopyString20(2, Distance); - continue; } } ReadLastTables(); @@ -262,11 +277,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) { @@ -281,7 +295,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); @@ -293,7 +307,7 @@ namespace SharpCompress.Compressor.Rar UnpCurChannel = 0; } AddBits(2); - TableSize = Compress.MC20*UnpChannels; + TableSize = Compress.MC20 * UnpChannels; } else { @@ -301,7 +315,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); @@ -318,7 +332,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) @@ -344,7 +358,9 @@ namespace SharpCompress.Compressor.Rar AddBits(7); } while (N-- > 0 && I < TableSize) + { Table[I++] = 0; + } } } if (inAddr > readTop) @@ -352,14 +368,19 @@ namespace SharpCompress.Compressor.Rar return (true); } 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); UnpackUtility.makeDecodeTables(Table, Compress.NC20, DD, Compress.DC20); UnpackUtility.makeDecodeTables(Table, Compress.NC20 + Compress.DC20, RD, Compress.RC20); } + // memcpy(UnpOldTable20,Table,sizeof(UnpOldTable20)); for (int i = 0; i < UnpOldTable20.Length; i++) { @@ -374,13 +395,15 @@ namespace SharpCompress.Compressor.Rar { UnpChannelDelta = UnpCurChannel = 0; UnpChannels = 1; + // memset(AudV,0,sizeof(AudV)); AudV[0] = new AudioVariables(); AudV[1] = new AudioVariables(); AudV[2] = new AudioVariables(); AudV[3] = new AudioVariables(); + // memset(UnpOldTable20,0,sizeof(UnpOldTable20)); - Utility.Fill(UnpOldTable20, (byte) 0); + Utility.Fill(UnpOldTable20, (byte)0); } } @@ -413,30 +436,31 @@ namespace SharpCompress.Compressor.Rar v.D3 = v.D2; // ->D3=V->D2; v.D2 = v.LastDelta - v.D1; // ->D2=V->LastDelta-V->D1; 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); - v.Dif[2] += System.Math.Abs(D + v.D1); // V->Dif[2]+=abs(D+V->D1); - v.Dif[3] += System.Math.Abs(D - v.D2); // V->Dif[3]+=abs(D-V->D2); - v.Dif[4] += System.Math.Abs(D + v.D2); // V->Dif[4]+=abs(D+V->D2); - v.Dif[5] += System.Math.Abs(D - v.D3); // V->Dif[5]+=abs(D-V->D3); - v.Dif[6] += System.Math.Abs(D + v.D3); // V->Dif[6]+=abs(D+V->D3); - v.Dif[7] += System.Math.Abs(D - v.D4); // V->Dif[7]+=abs(D-V->D4); - v.Dif[8] += System.Math.Abs(D + v.D4); // V->Dif[8]+=abs(D+V->D4); - 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.Dif[0] += Math.Abs(D); // V->Dif[0]+=abs(D); + v.Dif[1] += Math.Abs(D - v.D1); // V->Dif[1]+=abs(D-V->D1); + v.Dif[2] += Math.Abs(D + v.D1); // V->Dif[2]+=abs(D+V->D1); + v.Dif[3] += Math.Abs(D - v.D2); // V->Dif[3]+=abs(D-V->D2); + v.Dif[4] += Math.Abs(D + v.D2); // V->Dif[4]+=abs(D+V->D2); + v.Dif[5] += Math.Abs(D - v.D3); // V->Dif[5]+=abs(D-V->D3); + v.Dif[6] += Math.Abs(D + v.D3); // V->Dif[6]+=abs(D+V->D3); + v.Dif[7] += Math.Abs(D - v.D4); // V->Dif[7]+=abs(D-V->D4); + v.Dif[8] += Math.Abs(D + v.D4); // V->Dif[8]+=abs(D+V->D4); + v.Dif[9] += Math.Abs(D - UnpChannelDelta); // V->Dif[9]+=abs(D-UnpChannelDelta); + v.Dif[10] += 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; @@ -526,7 +550,7 @@ namespace SharpCompress.Compressor.Rar break; } } - return ((byte) Ch); + return ((byte)Ch); } } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Rar/UnpackUtility.cs b/src/SharpCompress/Compressor/Rar/UnpackUtility.cs index 9e8c81d9..bd207337 100644 --- a/src/SharpCompress/Compressor/Rar/UnpackUtility.cs +++ b/src/SharpCompress/Compressor/Rar/UnpackUtility.cs @@ -9,6 +9,7 @@ namespace SharpCompress.Compressor.Rar { int bits; long bitField = input.GetBits() & 0xfffe; + // if (bitField < dec.getDecodeLen()[8]) { // if (bitField < dec.getDecodeLen()[4]) { // if (bitField < dec.getDecodeLen()[2]) { @@ -101,9 +102,13 @@ namespace SharpCompress.Compressor.Rar if (bitField < decodeLen[6]) { if (bitField < decodeLen[5]) + { bits = 5; + } else + { bits = 6; + } } else { @@ -123,14 +128,24 @@ namespace SharpCompress.Compressor.Rar if (bitField < decodeLen[12]) { if (bitField < decodeLen[10]) + { if (bitField < decodeLen[9]) + { bits = 9; + } else + { bits = 10; + } + } else if (bitField < decodeLen[11]) + { bits = 11; + } else + { bits = 12; + } } else { @@ -152,7 +167,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 +188,18 @@ namespace SharpCompress.Compressor.Rar for (i = 0; i < size; i++) { - lenCount[(int) (lenTab[offset + i] & 0xF)]++; + lenCount[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]; } diff --git a/src/SharpCompress/Compressor/Rar/VM/BitInput.cs b/src/SharpCompress/Compressor/Rar/VM/BitInput.cs index 915a0841..a5291608 100644 --- a/src/SharpCompress/Compressor/Rar/VM/BitInput.cs +++ b/src/SharpCompress/Compressor/Rar/VM/BitInput.cs @@ -14,7 +14,7 @@ namespace SharpCompress.Compressor.Rar.VM InBuf = new byte[MAX_SIZE]; } - internal byte[] InBuf { get; private set; } + internal byte[] InBuf { get; } internal void InitBitInput() { diff --git a/src/SharpCompress/Compressor/Rar/VM/RarVM.cs b/src/SharpCompress/Compressor/Rar/VM/RarVM.cs index 7d6ae3e0..05438ed2 100644 --- a/src/SharpCompress/Compressor/Rar/VM/RarVM.cs +++ b/src/SharpCompress/Compressor/Rar/VM/RarVM.cs @@ -13,7 +13,6 @@ namespace SharpCompress.Compressor.Rar.VM // Mem.set_Renamed(offset + 2, Byte.valueOf((sbyte) ((Utility.URShift(value_Renamed, 16)) & 0xff))); // Mem.set_Renamed(offset + 3, Byte.valueOf((sbyte) ((Utility.URShift(value_Renamed, 24)) & 0xff))); - //} internal byte[] Mem { get; private set; } @@ -32,7 +31,7 @@ namespace SharpCompress.Compressor.Rar.VM private const long UINT_MASK = 0xffffFFFF; //((long)2*(long)Integer.MAX_VALUE); - private int[] R = new int[regCount]; + private readonly int[] R = new int[regCount]; private VMFlags flags; @@ -58,7 +57,7 @@ namespace SharpCompress.Compressor.Rar.VM private bool IsVMMem(byte[] mem) { - return this.Mem == mem; + return Mem == mem; } private int GetValue(bool byteMode, byte[] mem, int offset) @@ -69,23 +68,13 @@ namespace SharpCompress.Compressor.Rar.VM { return (mem[offset]); } - else - { - return (mem[offset] & 0xff); - } + return (mem[offset] & 0xff); } - else + if (IsVMMem(mem)) { - if (IsVMMem(mem)) - { - return DataConverter.LittleEndian.GetInt32(mem, offset); - } - else - { - return DataConverter.BigEndian.GetInt32(mem, offset); - - } + return DataConverter.LittleEndian.GetInt32(mem, offset); } + return DataConverter.BigEndian.GetInt32(mem, offset); } private void SetValue(bool byteMode, byte[] mem, int offset, int value) @@ -94,11 +83,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 @@ -112,16 +101,17 @@ namespace SharpCompress.Compressor.Rar.VM DataConverter.BigEndian.PutBytes(mem, offset, value); } } + // #define SET_VALUE(ByteMode,Addr,Value) SetValue(ByteMode,(uint // *)Addr,Value) } 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) @@ -143,27 +133,30 @@ 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)); { R[i] = prg.InitR[i]; } - long globalSize = (long) (Math.Min(prg.GlobalData.Count, VM_GLOBALMEMSIZE)) & 0xffFFffFF; + long globalSize = 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); { Mem[VM_GLOBALMEMADDR + i] = prg.GlobalData[i]; } } - long staticSize = (long) (Math.Min(prg.StaticData.Count, VM_GLOBALMEMSIZE - globalSize)) & 0xffFFffFF; + long staticSize = 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); { - Mem[VM_GLOBALMEMADDR + (int) globalSize + i] = prg.StaticData[i]; + Mem[VM_GLOBALMEMADDR + (int)globalSize + i] = prg.StaticData[i]; } } R[7] = VM_MEMSIZE; @@ -172,7 +165,7 @@ namespace SharpCompress.Compressor.Rar.VM //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 + .AltCommands : prg.Commands; if (!ExecuteCode(preparedCode, prg.CommandCount)) @@ -199,6 +192,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); { prg.GlobalData[i] = Mem[VM_GLOBALMEMADDR + i]; @@ -226,8 +220,8 @@ namespace SharpCompress.Compressor.Rar.VM int cmdCount) { maxOpCount = 25000000; - this.codeSize = cmdCount; - this.IP = 0; + codeSize = cmdCount; + IP = 0; while (true) { @@ -238,7 +232,8 @@ namespace SharpCompress.Compressor.Rar.VM { case VMCommands.VM_MOV: SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2)); - // SET_VALUE(Cmd->ByteMode,Op1,GET_VALUE(Cmd->ByteMode,Op2)); + + // SET_VALUE(Cmd->ByteMode,Op1,GET_VALUE(Cmd->ByteMode,Op2)); break; case VMCommands.VM_MOVB: @@ -249,134 +244,130 @@ namespace SharpCompress.Compressor.Rar.VM SetValue(false, Mem, op1, GetValue(false, Mem, op2)); break; - case VMCommands.VM_CMP: - { - VMFlags value1 = (VMFlags) GetValue(cmd.IsByteMode, Mem, op1); - VMFlags result = value1 - GetValue(cmd.IsByteMode, Mem, op2); + { + VMFlags value1 = (VMFlags)GetValue(cmd.IsByteMode, Mem, op1); + VMFlags result = value1 - GetValue(cmd.IsByteMode, Mem, op2); - if (result == 0) - { - flags = VMFlags.VM_FZ; - } - else - { - flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS)); - } + if (result == 0) + { + flags = VMFlags.VM_FZ; } + else + { + flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + } + } break; - case VMCommands.VM_CMPB: + { + VMFlags value1 = (VMFlags)GetValue(true, Mem, op1); + VMFlags result = value1 - GetValue(true, Mem, op2); + if (result == 0) { - VMFlags value1 = (VMFlags) GetValue(true, Mem, op1); - VMFlags result = value1 - GetValue(true, Mem, op2); - if (result == 0) - { - flags = VMFlags.VM_FZ; - } - else - { - flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS)); - } + flags = VMFlags.VM_FZ; } + else + { + flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + } + } break; case VMCommands.VM_CMPD: + { + VMFlags value1 = (VMFlags)GetValue(false, Mem, op1); + VMFlags result = value1 - GetValue(false, Mem, op2); + if (result == 0) { - VMFlags value1 = (VMFlags) GetValue(false, Mem, op1); - VMFlags result = value1 - GetValue(false, Mem, op2); - if (result == 0) - { - flags = VMFlags.VM_FZ; - } - else - { - flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS)); - } + flags = VMFlags.VM_FZ; } + else + { + flags = (VMFlags)((result > value1) ? 1 : 0 | (int)(result & VMFlags.VM_FS)); + } + } break; - case VMCommands.VM_ADD: + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int result = + (int) + (((value1 + (long)GetValue(cmd.IsByteMode, Mem, op2))) & + unchecked((int)0xffffffff)); + if (cmd.IsByteMode) { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - 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=(Result value1) ? 1 : 0 | (result & (int) VMFlags.VM_FS))); - SetValue(cmd.IsByteMode, Mem, op1, result); // (Cmd->ByteMode,Op1,Result); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int result = + (int) + (value1 & 0xffFFffFF - GetValue(cmd.IsByteMode, Mem, op2) & + unchecked((int)0xFFffFFff)); + flags = + (VMFlags) + ((result == 0) + ? (int)VMFlags.VM_FZ + : ((result > value1) ? 1 : 0 | (result & (int)VMFlags.VM_FS))); + SetValue(cmd.IsByteMode, Mem, op1, result); // (Cmd->ByteMode,Op1,Result); + } break; - case VMCommands.VM_SUBB: SetValue(true, Mem, op1, (int) - ((long) GetValue(true, Mem, op1) & 0xFFffFFff - (long) GetValue(true, Mem, op2) & - unchecked((int) 0xFFffFFff))); + (GetValue(true, Mem, op1) & 0xFFffFFff - 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))); + (GetValue(false, Mem, op1) & 0xFFffFFff - GetValue(false, Mem, op2) & + unchecked((int)0xFFffFFff))); break; - case VMCommands.VM_JZ: if ((flags & VMFlags.VM_FZ) != 0) { @@ -394,79 +385,75 @@ namespace SharpCompress.Compressor.Rar.VM break; case VMCommands.VM_INC: + { + int result = (int)(GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFffL + 1L); + if (cmd.IsByteMode) { - 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); + result &= 0xff; } + + SetValue(cmd.IsByteMode, Mem, op1, result); + 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)(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)(GetValue(false, Mem, op1) & 0xFFffFFffL + 1L)); break; - case VMCommands.VM_DEC: - { - 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); - } + { + int result = (int)(GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFff - 1); + SetValue(cmd.IsByteMode, Mem, op1, result); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + } break; - case VMCommands.VM_DECB: - SetValue(true, Mem, op1, (int) ((long) GetValue(true, Mem, op1) & 0xFFffFFff - 1)); + SetValue(true, Mem, op1, (int)(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)(GetValue(false, Mem, op1) & 0xFFffFFff - 1)); break; - case VMCommands.VM_JMP: setIP(GetValue(false, Mem, op1)); continue; case VMCommands.VM_XOR: - { - int result = GetValue(cmd.IsByteMode, Mem, op1) ^ GetValue(cmd.IsByteMode, Mem, op2); - flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = GetValue(cmd.IsByteMode, Mem, op1) ^ GetValue(cmd.IsByteMode, Mem, op2); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_AND: - { - int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2); - flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_OR: - { - int result = GetValue(cmd.IsByteMode, Mem, op1) | GetValue(cmd.IsByteMode, Mem, op2); - flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = GetValue(cmd.IsByteMode, Mem, op1) | GetValue(cmd.IsByteMode, Mem, op2); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_TEST: - { - int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2); - flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS); - } + { + int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2); + flags = (VMFlags)(result == 0 ? (int)VMFlags.VM_FZ : result & (int)VMFlags.VM_FS); + } break; case VMCommands.VM_JS: @@ -538,59 +525,58 @@ namespace SharpCompress.Compressor.Rar.VM break; case VMCommands.VM_SHL: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int value2 = GetValue(cmd.IsByteMode, Mem, op2); - int result = value1 << value2; - flags = - (VMFlags) - ((result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS)) | - (((value1 << (value2 - 1)) & unchecked((int) 0x80000000)) != 0 - ? (int) VMFlags.VM_FC - : 0)); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int value2 = GetValue(cmd.IsByteMode, Mem, op2); + int result = value1 << value2; + flags = + (VMFlags) + ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | + (((value1 << (value2 - 1)) & unchecked((int)0x80000000)) != 0 + ? (int)VMFlags.VM_FC + : 0)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_SHR: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int value2 = GetValue(cmd.IsByteMode, Mem, op2); - int result = Utility.URShift(value1, value2); - flags = - (VMFlags) - ((result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS)) | - ((Utility.URShift(value1, (value2 - 1))) & (int) VMFlags.VM_FC)); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int value2 = GetValue(cmd.IsByteMode, Mem, op2); + int result = Utility.URShift(value1, value2); + flags = + (VMFlags) + ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | + ((Utility.URShift(value1, (value2 - 1))) & (int)VMFlags.VM_FC)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_SAR: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - int value2 = GetValue(cmd.IsByteMode, Mem, op2); - int result = ((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); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int value2 = GetValue(cmd.IsByteMode, Mem, op2); + int result = value1 >> value2; + flags = + (VMFlags) + ((result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS)) | + ((value1 >> (value2 - 1)) & (int)VMFlags.VM_FC)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_NEG: - { - int result = -GetValue(cmd.IsByteMode, Mem, op1); - flags = - (VMFlags) - (result == 0 - ? (int) VMFlags.VM_FZ - : (int) VMFlags.VM_FC | (result & (int) VMFlags.VM_FS)); - SetValue(cmd.IsByteMode, Mem, op1, result); - } + { + int result = -GetValue(cmd.IsByteMode, Mem, op1); + flags = + (VMFlags) + (result == 0 + ? (int)VMFlags.VM_FZ + : (int)VMFlags.VM_FC | (result & (int)VMFlags.VM_FS)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; - case VMCommands.VM_NEGB: SetValue(true, Mem, op1, -GetValue(true, Mem, op1)); break; @@ -600,29 +586,31 @@ namespace SharpCompress.Compressor.Rar.VM break; case VMCommands.VM_PUSHA: + { + for (int i = 0, SP = R[7] - 4; i < regCount; i++, SP -= 4) { - for (int i = 0, SP = R[7] - 4; i < regCount; i++, SP -= 4) - { - SetValue(false, Mem, SP & VM_MEMMASK, R[i]); - } - R[7] -= regCount*4; + SetValue(false, Mem, SP & VM_MEMMASK, R[i]); } + R[7] -= regCount * 4; + } break; case VMCommands.VM_POPA: + { + for (int i = 0, SP = R[7]; i < regCount; i++, SP += 4) { - for (int i = 0, SP = R[7]; i < regCount; i++, SP += 4) - R[7 - i] = GetValue(false, Mem, SP & VM_MEMMASK); + R[7 - i] = GetValue(false, Mem, SP & VM_MEMMASK); } + } break; 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; @@ -631,83 +619,82 @@ 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: - { - int value1 = GetValue(cmd.IsByteMode, Mem, op1); - SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2)); - SetValue(cmd.IsByteMode, Mem, op2, value1); - } + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2)); + SetValue(cmd.IsByteMode, Mem, op2, value1); + } break; case VMCommands.VM_MUL: - { - int result = - (int) - (((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); - } + { + int result = + (int) + ((GetValue(cmd.IsByteMode, Mem, op1) & + 0xFFffFFff * GetValue(cmd.IsByteMode, Mem, op2) & unchecked((int)0xFFffFFff)) & + unchecked((int)0xFFffFFff)); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_DIV: + { + int divider = GetValue(cmd.IsByteMode, Mem, op2); + if (divider != 0) { - int divider = GetValue(cmd.IsByteMode, Mem, op2); - if (divider != 0) - { - int result = GetValue(cmd.IsByteMode, Mem, op1)/divider; - SetValue(cmd.IsByteMode, Mem, op1, result); - } + int result = GetValue(cmd.IsByteMode, Mem, op1) / divider; + SetValue(cmd.IsByteMode, Mem, op1, result); } + } break; case VMCommands.VM_ADC: + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int FC = (int)(flags & VMFlags.VM_FC); + int result = + (int) + (value1 & 0xFFffFFff + GetValue(cmd.IsByteMode, Mem, op2) & + 0xFFffFFff + FC & unchecked((int)0xFFffFFff)); + if (cmd.IsByteMode) { - 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)); - if (cmd.IsByteMode) - { - result &= 0xff; - } - - flags = - (VMFlags) - ((result < value1 || result == value1 && FC != 0) - ? 1 - : 0 | (result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS))); - SetValue(cmd.IsByteMode, Mem, op1, result); + result &= 0xff; } + + flags = + (VMFlags) + ((result < value1 || result == value1 && FC != 0) + ? 1 + : 0 | (result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS))); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; case VMCommands.VM_SBB: + { + int value1 = GetValue(cmd.IsByteMode, Mem, op1); + int FC = (int)(flags & VMFlags.VM_FC); + int result = + (int) + (value1 & 0xFFffFFff - GetValue(cmd.IsByteMode, Mem, op2) & + 0xFFffFFff - FC & unchecked((int)0xFFffFFff)); + if (cmd.IsByteMode) { - 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)); - if (cmd.IsByteMode) - { - result &= 0xff; - } - flags = - (VMFlags) - ((result > value1 || result == value1 && FC != 0) - ? 1 - : 0 | (result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS))); - SetValue(cmd.IsByteMode, Mem, op1, result); + result &= 0xff; } + flags = + (VMFlags) + ((result > value1 || result == value1 && FC != 0) + ? 1 + : 0 | (result == 0 ? (int)VMFlags.VM_FZ : (result & (int)VMFlags.VM_FS))); + SetValue(cmd.IsByteMode, Mem, op1, result); + } break; - case VMCommands.VM_RET: if (R[7] >= VM_MEMSIZE) { @@ -717,9 +704,8 @@ namespace SharpCompress.Compressor.Rar.VM R[7] += 4; continue; - case VMCommands.VM_STANDARD: - ExecuteStandardFilter((VMStandardFilters) (cmd.Op1.Data)); + ExecuteStandardFilter((VMStandardFilters)(cmd.Op1.Data)); break; case VMCommands.VM_PRINT: @@ -733,7 +719,8 @@ namespace SharpCompress.Compressor.Rar.VM public void prepare(byte[] code, int codeSize, VMPreparedProgram prg) { InitBitInput(); - int cpLength = System.Math.Min(MAX_SIZE, codeSize); + int cpLength = Math.Min(MAX_SIZE, codeSize); + // memcpy(inBuf,Code,Min(CodeSize,BitInput::MAX_SIZE)); Buffer.BlockCopy(code, 0, InBuf, 0, cpLength); @@ -753,12 +740,13 @@ namespace SharpCompress.Compressor.Rar.VM { 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; prg.Commands.Add(curCmd); prg.CommandCount = prg.CommandCount + 1; + // TODO // curCmd->Op1.Data=FilterType; // >>>>>> CurCmd->Op1.Addr=&CurCmd->Op1.Data; <<<<<<<<<< not set @@ -776,10 +764,10 @@ namespace SharpCompress.Compressor.Rar.VM if ((dataFlag & 0x8000) != 0) { - long dataSize = (long) ((long) ReadData(this) & 0xffFFffFFL + 1L); + long dataSize = 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); } } @@ -790,15 +778,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); @@ -810,22 +798,27 @@ 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) { decodeArg(curCmd.Op1, curCmd.IsByteMode); if (opNum == 2) + { decodeArg(curCmd.Op2, curCmd.IsByteMode); + } else { if (curCmd.Op1.Type == VMOpType.VM_OPINT && - (VMCmdFlags.VM_CmdFlags[(int) curCmd.OpCode] & + (VMCmdFlags.VM_CmdFlags[(int)curCmd.OpCode] & (VMCmdFlags.VMCF_JUMP | VMCmdFlags.VMCF_PROC)) != 0) { int distance = curCmd.Op1.Data; if (distance >= 256) + { distance -= 256; + } else { if (distance >= 136) @@ -858,6 +851,7 @@ namespace SharpCompress.Compressor.Rar.VM } VMPreparedCommand curCmd2 = new VMPreparedCommand(); curCmd2.OpCode = VMCommands.VM_RET; + // TODO CurCmd->Op1.Addr=&CurCmd->Op1.Data; // CurCmd->Op2.Addr=&CurCmd->Op2.Data; curCmd2.Op1.Type = VMOpType.VM_OPNONE; @@ -874,6 +868,7 @@ namespace SharpCompress.Compressor.Rar.VM prg.Commands.Add(curCmd2); prg.CommandCount = prg.CommandCount + 1; + // #ifdef VM_OPTIMIZE if (codeSize != 0) { @@ -941,6 +936,7 @@ namespace SharpCompress.Compressor.Rar.VM //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 commands = prg.Commands; + //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'" foreach (VMPreparedCommand cmd in commands) { @@ -954,7 +950,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; } @@ -962,7 +958,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; @@ -1014,7 +1010,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 @@ -1042,23 +1038,23 @@ namespace SharpCompress.Compressor.Rar.VM 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(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++) { @@ -1076,348 +1072,371 @@ namespace SharpCompress.Compressor.Rar.VM { case VMStandardFilters.VMSF_E8: case VMStandardFilters.VMSF_E8E9: - { - int dataSize = R[4]; - long fileOffset = R[6] & unchecked((int) 0xFFffFFff); + { + int dataSize = R[4]; + long fileOffset = R[6] & unchecked((int)0xFFffFFff); - if (dataSize >= VM_GLOBALMEMADDR) + if (dataSize >= VM_GLOBALMEMADDR) + { + break; + } + int fileSize = 0x1000000; + byte cmpByte2 = (byte)((filterType == VMStandardFilters.VMSF_E8E9) ? 0xe9 : 0xe8); + for (int curPos = 0; curPos < dataSize - 4;) + { + byte curByte = Mem[curPos++]; + if (curByte == 0xe8 || curByte == cmpByte2) { - break; - } - int fileSize = 0x1000000; - byte cmpByte2 = (byte) ((filterType == VMStandardFilters.VMSF_E8E9) ? 0xe9 : 0xe8); - for (int curPos = 0; curPos < dataSize - 4;) - { - byte curByte = Mem[curPos++]; - if (curByte == 0xe8 || curByte == cmpByte2) + // #ifdef PRESENT_INT32 + // sint32 Offset=CurPos+FileOffset; + // sint32 Addr=GET_VALUE(false,Data); + // if (Addr<0) + // { + // if (Addr+Offset>=0) + // SET_VALUE(false,Data,Addr+FileSize); + // } + // else + // if (Addr=0) - // SET_VALUE(false,Data,Addr+FileSize); - // } - // else - // if (Addr= VM_GLOBALMEMADDR) { - int dataSize = R[4]; - long fileOffset = R[6] & unchecked((int) 0xFFffFFff); - - if (dataSize >= VM_GLOBALMEMADDR) - { - break; - } - int curPos = 0; - //UPGRADE_NOTE: Final was removed from the declaration of 'Masks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - byte[] Masks = 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) - { - int Byte = (Mem[curPos] & 0x1f) - 0x10; - if (Byte >= 0) - { - byte cmdMask = Masks[Byte]; - if (cmdMask != 0) - for (int i = 0; i <= 2; i++) - if ((cmdMask & (1 << i)) != 0) - { - int startPos = i*41 + 5; - int opType = filterItanium_GetBits(curPos, startPos + 37, 4); - if (opType == 5) - { - int offset = filterItanium_GetBits(curPos, startPos + 13, 20); - filterItanium_SetBits(curPos, (int) (offset - fileOffset) & 0xfffff, - startPos + 13, 20); - } - } - } - curPos += 16; - fileOffset++; - } + break; } + int curPos = 0; + + //UPGRADE_NOTE: Final was removed from the declaration of 'Masks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + byte[] Masks = {4, 4, 6, 6, 0, 0, 7, 7, 4, 4, 0, 0, 4, 4, 0, 0}; + fileOffset = Utility.URShift(fileOffset, 4); + + while (curPos < dataSize - 21) + { + int Byte = (Mem[curPos] & 0x1f) - 0x10; + if (Byte >= 0) + { + byte cmdMask = Masks[Byte]; + if (cmdMask != 0) + { + for (int i = 0; i <= 2; i++) + { + if ((cmdMask & (1 << i)) != 0) + { + int startPos = i * 41 + 5; + int opType = filterItanium_GetBits(curPos, startPos + 37, 4); + if (opType == 5) + { + int offset = filterItanium_GetBits(curPos, startPos + 13, 20); + filterItanium_SetBits(curPos, (int)(offset - fileOffset) & 0xfffff, + startPos + 13, 20); + } + } + } + } + } + curPos += 16; + fileOffset++; + } + } break; case VMStandardFilters.VMSF_DELTA: + { + int dataSize = R[4] & unchecked((int)0xFFffFFff); + int channels = R[0] & unchecked((int)0xFFffFFff); + int srcPos = 0; + int border = (dataSize * 2) & unchecked((int)0xFFffFFff); + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); + if (dataSize >= VM_GLOBALMEMADDR / 2) { - 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) - { - break; - } - // bytes from same channels are grouped to continual data blocks, - // so we need to place them back to their interleaving positions + break; + } - for (int curChannel = 0; curChannel < channels; curChannel++) + // bytes from same channels are grouped to continual data blocks, + // so we need to place them back to their interleaving positions + + for (int curChannel = 0; curChannel < channels; curChannel++) + { + byte PrevByte = 0; + for (int destPos = dataSize + curChannel; destPos < border; destPos += channels) { - 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++])); } } + } break; case VMStandardFilters.VMSF_RGB: + { + // byte *SrcData=Mem,*DestData=SrcData+DataSize; + int dataSize = R[4], width = R[0] - 3, posR = R[1]; + int channels = 3; + int srcPos = 0; + int destDataPos = dataSize; + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); + if (dataSize >= VM_GLOBALMEMADDR / 2 || posR < 0) { - // byte *SrcData=Mem,*DestData=SrcData+DataSize; - int dataSize = R[4], width = R[0] - 3, posR = R[1]; - int channels = 3; - int srcPos = 0; - int destDataPos = dataSize; - SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); - if (dataSize >= VM_GLOBALMEMADDR/2 || posR < 0) - { - break; - } - for (int curChannel = 0; curChannel < channels; curChannel++) - { - long prevByte = 0; + break; + } + for (int curChannel = 0; curChannel < channels; curChannel++) + { + long prevByte = 0; - for (int i = curChannel; i < dataSize; i += channels) + for (int i = curChannel; i < dataSize; i += channels) + { + long predicted; + int upperPos = i - width; + if (upperPos >= 3) { - long predicted; - int upperPos = i - width; - if (upperPos >= 3) - { - int upperDataPos = destDataPos + upperPos; - 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)); - if (pa <= pb && pa <= pc) - { - predicted = prevByte; - } - else - { - if (pb <= pc) - { - predicted = upperByte; - } - else - { - predicted = upperLeftByte; - } - } - } - else + int upperDataPos = destDataPos + upperPos; + int upperByte = Mem[upperDataPos] & 0xff; + int upperLeftByte = Mem[upperDataPos - 3] & 0xff; + predicted = prevByte + upperByte - upperLeftByte; + int pa = Math.Abs((int)(predicted - prevByte)); + int pb = Math.Abs((int)(predicted - upperByte)); + int pc = Math.Abs((int)(predicted - upperLeftByte)); + if (pa <= pb && pa <= pc) { predicted = prevByte; } - - prevByte = (predicted - Mem[srcPos++] & 0xff) & 0xff; - Mem[destDataPos + i] = (byte) (prevByte & 0xff); + else + { + if (pb <= pc) + { + predicted = upperByte; + } + else + { + predicted = upperLeftByte; + } + } } - } - 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); + else + { + predicted = prevByte; + } + + prevByte = (predicted - Mem[srcPos++] & 0xff) & 0xff; + Mem[destDataPos + i] = (byte)(prevByte & 0xff); } } + for (int i = posR, border = dataSize - 2; i < border; i += 3) + { + byte G = Mem[destDataPos + i + 1]; + Mem[destDataPos + i] = (byte)(Mem[destDataPos + i] + G); + Mem[destDataPos + i + 2] = (byte)(Mem[destDataPos + i + 2] + G); + } + } break; case VMStandardFilters.VMSF_AUDIO: + { + int dataSize = R[4], channels = R[0]; + int srcPos = 0; + int destDataPos = dataSize; + + //byte *SrcData=Mem,*DestData=SrcData+DataSize; + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); + if (dataSize >= VM_GLOBALMEMADDR / 2) { - int dataSize = R[4], channels = R[0]; - int srcPos = 0; - int destDataPos = dataSize; - //byte *SrcData=Mem,*DestData=SrcData+DataSize; - SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); - if (dataSize >= VM_GLOBALMEMADDR/2) - { - break; - } - for (int curChannel = 0; curChannel < channels; curChannel++) - { - long prevByte = 0; - long prevDelta = 0; - long[] Dif = new long[7]; - int D1 = 0, D2 = 0, D3; - int K1 = 0, K2 = 0, K3 = 0; + break; + } + for (int curChannel = 0; curChannel < channels; curChannel++) + { + long prevByte = 0; + long prevDelta = 0; + long[] Dif = new long[7]; + int D1 = 0, D2 = 0, D3; + int K1 = 0, K2 = 0, K3 = 0; - for (int i = curChannel, byteCount = 0; i < dataSize; i += channels, byteCount++) + for (int i = curChannel, byteCount = 0; i < dataSize; i += channels, byteCount++) + { + D3 = D2; + D2 = (int)(prevDelta - D1); + D1 = (int)prevDelta; + + long predicted = 8 * prevByte + K1 * D1 + K2 * D2 + K3 * D3; + predicted = Utility.URShift(predicted, 3) & 0xff; + + long curByte = Mem[srcPos++]; + + predicted -= curByte; + Mem[destDataPos + i] = (byte)predicted; + prevDelta = (byte)(predicted - prevByte); + + //fix java byte + if (prevDelta >= 128) { - D3 = D2; - D2 = (int) (prevDelta - D1); - D1 = (int) prevDelta; + prevDelta = 0 - (256 - prevDelta); + } + prevByte = predicted; - long predicted = 8*prevByte + K1*D1 + K2*D2 + K3*D3; - predicted = Utility.URShift(predicted, 3) & 0xff; + //fix java byte + if (curByte >= 128) + { + curByte = 0 - (256 - curByte); + } + int D = ((int)curByte) << 3; - long curByte = (long) (Mem[srcPos++]); + Dif[0] += Math.Abs(D); + Dif[1] += Math.Abs(D - D1); + Dif[2] += Math.Abs(D + D1); + Dif[3] += Math.Abs(D - D2); + Dif[4] += Math.Abs(D + D2); + Dif[5] += Math.Abs(D - D3); + Dif[6] += Math.Abs(D + D3); - predicted -= curByte; - Mem[destDataPos + i] = (byte) predicted; - prevDelta = (byte) (predicted - prevByte); - //fix java byte - if (prevDelta >= 128) + if ((byteCount & 0x1f) == 0) + { + long minDif = Dif[0], numMinDif = 0; + Dif[0] = 0; + for (int j = 1; j < Dif.Length; j++) { - prevDelta = 0 - (256 - prevDelta); - } - prevByte = predicted; - //fix java byte - if (curByte >= 128) - { - curByte = 0 - (256 - curByte); - } - int D = ((int) curByte) << 3; - - Dif[0] += System.Math.Abs(D); - Dif[1] += System.Math.Abs(D - D1); - Dif[2] += System.Math.Abs(D + D1); - Dif[3] += System.Math.Abs(D - D2); - Dif[4] += System.Math.Abs(D + D2); - Dif[5] += System.Math.Abs(D - D3); - Dif[6] += System.Math.Abs(D + D3); - - if ((byteCount & 0x1f) == 0) - { - long minDif = Dif[0], numMinDif = 0; - Dif[0] = 0; - for (int j = 1; j < Dif.Length; j++) + if (Dif[j] < minDif) { - if (Dif[j] < minDif) + minDif = Dif[j]; + numMinDif = j; + } + Dif[j] = 0; + } + switch ((int)numMinDif) + { + case 1: + if (K1 >= -16) { - minDif = Dif[j]; - numMinDif = j; + K1--; } - Dif[j] = 0; - } - switch ((int) numMinDif) - { - case 1: - if (K1 >= -16) - K1--; - break; + break; - case 2: - if (K1 < 16) - K1++; - break; + case 2: + if (K1 < 16) + { + K1++; + } + break; - case 3: - if (K2 >= -16) - K2--; - break; + case 3: + if (K2 >= -16) + { + K2--; + } + break; - case 4: - if (K2 < 16) - K2++; - break; + case 4: + if (K2 < 16) + { + K2++; + } + break; - case 5: - if (K3 >= -16) - K3--; - break; + case 5: + if (K3 >= -16) + { + K3--; + } + break; - case 6: - if (K3 < 16) - K3++; - break; - } + case 6: + if (K3 < 16) + { + K3++; + } + break; } } } } + } break; case VMStandardFilters.VMSF_UPCASE: + { + int dataSize = R[4], srcPos = 0, destPos = dataSize; + if (dataSize >= VM_GLOBALMEMADDR / 2) { - int dataSize = R[4], srcPos = 0, destPos = dataSize; - if (dataSize >= VM_GLOBALMEMADDR/2) - { - break; - } - while (srcPos < dataSize) - { - byte curByte = Mem[srcPos++]; - if (curByte == 2 && (curByte = Mem[srcPos++]) != 2) - { - curByte = (byte) (curByte - 32); - } - Mem[destPos++] = curByte; - } - SetValue(false, Mem, VM_GLOBALMEMADDR + 0x1c, destPos - dataSize); - SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); + break; } + while (srcPos < dataSize) + { + byte curByte = Mem[srcPos++]; + if (curByte == 2 && (curByte = Mem[srcPos++]) != 2) + { + curByte = (byte)(curByte - 32); + } + Mem[destPos++] = curByte; + } + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x1c, destPos - dataSize); + SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize); + } break; } } 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 = Mem[curPos + inAddr++] & 0xff; + bitField |= (Mem[curPos + inAddr++] & 0xff) << 8; + bitField |= (Mem[curPos + inAddr++] & 0xff) << 16; + bitField |= (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)))); } - public virtual void setMemory(int pos, byte[] data, int offset, int dataSize) { if (pos < VM_MEMSIZE) { //&& data!=Mem+Pos) //memmove(Mem+Pos,Data,Min(DataSize,VM_MEMSIZE-Pos)); - for (int i = 0; i < System.Math.Min(data.Length - offset, dataSize); i++) + for (int i = 0; i < Math.Min(data.Length - offset, dataSize); i++) { if ((VM_MEMSIZE - pos) < i) { diff --git a/src/SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs b/src/SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs index ebe947bb..40ce0920 100644 --- a/src/SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs +++ b/src/SharpCompress/Compressor/Rar/VM/VMCmdFlags.cs @@ -12,35 +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 = + { + 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/src/SharpCompress/Compressor/Rar/VM/VMCommands.cs b/src/SharpCompress/Compressor/Rar/VM/VMCommands.cs index 6af86b24..c2ae0658 100644 --- a/src/SharpCompress/Compressor/Rar/VM/VMCommands.cs +++ b/src/SharpCompress/Compressor/Rar/VM/VMCommands.cs @@ -73,6 +73,6 @@ namespace SharpCompress.Compressor.Rar.VM VM_NEGB = 52, VM_NEGD = 53, - VM_STANDARD = 54, + VM_STANDARD = 54 } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Rar/VM/VMFlags.cs b/src/SharpCompress/Compressor/Rar/VM/VMFlags.cs index 2e5cd9d4..b2413574 100644 --- a/src/SharpCompress/Compressor/Rar/VM/VMFlags.cs +++ b/src/SharpCompress/Compressor/Rar/VM/VMFlags.cs @@ -5,6 +5,6 @@ namespace SharpCompress.Compressor.Rar.VM None = 0, VM_FC = 1, VM_FZ = 2, - VM_FS = 80000000, + VM_FS = 80000000 } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Rar/VM/VMOpType.cs b/src/SharpCompress/Compressor/Rar/VM/VMOpType.cs index 0c26d0f7..467665b6 100644 --- a/src/SharpCompress/Compressor/Rar/VM/VMOpType.cs +++ b/src/SharpCompress/Compressor/Rar/VM/VMOpType.cs @@ -5,6 +5,6 @@ namespace SharpCompress.Compressor.Rar.VM VM_OPREG = 0, VM_OPINT = 1, VM_OPREGMEM = 2, - VM_OPNONE = 3, + VM_OPNONE = 3 } } \ No newline at end of file diff --git a/src/SharpCompress/Compressor/Rar/VM/VMStandardFilterSignature.cs b/src/SharpCompress/Compressor/Rar/VM/VMStandardFilterSignature.cs index 5b86b2cc..d36af1c1 100644 --- a/src/SharpCompress/Compressor/Rar/VM/VMStandardFilterSignature.cs +++ b/src/SharpCompress/Compressor/Rar/VM/VMStandardFilterSignature.cs @@ -4,9 +4,9 @@ namespace SharpCompress.Compressor.Rar.VM { internal VMStandardFilterSignature(int length, uint crc, VMStandardFilters type) { - this.Length = length; + Length = length; CRC = crc; - this.Type = type; + Type = type; } internal int Length { get; private set; } diff --git a/src/SharpCompress/Compressor/Rar/VM/VMStandardFilters.cs b/src/SharpCompress/Compressor/Rar/VM/VMStandardFilters.cs index fc9db51e..2cb5004b 100644 --- a/src/SharpCompress/Compressor/Rar/VM/VMStandardFilters.cs +++ b/src/SharpCompress/Compressor/Rar/VM/VMStandardFilters.cs @@ -9,6 +9,6 @@ namespace SharpCompress.Compressor.Rar.VM VMSF_RGB = 4, VMSF_AUDIO = 5, VMSF_DELTA = 6, - VMSF_UPCASE = 7, + VMSF_UPCASE = 7 } } \ No newline at end of file diff --git a/src/SharpCompress/Converter/DataConverter.cs b/src/SharpCompress/Converter/DataConverter.cs index 6098c887..84f5fac1 100644 --- a/src/SharpCompress/Converter/DataConverter.cs +++ b/src/SharpCompress/Converter/DataConverter.cs @@ -38,606 +38,761 @@ // using System; -using System.Collections; -using System.Text; -using System.Collections.Generic; #pragma warning disable 3021 -namespace SharpCompress.Converter { - +namespace SharpCompress.Converter +{ #if MONO_DATACONVERTER_PUBLIC public #endif - unsafe abstract class DataConverter { -// Disables the warning: CLS compliance checking will not be performed on -// `XXXX' because it is not visible from outside this assembly + unsafe abstract class DataConverter + { + // Disables the warning: CLS compliance checking will not be performed on + // `XXXX' because it is not visible from outside this assembly #pragma warning disable 3019 - static readonly DataConverter SwapConv = new SwapConverter (); - static readonly DataConverter CopyConv = new CopyConverter (); - - public static readonly bool IsLittleEndian = BitConverter.IsLittleEndian; - - public abstract double GetDouble (byte [] data, int index); - public abstract float GetFloat (byte [] data, int index); - public abstract long GetInt64 (byte [] data, int index); - public abstract int GetInt32 (byte [] data, int index); - - public abstract short GetInt16 (byte [] data, int index); - - [CLSCompliant (false)] - public abstract uint GetUInt32 (byte [] data, int index); - [CLSCompliant (false)] - public abstract ushort GetUInt16 (byte [] data, int index); - [CLSCompliant (false)] - public abstract ulong GetUInt64 (byte [] data, int index); - - public abstract void PutBytes (byte [] dest, int destIdx, double value); - public abstract void PutBytes (byte [] dest, int destIdx, float value); - public abstract void PutBytes (byte [] dest, int destIdx, int value); - public abstract void PutBytes (byte [] dest, int destIdx, long value); - public abstract void PutBytes (byte [] dest, int destIdx, short value); - - [CLSCompliant (false)] - public abstract void PutBytes (byte [] dest, int destIdx, ushort value); - [CLSCompliant (false)] - public abstract void PutBytes (byte [] dest, int destIdx, uint value); - [CLSCompliant (false)] - public abstract void PutBytes (byte [] dest, int destIdx, ulong value); - - public byte[] GetBytes (double value) - { - byte [] ret = new byte [8]; - PutBytes (ret, 0, value); - return ret; - } - - public byte[] GetBytes (float value) - { - byte [] ret = new byte [4]; - PutBytes (ret, 0, value); - return ret; - } - - public byte[] GetBytes (int value) - { - byte [] ret = new byte [4]; - PutBytes (ret, 0, value); - return ret; - } - - public byte[] GetBytes (long value) - { - byte [] ret = new byte [8]; - PutBytes (ret, 0, value); - return ret; - } - - public byte[] GetBytes (short value) - { - byte [] ret = new byte [2]; - PutBytes (ret, 0, value); - return ret; - } - - [CLSCompliant (false)] - public byte[] GetBytes (ushort value) - { - byte [] ret = new byte [2]; - PutBytes (ret, 0, value); - return ret; - } - - [CLSCompliant (false)] - public byte[] GetBytes (uint value) - { - byte [] ret = new byte [4]; - PutBytes (ret, 0, value); - return ret; - } - - [CLSCompliant (false)] - public byte[] GetBytes (ulong value) - { - byte [] ret = new byte [8]; - PutBytes (ret, 0, value); - return ret; - } - - static public DataConverter LittleEndian { - get { - return BitConverter.IsLittleEndian ? CopyConv : SwapConv; - } - } - - static public DataConverter BigEndian { - get { - return BitConverter.IsLittleEndian ? SwapConv : CopyConv; - } - } - - static public DataConverter Native { - get { - return CopyConv; - } - } - - internal void Check (byte [] dest, int destIdx, int size) - { - if (dest == null) - throw new ArgumentNullException ("dest"); - if (destIdx < 0 || destIdx > dest.Length - size) - throw new ArgumentException ("destIdx"); - } - - class CopyConverter : DataConverter { - public override double GetDouble (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 8) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - double ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 8; i++) - b [i] = data [index+i]; - - return ret; - } - - public override ulong GetUInt64 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 8) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - ulong ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 8; i++) - b [i] = data [index+i]; - - return ret; - } - - public override long GetInt64 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 8) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - long ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 8; i++) - b [i] = data [index+i]; - - return ret; - } - - public override float GetFloat (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 4) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - float ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 4; i++) - b [i] = data [index+i]; - - return ret; - } - - public override int GetInt32 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 4) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - int ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 4; i++) - b [i] = data [index+i]; - - return ret; - } - - public override uint GetUInt32 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 4) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - uint ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 4; i++) - b [i] = data [index+i]; - - return ret; - } - - public override short GetInt16 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 2) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - short ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 2; i++) - b [i] = data [index+i]; - - return ret; - } - - public override ushort GetUInt16 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 2) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - ushort ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 2; i++) - b [i] = data [index+i]; - - return ret; - } - - public override void PutBytes (byte [] dest, int destIdx, double value) - { - Check (dest, destIdx, 8); - fixed (byte *target = &dest [destIdx]){ - long *source = (long *) &value; - - *((long *)target) = *source; - } - } - - public override void PutBytes (byte [] dest, int destIdx, float value) - { - Check (dest, destIdx, 4); - fixed (byte *target = &dest [destIdx]){ - uint *source = (uint *) &value; - - *((uint *)target) = *source; - } - } - - public override void PutBytes (byte [] dest, int destIdx, int value) - { - Check (dest, destIdx, 4); - fixed (byte *target = &dest [destIdx]){ - uint *source = (uint *) &value; - - *((uint *)target) = *source; - } - } - - public override void PutBytes (byte [] dest, int destIdx, uint value) - { - Check (dest, destIdx, 4); - fixed (byte *target = &dest [destIdx]){ - uint *source = (uint *) &value; - - *((uint *)target) = *source; - } - } - - public override void PutBytes (byte [] dest, int destIdx, long value) - { - Check (dest, destIdx, 8); - fixed (byte *target = &dest [destIdx]){ - long *source = (long *) &value; - - *((long*)target) = *source; - } - } - - public override void PutBytes (byte [] dest, int destIdx, ulong value) - { - Check (dest, destIdx, 8); - fixed (byte *target = &dest [destIdx]){ - ulong *source = (ulong *) &value; - - *((ulong *) target) = *source; - } - } - - public override void PutBytes (byte [] dest, int destIdx, short value) - { - Check (dest, destIdx, 2); - fixed (byte *target = &dest [destIdx]){ - ushort *source = (ushort *) &value; - - *((ushort *)target) = *source; - } - } - - public override void PutBytes (byte [] dest, int destIdx, ushort value) - { - Check (dest, destIdx, 2); - fixed (byte *target = &dest [destIdx]){ - ushort *source = (ushort *) &value; - - *((ushort *)target) = *source; - } - } - } - - class SwapConverter : DataConverter { - public override double GetDouble (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 8) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - double ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 8; i++) - b [7-i] = data [index+i]; - - return ret; - } - - public override ulong GetUInt64 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 8) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - ulong ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 8; i++) - b [7-i] = data [index+i]; - - return ret; - } - - public override long GetInt64 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 8) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - long ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 8; i++) - b [7-i] = data [index+i]; - - return ret; - } - - public override float GetFloat (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 4) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - float ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 4; i++) - b [3-i] = data [index+i]; - - return ret; - } - - public override int GetInt32 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 4) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - int ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 4; i++) - b [3-i] = data [index+i]; - - return ret; - } - - public override uint GetUInt32 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 4) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - uint ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 4; i++) - b [3-i] = data [index+i]; - - return ret; - } - - public override short GetInt16 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 2) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - short ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 2; i++) - b [1-i] = data [index+i]; - - return ret; - } - - public override ushort GetUInt16 (byte [] data, int index) - { - if (data == null) - throw new ArgumentNullException ("data"); - if (data.Length - index < 2) - throw new ArgumentException ("index"); - if (index < 0) - throw new ArgumentException ("index"); - - ushort ret; - byte *b = (byte *)&ret; - - for (int i = 0; i < 2; i++) - b [1-i] = data [index+i]; - - return ret; - } - - public override void PutBytes (byte [] dest, int destIdx, double value) - { - Check (dest, destIdx, 8); - - fixed (byte *target = &dest [destIdx]){ - byte *source = (byte *) &value; - - for (int i = 0; i < 8; i++) - target [i] = source [7-i]; - } - } - - public override void PutBytes (byte [] dest, int destIdx, float value) - { - Check (dest, destIdx, 4); - - fixed (byte *target = &dest [destIdx]){ - byte *source = (byte *) &value; - - for (int i = 0; i < 4; i++) - target [i] = source [3-i]; - } - } - - public override void PutBytes (byte [] dest, int destIdx, int value) - { - Check (dest, destIdx, 4); - - fixed (byte *target = &dest [destIdx]){ - byte *source = (byte *) &value; - - for (int i = 0; i < 4; i++) - target [i] = source [3-i]; - } - } - - public override void PutBytes (byte [] dest, int destIdx, uint value) - { - Check (dest, destIdx, 4); - - fixed (byte *target = &dest [destIdx]){ - byte *source = (byte *) &value; - - for (int i = 0; i < 4; i++) - target [i] = source [3-i]; - } - } - - public override void PutBytes (byte [] dest, int destIdx, long value) - { - Check (dest, destIdx, 8); - - fixed (byte *target = &dest [destIdx]){ - byte *source = (byte *) &value; - - for (int i = 0; i < 8; i++) - target [i] = source [7-i]; - } - } - - public override void PutBytes (byte [] dest, int destIdx, ulong value) - { - Check (dest, destIdx, 8); - - fixed (byte *target = &dest [destIdx]){ - byte *source = (byte *) &value; - - for (int i = 0; i < 8; i++) - target [i] = source [7-i]; - } - } - - public override void PutBytes (byte [] dest, int destIdx, short value) - { - Check (dest, destIdx, 2); - - fixed (byte *target = &dest [destIdx]){ - byte *source = (byte *) &value; - - for (int i = 0; i < 2; i++) - target [i] = source [1-i]; - } - } - - public override void PutBytes (byte [] dest, int destIdx, ushort value) - { - Check (dest, destIdx, 2); - - fixed (byte *target = &dest [destIdx]){ - byte *source = (byte *) &value; - - for (int i = 0; i < 2; i++) - target [i] = source [1-i]; - } - } - } - + static readonly DataConverter SwapConv = new SwapConverter(); + + public static readonly bool IsLittleEndian = BitConverter.IsLittleEndian; + + public abstract double GetDouble(byte[] data, int index); + public abstract float GetFloat(byte[] data, int index); + public abstract long GetInt64(byte[] data, int index); + public abstract int GetInt32(byte[] data, int index); + + public abstract short GetInt16(byte[] data, int index); + + [CLSCompliant(false)] + public abstract uint GetUInt32(byte[] data, int index); + + [CLSCompliant(false)] + public abstract ushort GetUInt16(byte[] data, int index); + + [CLSCompliant(false)] + public abstract ulong GetUInt64(byte[] data, int index); + + public abstract void PutBytes(byte[] dest, int destIdx, double value); + public abstract void PutBytes(byte[] dest, int destIdx, float value); + public abstract void PutBytes(byte[] dest, int destIdx, int value); + public abstract void PutBytes(byte[] dest, int destIdx, long value); + public abstract void PutBytes(byte[] dest, int destIdx, short value); + + [CLSCompliant(false)] + public abstract void PutBytes(byte[] dest, int destIdx, ushort value); + + [CLSCompliant(false)] + public abstract void PutBytes(byte[] dest, int destIdx, uint value); + + [CLSCompliant(false)] + public abstract void PutBytes(byte[] dest, int destIdx, ulong value); + + public byte[] GetBytes(double value) + { + byte[] ret = new byte[8]; + PutBytes(ret, 0, value); + return ret; + } + + public byte[] GetBytes(float value) + { + byte[] ret = new byte[4]; + PutBytes(ret, 0, value); + return ret; + } + + public byte[] GetBytes(int value) + { + byte[] ret = new byte[4]; + PutBytes(ret, 0, value); + return ret; + } + + public byte[] GetBytes(long value) + { + byte[] ret = new byte[8]; + PutBytes(ret, 0, value); + return ret; + } + + public byte[] GetBytes(short value) + { + byte[] ret = new byte[2]; + PutBytes(ret, 0, value); + return ret; + } + + [CLSCompliant(false)] + public byte[] GetBytes(ushort value) + { + byte[] ret = new byte[2]; + PutBytes(ret, 0, value); + return ret; + } + + [CLSCompliant(false)] + public byte[] GetBytes(uint value) + { + byte[] ret = new byte[4]; + PutBytes(ret, 0, value); + return ret; + } + + [CLSCompliant(false)] + public byte[] GetBytes(ulong value) + { + byte[] ret = new byte[8]; + PutBytes(ret, 0, value); + return ret; + } + + static public DataConverter LittleEndian { get { return BitConverter.IsLittleEndian ? Native : SwapConv; } } + + static public DataConverter BigEndian { get { return BitConverter.IsLittleEndian ? SwapConv : Native; } } + + static public DataConverter Native { get; } = new CopyConverter(); + + internal void Check(byte[] dest, int destIdx, int size) + { + if (dest == null) + { + throw new ArgumentNullException("dest"); + } + if (destIdx < 0 || destIdx > dest.Length - size) + { + throw new ArgumentException("destIdx"); + } + } + + class CopyConverter : DataConverter + { + public override double GetDouble(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 8) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + double ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 8; i++) + { + b[i] = data[index + i]; + } + + return ret; + } + + public override ulong GetUInt64(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 8) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + ulong ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 8; i++) + { + b[i] = data[index + i]; + } + + return ret; + } + + public override long GetInt64(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 8) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + long ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 8; i++) + { + b[i] = data[index + i]; + } + + return ret; + } + + public override float GetFloat(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 4) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + float ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 4; i++) + { + b[i] = data[index + i]; + } + + return ret; + } + + public override int GetInt32(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 4) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + int ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 4; i++) + { + b[i] = data[index + i]; + } + + return ret; + } + + public override uint GetUInt32(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 4) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + uint ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 4; i++) + { + b[i] = data[index + i]; + } + + return ret; + } + + public override short GetInt16(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 2) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + short ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 2; i++) + { + b[i] = data[index + i]; + } + + return ret; + } + + public override ushort GetUInt16(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 2) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + ushort ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 2; i++) + { + b[i] = data[index + i]; + } + + return ret; + } + + public override void PutBytes(byte[] dest, int destIdx, double value) + { + Check(dest, destIdx, 8); + fixed (byte* target = &dest[destIdx]) + { + long* source = (long*)&value; + + *((long*)target) = *source; + } + } + + public override void PutBytes(byte[] dest, int destIdx, float value) + { + Check(dest, destIdx, 4); + fixed (byte* target = &dest[destIdx]) + { + uint* source = (uint*)&value; + + *((uint*)target) = *source; + } + } + + public override void PutBytes(byte[] dest, int destIdx, int value) + { + Check(dest, destIdx, 4); + fixed (byte* target = &dest[destIdx]) + { + uint* source = (uint*)&value; + + *((uint*)target) = *source; + } + } + + public override void PutBytes(byte[] dest, int destIdx, uint value) + { + Check(dest, destIdx, 4); + fixed (byte* target = &dest[destIdx]) + { + uint* source = &value; + + *((uint*)target) = *source; + } + } + + public override void PutBytes(byte[] dest, int destIdx, long value) + { + Check(dest, destIdx, 8); + fixed (byte* target = &dest[destIdx]) + { + long* source = &value; + + *((long*)target) = *source; + } + } + + public override void PutBytes(byte[] dest, int destIdx, ulong value) + { + Check(dest, destIdx, 8); + fixed (byte* target = &dest[destIdx]) + { + ulong* source = &value; + + *((ulong*)target) = *source; + } + } + + public override void PutBytes(byte[] dest, int destIdx, short value) + { + Check(dest, destIdx, 2); + fixed (byte* target = &dest[destIdx]) + { + ushort* source = (ushort*)&value; + + *((ushort*)target) = *source; + } + } + + public override void PutBytes(byte[] dest, int destIdx, ushort value) + { + Check(dest, destIdx, 2); + fixed (byte* target = &dest[destIdx]) + { + ushort* source = &value; + + *((ushort*)target) = *source; + } + } + } + + class SwapConverter : DataConverter + { + public override double GetDouble(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 8) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + double ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 8; i++) + { + b[7 - i] = data[index + i]; + } + + return ret; + } + + public override ulong GetUInt64(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 8) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + ulong ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 8; i++) + { + b[7 - i] = data[index + i]; + } + + return ret; + } + + public override long GetInt64(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 8) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + long ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 8; i++) + { + b[7 - i] = data[index + i]; + } + + return ret; + } + + public override float GetFloat(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 4) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + float ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 4; i++) + { + b[3 - i] = data[index + i]; + } + + return ret; + } + + public override int GetInt32(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 4) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + int ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 4; i++) + { + b[3 - i] = data[index + i]; + } + + return ret; + } + + public override uint GetUInt32(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 4) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + uint ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 4; i++) + { + b[3 - i] = data[index + i]; + } + + return ret; + } + + public override short GetInt16(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 2) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + short ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 2; i++) + { + b[1 - i] = data[index + i]; + } + + return ret; + } + + public override ushort GetUInt16(byte[] data, int index) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length - index < 2) + { + throw new ArgumentException("index"); + } + if (index < 0) + { + throw new ArgumentException("index"); + } + + ushort ret; + byte* b = (byte*)&ret; + + for (int i = 0; i < 2; i++) + { + b[1 - i] = data[index + i]; + } + + return ret; + } + + public override void PutBytes(byte[] dest, int destIdx, double value) + { + Check(dest, destIdx, 8); + + fixed (byte* target = &dest[destIdx]) + { + byte* source = (byte*)&value; + + for (int i = 0; i < 8; i++) + { + target[i] = source[7 - i]; + } + } + } + + public override void PutBytes(byte[] dest, int destIdx, float value) + { + Check(dest, destIdx, 4); + + fixed (byte* target = &dest[destIdx]) + { + byte* source = (byte*)&value; + + for (int i = 0; i < 4; i++) + { + target[i] = source[3 - i]; + } + } + } + + public override void PutBytes(byte[] dest, int destIdx, int value) + { + Check(dest, destIdx, 4); + + fixed (byte* target = &dest[destIdx]) + { + byte* source = (byte*)&value; + + for (int i = 0; i < 4; i++) + { + target[i] = source[3 - i]; + } + } + } + + public override void PutBytes(byte[] dest, int destIdx, uint value) + { + Check(dest, destIdx, 4); + + fixed (byte* target = &dest[destIdx]) + { + byte* source = (byte*)&value; + + for (int i = 0; i < 4; i++) + { + target[i] = source[3 - i]; + } + } + } + + public override void PutBytes(byte[] dest, int destIdx, long value) + { + Check(dest, destIdx, 8); + + fixed (byte* target = &dest[destIdx]) + { + byte* source = (byte*)&value; + + for (int i = 0; i < 8; i++) + { + target[i] = source[7 - i]; + } + } + } + + public override void PutBytes(byte[] dest, int destIdx, ulong value) + { + Check(dest, destIdx, 8); + + fixed (byte* target = &dest[destIdx]) + { + byte* source = (byte*)&value; + + for (int i = 0; i < 8; i++) + { + target[i] = source[7 - i]; + } + } + } + + public override void PutBytes(byte[] dest, int destIdx, short value) + { + Check(dest, destIdx, 2); + + fixed (byte* target = &dest[destIdx]) + { + byte* source = (byte*)&value; + + for (int i = 0; i < 2; i++) + { + target[i] = source[1 - i]; + } + } + } + + public override void PutBytes(byte[] dest, int destIdx, ushort value) + { + Check(dest, destIdx, 2); + + fixed (byte* target = &dest[destIdx]) + { + byte* source = (byte*)&value; + + for (int i = 0; i < 2; i++) + { + target[i] = source[1 - i]; + } + } + } + } + #if MONO_DATACONVERTER_STATIC_METHODS static unsafe void PutBytesLE (byte *dest, byte *src, int count) { @@ -1246,6 +1401,5 @@ namespace SharpCompress.Converter { return GetBytesSwap (BitConverter.IsLittleEndian, (byte *) &value, 8); } #endif - - } + } } \ No newline at end of file diff --git a/src/SharpCompress/Crypto/DataLengthException.cs b/src/SharpCompress/Crypto/DataLengthException.cs index 63e9094f..8a3e1c47 100644 --- a/src/SharpCompress/Crypto/DataLengthException.cs +++ b/src/SharpCompress/Crypto/DataLengthException.cs @@ -8,6 +8,7 @@ namespace Org.BouncyCastle.Crypto /** * base constructor. */ + public DataLengthException() { } @@ -17,6 +18,7 @@ namespace Org.BouncyCastle.Crypto * * @param message the message to be carried with the exception. */ + public DataLengthException( string message) : base(message) diff --git a/src/SharpCompress/Crypto/IBlockCipher.cs b/src/SharpCompress/Crypto/IBlockCipher.cs index 7aeb73c6..a4f30012 100644 --- a/src/SharpCompress/Crypto/IBlockCipher.cs +++ b/src/SharpCompress/Crypto/IBlockCipher.cs @@ -1,5 +1,4 @@ - -namespace Org.BouncyCastle.Crypto +namespace Org.BouncyCastle.Crypto { /// Base interface for a symmetric key block cipher. public interface IBlockCipher diff --git a/src/SharpCompress/Crypto/ICipherParameters.cs b/src/SharpCompress/Crypto/ICipherParameters.cs index bbc78dd3..16439a25 100644 --- a/src/SharpCompress/Crypto/ICipherParameters.cs +++ b/src/SharpCompress/Crypto/ICipherParameters.cs @@ -1,5 +1,4 @@ - -namespace Org.BouncyCastle.Crypto +namespace Org.BouncyCastle.Crypto { public interface ICipherParameters { diff --git a/src/SharpCompress/Crypto/KeyParameter.cs b/src/SharpCompress/Crypto/KeyParameter.cs index 9cf4bc8c..41d8e1a7 100644 --- a/src/SharpCompress/Crypto/KeyParameter.cs +++ b/src/SharpCompress/Crypto/KeyParameter.cs @@ -11,7 +11,9 @@ namespace Org.BouncyCastle.Crypto.Parameters byte[] key) { if (key == null) + { throw new ArgumentNullException("key"); + } this.key = (byte[])key.Clone(); } @@ -22,11 +24,17 @@ namespace Org.BouncyCastle.Crypto.Parameters int keyLen) { if (key == null) + { throw new ArgumentNullException("key"); + } if (keyOff < 0 || keyOff > key.Length) + { throw new ArgumentOutOfRangeException("keyOff"); + } if (keyLen < 0 || (keyOff + keyLen) > key.Length) + { throw new ArgumentOutOfRangeException("keyLen"); + } this.key = new byte[keyLen]; Array.Copy(key, keyOff, this.key, 0, keyLen); diff --git a/src/SharpCompress/Crypto/RijndaelEngine.cs b/src/SharpCompress/Crypto/RijndaelEngine.cs index 7e3f14e9..7aca7aea 100644 --- a/src/SharpCompress/Crypto/RijndaelEngine.cs +++ b/src/SharpCompress/Crypto/RijndaelEngine.cs @@ -12,114 +12,114 @@ namespace Org.BouncyCastle.Crypto.Engines private static readonly byte[] Logtable = { - 0, 0, 25, 1, 50, 2, 26, 198, - 75, 199, 27, 104, 51, 238, 223, 3, - 100, 4, 224, 14, 52, 141, 129, 239, - 76, 113, 8, 200, 248, 105, 28, 193, - 125, 194, 29, 181, 249, 185, 39, 106, - 77, 228, 166, 114, 154, 201, 9, 120, - 101, 47, 138, 5, 33, 15, 225, 36, - 18, 240, 130, 69, 53, 147, 218, 142, - 150, 143, 219, 189, 54, 208, 206, 148, - 19, 92, 210, 241, 64, 70, 131, 56, - 102, 221, 253, 48, 191, 6, 139, 98, - 179, 37, 226, 152, 34, 136, 145, 16, - 126, 110, 72, 195, 163, 182, 30, 66, - 58, 107, 40, 84, 250, 133, 61, 186, - 43, 121, 10, 21, 155, 159, 94, 202, - 78, 212, 172, 229, 243, 115, 167, 87, - 175, 88, 168, 80, 244, 234, 214, 116, - 79, 174, 233, 213, 231, 230, 173, 232, - 44, 215, 117, 122, 235, 22, 11, 245, - 89, 203, 95, 176, 156, 169, 81, 160, - 127, 12, 246, 111, 23, 196, 73, 236, - 216, 67, 31, 45, 164, 118, 123, 183, - 204, 187, 62, 90, 251, 96, 177, 134, - 59, 82, 161, 108, 170, 85, 41, 157, - 151, 178, 135, 144, 97, 190, 220, 252, - 188, 149, 207, 205, 55, 63, 91, 209, - 83, 57, 132, 60, 65, 162, 109, 71, - 20, 42, 158, 93, 86, 242, 211, 171, - 68, 17, 146, 217, 35, 32, 46, 137, - 180, 124, 184, 38, 119, 153, 227, 165, - 103, 74, 237, 222, 197, 49, 254, 24, - 13, 99, 140, 128, 192, 247, 112, 7 + 0, 0, 25, 1, 50, 2, 26, 198, + 75, 199, 27, 104, 51, 238, 223, 3, + 100, 4, 224, 14, 52, 141, 129, 239, + 76, 113, 8, 200, 248, 105, 28, 193, + 125, 194, 29, 181, 249, 185, 39, 106, + 77, 228, 166, 114, 154, 201, 9, 120, + 101, 47, 138, 5, 33, 15, 225, 36, + 18, 240, 130, 69, 53, 147, 218, 142, + 150, 143, 219, 189, 54, 208, 206, 148, + 19, 92, 210, 241, 64, 70, 131, 56, + 102, 221, 253, 48, 191, 6, 139, 98, + 179, 37, 226, 152, 34, 136, 145, 16, + 126, 110, 72, 195, 163, 182, 30, 66, + 58, 107, 40, 84, 250, 133, 61, 186, + 43, 121, 10, 21, 155, 159, 94, 202, + 78, 212, 172, 229, 243, 115, 167, 87, + 175, 88, 168, 80, 244, 234, 214, 116, + 79, 174, 233, 213, 231, 230, 173, 232, + 44, 215, 117, 122, 235, 22, 11, 245, + 89, 203, 95, 176, 156, 169, 81, 160, + 127, 12, 246, 111, 23, 196, 73, 236, + 216, 67, 31, 45, 164, 118, 123, 183, + 204, 187, 62, 90, 251, 96, 177, 134, + 59, 82, 161, 108, 170, 85, 41, 157, + 151, 178, 135, 144, 97, 190, 220, 252, + 188, 149, 207, 205, 55, 63, 91, 209, + 83, 57, 132, 60, 65, 162, 109, 71, + 20, 42, 158, 93, 86, 242, 211, 171, + 68, 17, 146, 217, 35, 32, 46, 137, + 180, 124, 184, 38, 119, 153, 227, 165, + 103, 74, 237, 222, 197, 49, 254, 24, + 13, 99, 140, 128, 192, 247, 112, 7 }; private static readonly byte[] Alogtable = { - 0, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, - 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, - 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, - 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, - 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, - 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, - 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, - 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, - 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, - 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, - 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, - 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, - 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, - 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, - 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, - 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, - 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, - 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, - 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, - 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, - 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, - 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, - 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, - 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, - 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, - 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, - 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, - 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, - 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, - 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, - 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, - 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, + 0, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, + 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, + 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, + 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, + 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, + 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, + 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, + 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, + 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, + 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, + 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, + 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, + 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, + 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, + 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, + 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, + 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, + 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, + 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, + 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, + 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, + 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, + 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, + 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, + 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, + 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, + 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, + 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, + 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, + 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, + 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, + 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1 }; private static readonly byte[] S = { - 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, - 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, - 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, - 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, - 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, - 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, - 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, - 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, - 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, - 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, - 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, - 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, - 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, - 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, - 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, - 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22, + 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, + 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, + 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, + 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, + 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, + 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, + 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, + 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, + 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, + 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, + 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, + 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, + 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, + 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, + 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, + 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22 }; private static readonly byte[] Si = { - 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, - 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, - 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, - 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, - 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, - 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, - 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, - 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, - 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, - 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, - 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, - 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, - 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, - 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, - 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, - 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125, + 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, + 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, + 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, + 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, + 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, + 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, + 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, + 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, + 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, + 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, + 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, + 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, + 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, + 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, + 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, + 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125 }; private static readonly byte[] rcon = @@ -128,28 +128,29 @@ namespace Org.BouncyCastle.Crypto.Engines 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; - static readonly byte[][] shifts0 = new byte[][] - { - new byte[]{ 0, 8, 16, 24 }, - new byte[]{ 0, 8, 16, 24 }, - new byte[]{ 0, 8, 16, 24 }, - new byte[]{ 0, 8, 16, 32 }, - new byte[]{ 0, 8, 24, 32 } - }; + static readonly byte[][] shifts0 = + { + new byte[] {0, 8, 16, 24}, + new byte[] {0, 8, 16, 24}, + new byte[] {0, 8, 16, 24}, + new byte[] {0, 8, 16, 32}, + new byte[] {0, 8, 24, 32} + }; static readonly byte[][] shifts1 = { - new byte[]{ 0, 24, 16, 8 }, - new byte[]{ 0, 32, 24, 16 }, - new byte[]{ 0, 40, 32, 24 }, - new byte[]{ 0, 48, 40, 24 }, - new byte[]{ 0, 56, 40, 32 } + new byte[] {0, 24, 16, 8}, + new byte[] {0, 32, 24, 16}, + new byte[] {0, 40, 32, 24}, + new byte[] {0, 48, 40, 24}, + new byte[] {0, 56, 40, 32} }; /** * multiply two elements of GF(2^m) * needed for MixColumn and InvMixColumn */ + private byte Mul0x2( int b) { @@ -157,10 +158,7 @@ namespace Org.BouncyCastle.Crypto.Engines { return Alogtable[25 + (Logtable[b] & 0xff)]; } - else - { - return 0; - } + return 0; } private byte Mul0x3( @@ -170,10 +168,7 @@ namespace Org.BouncyCastle.Crypto.Engines { return Alogtable[1 + (Logtable[b] & 0xff)]; } - else - { - return 0; - } + return 0; } private byte Mul0x9( @@ -183,10 +178,7 @@ namespace Org.BouncyCastle.Crypto.Engines { return Alogtable[199 + b]; } - else - { - return 0; - } + return 0; } private byte Mul0xb( @@ -196,10 +188,7 @@ namespace Org.BouncyCastle.Crypto.Engines { return Alogtable[104 + b]; } - else - { - return 0; - } + return 0; } private byte Mul0xd( @@ -209,10 +198,7 @@ namespace Org.BouncyCastle.Crypto.Engines { return Alogtable[238 + b]; } - else - { - return 0; - } + return 0; } private byte Mul0xe( @@ -222,15 +208,13 @@ namespace Org.BouncyCastle.Crypto.Engines { return Alogtable[223 + b]; } - else - { - return 0; - } + return 0; } /** * xor corresponding text input and round key input bytes */ + private void KeyAddition( long[] rk) { @@ -261,6 +245,7 @@ namespace Org.BouncyCastle.Crypto.Engines * Row 0 remains unchanged * The other three rows are shifted a variable amount */ + private void ShiftRow( byte[] shiftsSC) { @@ -287,6 +272,7 @@ namespace Org.BouncyCastle.Crypto.Engines * Replace every byte of the input by the byte at that place * in the nonlinear S-box */ + private void Substitution( byte[] box) { @@ -299,6 +285,7 @@ namespace Org.BouncyCastle.Crypto.Engines /** * Mix the bytes of every column in a linear way */ + private void MixColumn() { long r0, r1, r2, r3; @@ -331,6 +318,7 @@ namespace Org.BouncyCastle.Crypto.Engines * Mix the bytes of every column in a linear way * This is the opposite operation of Mixcolumn */ + private void InvMixColumn() { long r0, r1, r2, r3; @@ -370,6 +358,7 @@ namespace Org.BouncyCastle.Crypto.Engines * Calculate the necessary round keys * The number of calculations depends on keyBits and blockBits */ + private long[][] GenerateWorkingKey( byte[] key) { @@ -377,11 +366,14 @@ namespace Org.BouncyCastle.Crypto.Engines int t, rconpointer = 0; int keyBits = key.Length * 8; byte[,] tk = new byte[4, MAXKC]; + //long[,] W = new long[MAXROUNDS+1,4]; long[][] W = new long[MAXROUNDS + 1][]; for (int i = 0; i < MAXROUNDS + 1; i++) + { W[i] = new long[4]; + } switch (keyBits) { @@ -446,7 +438,7 @@ namespace Org.BouncyCastle.Crypto.Engines { tk[i, 0] ^= S[tk[(i + 1) % 4, KC - 1] & 0xff]; } - tk[0, 0] ^= (byte)rcon[rconpointer++]; + tk[0, 0] ^= rcon[rconpointer++]; if (KC <= 6) { @@ -494,26 +486,31 @@ namespace Org.BouncyCastle.Crypto.Engines return W; } - private int BC; - private long BC_MASK; + private readonly int BC; + private readonly long BC_MASK; private int ROUNDS; - private int blockBits; + private readonly int blockBits; private long[][] workingKey; private long A0, A1, A2, A3; private bool forEncryption; - private byte[] shifts0SC; - private byte[] shifts1SC; + private readonly byte[] shifts0SC; + private readonly byte[] shifts1SC; /** * default constructor - 128 bit block size. */ - public RijndaelEngine() : this(128) { } + + public RijndaelEngine() + : this(128) + { + } /** * basic constructor - set the cipher up for a given blocksize * * @param blocksize the blocksize in bits, must be 128, 192, or 256. */ + public RijndaelEngine( int blockBits) { @@ -564,6 +561,7 @@ namespace Org.BouncyCastle.Crypto.Engines * @exception ArgumentException if the parameters argument is * inappropriate. */ + public void Init( bool forEncryption, ICipherParameters parameters) @@ -576,18 +574,12 @@ namespace Org.BouncyCastle.Crypto.Engines return; } - throw new ArgumentException("invalid parameter passed to Rijndael init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to Rijndael init - " + parameters.GetType()); } - public string AlgorithmName - { - get { return "Rijndael"; } - } + public string AlgorithmName { get { return "Rijndael"; } } - public bool IsPartialBlockOkay - { - get { return false; } - } + public bool IsPartialBlockOkay { get { return false; } } public int GetBlockSize() { @@ -641,10 +633,10 @@ namespace Org.BouncyCastle.Crypto.Engines { int index = off; - A0 = (long)(bytes[index++] & 0xff); - A1 = (long)(bytes[index++] & 0xff); - A2 = (long)(bytes[index++] & 0xff); - A3 = (long)(bytes[index++] & 0xff); + A0 = bytes[index++] & 0xff; + A1 = bytes[index++] & 0xff; + A2 = bytes[index++] & 0xff; + A3 = bytes[index++] & 0xff; for (int j = 8; j != BC; j += 8) { diff --git a/src/SharpCompress/EnumExtensions.cs b/src/SharpCompress/EnumExtensions.cs index e7fb0229..5f5fe0d6 100644 --- a/src/SharpCompress/EnumExtensions.cs +++ b/src/SharpCompress/EnumExtensions.cs @@ -1,4 +1,5 @@ -#if NET35 + +#if NET35 using System; namespace SharpCompress diff --git a/src/SharpCompress/IO/AppendingStream.cs b/src/SharpCompress/IO/AppendingStream.cs index ca47ca83..3c55bfb4 100644 --- a/src/SharpCompress/IO/AppendingStream.cs +++ b/src/SharpCompress/IO/AppendingStream.cs @@ -14,42 +14,20 @@ namespace SharpCompress.IO this.streams = new Queue(streams); } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { throw new NotImplementedException(); } - public override long Length - { - get { throw new NotImplementedException(); } - } + public override long Length { get { throw new NotImplementedException(); } } - public override long Position - { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } - } + public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -71,10 +49,7 @@ namespace SharpCompress.IO { return totalRead; } - else - { - current = streams.Dequeue(); - } + current = streams.Dequeue(); } totalRead += read; } @@ -96,4 +71,4 @@ namespace SharpCompress.IO throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/src/SharpCompress/IO/BufferedSubStream.cs b/src/SharpCompress/IO/BufferedSubStream.cs index 7c61e641..f98c1c0b 100644 --- a/src/SharpCompress/IO/BufferedSubStream.cs +++ b/src/SharpCompress/IO/BufferedSubStream.cs @@ -1,4 +1,5 @@ -using System.IO; +using System; +using System.IO; namespace SharpCompress.IO { @@ -7,7 +8,7 @@ namespace SharpCompress.IO private long position; private int cacheOffset; private int cacheLength; - private byte[] cache; + private readonly byte[] cache; public BufferedSubStream(Stream stream, long origin, long bytesToRead) { @@ -27,43 +28,29 @@ namespace SharpCompress.IO private long BytesLeftToRead { get; set; } - public Stream Stream { get; private set; } + public Stream Stream { get; } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } - public override long Length - { - get { throw new System.NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new System.NotSupportedException(); } - set { throw new System.NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { if (count > BytesLeftToRead) + { count = (int)BytesLeftToRead; + } if (count > 0) { @@ -76,9 +63,11 @@ namespace SharpCompress.IO } if (count > cacheLength) + { count = cacheLength; + } - System.Buffer.BlockCopy(cache, cacheOffset, buffer, offset, count); + Buffer.BlockCopy(cache, cacheOffset, buffer, offset, count); cacheOffset += count; cacheLength -= count; BytesLeftToRead -= count; @@ -89,17 +78,17 @@ namespace SharpCompress.IO public override long Seek(long offset, SeekOrigin origin) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } public override void SetLength(long value) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } } } \ No newline at end of file diff --git a/src/SharpCompress/IO/CountingWritableSubStream.cs b/src/SharpCompress/IO/CountingWritableSubStream.cs index 3b9d2c7a..17313612 100644 --- a/src/SharpCompress/IO/CountingWritableSubStream.cs +++ b/src/SharpCompress/IO/CountingWritableSubStream.cs @@ -5,7 +5,7 @@ namespace SharpCompress.IO { internal class CountingWritableSubStream : Stream { - private Stream writableStream; + private readonly Stream writableStream; internal CountingWritableSubStream(Stream stream) { @@ -14,35 +14,19 @@ namespace SharpCompress.IO public uint Count { get; private set; } - public override bool CanRead - { - get { return false; } - } + public override bool CanRead { get { return false; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return true; } - } + public override bool CanWrite { get { return true; } } public override void Flush() { } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -62,7 +46,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/src/SharpCompress/IO/ListeningStream.cs b/src/SharpCompress/IO/ListeningStream.cs index 49a4a5d0..bbec0a96 100644 --- a/src/SharpCompress/IO/ListeningStream.cs +++ b/src/SharpCompress/IO/ListeningStream.cs @@ -6,7 +6,7 @@ namespace SharpCompress.IO internal class ListeningStream : Stream { private long currentEntryTotalReadBytes; - private IExtractionListener listener; + private readonly IExtractionListener listener; public ListeningStream(IExtractionListener listener, Stream stream) { @@ -22,38 +22,22 @@ namespace SharpCompress.IO } } - public Stream Stream { get; private set; } + public Stream Stream { get; } - public override bool CanRead - { - get { return Stream.CanRead; } - } + public override bool CanRead { get { return Stream.CanRead; } } - public override bool CanSeek - { - get { return Stream.CanSeek; } - } + public override bool CanSeek { get { return Stream.CanSeek; } } - public override bool CanWrite - { - get { return Stream.CanWrite; } - } + public override bool CanWrite { get { return Stream.CanWrite; } } public override void Flush() { Stream.Flush(); } - public override long Length - { - get { return Stream.Length; } - } + public override long Length { get { return Stream.Length; } } - public override long Position - { - get { return Stream.Position; } - set { Stream.Position = value; } - } + public override long Position { get { return Stream.Position; } set { Stream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { diff --git a/src/SharpCompress/IO/MarkingBinaryReader.cs b/src/SharpCompress/IO/MarkingBinaryReader.cs index a3662144..8f4a3196 100644 --- a/src/SharpCompress/IO/MarkingBinaryReader.cs +++ b/src/SharpCompress/IO/MarkingBinaryReader.cs @@ -7,7 +7,6 @@ namespace SharpCompress.IO { internal class MarkingBinaryReader : BinaryReader { - public MarkingBinaryReader(Stream stream) : base(stream) { diff --git a/src/SharpCompress/IO/NonDisposingStream.cs b/src/SharpCompress/IO/NonDisposingStream.cs index d19ea095..ebd77787 100644 --- a/src/SharpCompress/IO/NonDisposingStream.cs +++ b/src/SharpCompress/IO/NonDisposingStream.cs @@ -14,38 +14,22 @@ namespace SharpCompress.IO //don't dispose anything } - public Stream Stream { get; private set; } + public Stream Stream { get; } - public override bool CanRead - { - get { return Stream.CanRead; } - } + public override bool CanRead { get { return Stream.CanRead; } } - public override bool CanSeek - { - get { return Stream.CanSeek; } - } + public override bool CanSeek { get { return Stream.CanSeek; } } - public override bool CanWrite - { - get { return Stream.CanWrite; } - } + public override bool CanWrite { get { return Stream.CanWrite; } } public override void Flush() { Stream.Flush(); } - public override long Length - { - get { return Stream.Length; } - } + public override long Length { get { return Stream.Length; } } - public override long Position - { - get { return Stream.Position; } - set { Stream.Position = value; } - } + public override long Position { get { return Stream.Position; } set { Stream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { diff --git a/src/SharpCompress/IO/ReadOnlySubStream.cs b/src/SharpCompress/IO/ReadOnlySubStream.cs index 8126d61d..c9c1df3c 100644 --- a/src/SharpCompress/IO/ReadOnlySubStream.cs +++ b/src/SharpCompress/IO/ReadOnlySubStream.cs @@ -1,4 +1,5 @@ -using System.IO; +using System; +using System.IO; namespace SharpCompress.IO { @@ -29,38 +30,22 @@ namespace SharpCompress.IO private long BytesLeftToRead { get; set; } - public Stream Stream { get; private set; } + public Stream Stream { get; } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } - public override long Length - { - get { throw new System.NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new System.NotSupportedException(); } - set { throw new System.NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { @@ -78,17 +63,17 @@ namespace SharpCompress.IO public override long Seek(long offset, SeekOrigin origin) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } public override void SetLength(long value) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } } } \ No newline at end of file diff --git a/src/SharpCompress/IO/RewindableStream.cs b/src/SharpCompress/IO/RewindableStream.cs index 14e18bd5..f1f58436 100644 --- a/src/SharpCompress/IO/RewindableStream.cs +++ b/src/SharpCompress/IO/RewindableStream.cs @@ -1,4 +1,5 @@ -using System.IO; +using System; +using System.IO; namespace SharpCompress.IO { @@ -67,27 +68,18 @@ namespace SharpCompress.IO IsRecording = true; } - public override bool CanRead - { - get { return true; } - } + public override bool CanRead { get { return true; } } public override bool CanSeek => stream.CanSeek; - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite { get { return false; } } public override void Flush() { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } - public override long Length - { - get { throw new System.NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } public override long Position { @@ -144,17 +136,17 @@ namespace SharpCompress.IO public override long Seek(long offset, SeekOrigin origin) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } public override void SetLength(long value) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } } } \ No newline at end of file diff --git a/src/SharpCompress/IO/StreamingMode.cs b/src/SharpCompress/IO/StreamingMode.cs index 2497e2d8..29d3a147 100644 --- a/src/SharpCompress/IO/StreamingMode.cs +++ b/src/SharpCompress/IO/StreamingMode.cs @@ -3,6 +3,6 @@ internal enum StreamingMode { Streaming, - Seekable, + Seekable } } \ No newline at end of file diff --git a/src/SharpCompress/LazyReadOnlyCollection.cs b/src/SharpCompress/LazyReadOnlyCollection.cs index 7dfbcc9c..d3e3fff4 100644 --- a/src/SharpCompress/LazyReadOnlyCollection.cs +++ b/src/SharpCompress/LazyReadOnlyCollection.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; namespace SharpCompress @@ -27,10 +28,7 @@ namespace SharpCompress #region IEnumerator Members - public T Current - { - get { return lazyReadOnlyCollection.backing[index]; } - } + public T Current { get { return lazyReadOnlyCollection.backing[index]; } } #endregion @@ -48,10 +46,7 @@ namespace SharpCompress #region IEnumerator Members - object System.Collections.IEnumerator.Current - { - get { return Current; } - } + object IEnumerator.Current { get { return Current; } } public bool MoveNext() { @@ -125,10 +120,7 @@ namespace SharpCompress } } - public bool IsReadOnly - { - get { return true; } - } + public bool IsReadOnly { get { return true; } } public bool Remove(T item) { @@ -149,7 +141,7 @@ namespace SharpCompress #region IEnumerable Members - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } diff --git a/src/SharpCompress/ReadOnlyCollection.cs b/src/SharpCompress/ReadOnlyCollection.cs index 37bd9a4c..7b6f54e9 100644 --- a/src/SharpCompress/ReadOnlyCollection.cs +++ b/src/SharpCompress/ReadOnlyCollection.cs @@ -1,11 +1,12 @@ using System; +using System.Collections; using System.Collections.Generic; namespace SharpCompress { internal class ReadOnlyCollection : ICollection { - private ICollection collection; + private readonly ICollection collection; public ReadOnlyCollection(ICollection collection) { @@ -32,15 +33,9 @@ namespace SharpCompress collection.CopyTo(array, arrayIndex); } - public int Count - { - get { return collection.Count; } - } + public int Count { get { return collection.Count; } } - public bool IsReadOnly - { - get { return true; } - } + public bool IsReadOnly { get { return true; } } public bool Remove(T item) { @@ -52,7 +47,7 @@ namespace SharpCompress return collection.GetEnumerator(); } - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() { throw new NotSupportedException(); } diff --git a/src/SharpCompress/Reader/AbstractReader.cs b/src/SharpCompress/Reader/AbstractReader.cs index ca7ba6ce..adb83037 100644 --- a/src/SharpCompress/Reader/AbstractReader.cs +++ b/src/SharpCompress/Reader/AbstractReader.cs @@ -2,10 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using SharpCompress.Archive; -using SharpCompress.Archive.Rar; using SharpCompress.Common; -using SharpCompress.Reader.Rar; namespace SharpCompress.Reader { @@ -26,8 +23,6 @@ namespace SharpCompress.Reader public event EventHandler CompressedBytesRead; public event EventHandler FilePartExtractionBegin; - - internal AbstractReader(Options options, ArchiveType archiveType) { ArchiveType = archiveType; @@ -36,7 +31,7 @@ namespace SharpCompress.Reader internal Options Options { get; private set; } - public ArchiveType ArchiveType { get; private set; } + public ArchiveType ArchiveType { get; } /// /// Current volume that the current entry resides in @@ -46,10 +41,7 @@ namespace SharpCompress.Reader /// /// Current file entry /// - public TEntry Entry - { - get { return entriesForCurrentReadStream.Current; } - } + public TEntry Entry { get { return entriesForCurrentReadStream.Current; } } #region IDisposable Members @@ -64,7 +56,6 @@ namespace SharpCompress.Reader #endregion - public bool Cancelled { get; private set; } /// @@ -74,10 +65,10 @@ namespace SharpCompress.Reader /// public void Cancel() { - if (!completed) - { - Cancelled = true; - } + if (!completed) + { + Cancelled = true; + } } public bool MoveToNextEntry() @@ -185,13 +176,13 @@ namespace SharpCompress.Reader if ((writableStream == null) || (!writableStream.CanWrite)) { throw new ArgumentNullException( - "A writable Stream was required. Use Cancel if that was intended."); + "A writable Stream was required. Use Cancel if that was intended."); } var streamListener = this as IReaderExtractionListener; - streamListener.FireEntryExtractionBegin(this.Entry); + streamListener.FireEntryExtractionBegin(Entry); Write(writableStream); - streamListener.FireEntryExtractionEnd(this.Entry); + streamListener.FireEntryExtractionEnd(Entry); wroteCurrentEntry = true; } @@ -219,30 +210,27 @@ namespace SharpCompress.Reader /// protected EntryStream CreateEntryStream(Stream decompressed) { - return new EntryStream(this, decompressed); + return new EntryStream(this, decompressed); } protected virtual EntryStream GetEntryStream() { - return CreateEntryStream(Entry.Parts.First().GetCompressedStream()); + return CreateEntryStream(Entry.Parts.First().GetCompressedStream()); } #endregion - IEntry IReader.Entry - { - get { return Entry; } - } + IEntry IReader.Entry { get { return Entry; } } void IExtractionListener.FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes) { if (CompressedBytesRead != null) { - CompressedBytesRead(this, new CompressedBytesReadEventArgs() - { - CurrentFilePartCompressedBytesRead = currentPartCompressedBytes, - CompressedBytesRead = compressedReadBytes - }); + CompressedBytesRead(this, new CompressedBytesReadEventArgs + { + CurrentFilePartCompressedBytesRead = currentPartCompressedBytes, + CompressedBytesRead = compressedReadBytes + }); } } @@ -250,18 +238,18 @@ namespace SharpCompress.Reader { if (FilePartExtractionBegin != null) { - FilePartExtractionBegin(this, new FilePartExtractionBeginEventArgs() - { - CompressedSize = compressedSize, - Size = size, - Name = name, - }); + FilePartExtractionBegin(this, new FilePartExtractionBeginEventArgs + { + CompressedSize = compressedSize, + Size = size, + Name = name + }); } } void IReaderExtractionListener.FireEntryExtractionBegin(Entry entry) { - if (EntryExtractionBegin!=null) + if (EntryExtractionBegin != null) { EntryExtractionBegin(this, new ReaderExtractionEventArgs(entry)); } @@ -269,7 +257,7 @@ namespace SharpCompress.Reader void IReaderExtractionListener.FireEntryExtractionEnd(Entry entry) { - if (EntryExtractionEnd!=null) + if (EntryExtractionEnd != null) { EntryExtractionEnd(this, new ReaderExtractionEventArgs(entry)); } diff --git a/src/SharpCompress/Reader/GZip/GZipReader.cs b/src/SharpCompress/Reader/GZip/GZipReader.cs index 6dee2da3..43ecf4ed 100644 --- a/src/SharpCompress/Reader/GZip/GZipReader.cs +++ b/src/SharpCompress/Reader/GZip/GZipReader.cs @@ -7,18 +7,13 @@ namespace SharpCompress.Reader.GZip { public class GZipReader : AbstractReader { - private readonly GZipVolume volume; - internal GZipReader(Stream stream, Options options) : base(options, ArchiveType.GZip) { - volume = new GZipVolume(stream, options); + Volume = new GZipVolume(stream, options); } - public override GZipVolume Volume - { - get { return volume; } - } + public override GZipVolume Volume { get; } #region Open diff --git a/src/SharpCompress/Reader/IReader.Extensions.cs b/src/SharpCompress/Reader/IReader.Extensions.cs index c01d0f1f..ce85b5a0 100644 --- a/src/SharpCompress/Reader/IReader.Extensions.cs +++ b/src/SharpCompress/Reader/IReader.Extensions.cs @@ -1,7 +1,4 @@ -using System.IO; -using SharpCompress.Common; - -namespace SharpCompress.Reader +namespace SharpCompress.Reader { public static class IReaderExtensions { diff --git a/src/SharpCompress/Reader/IReaderExtractionListener.cs b/src/SharpCompress/Reader/IReaderExtractionListener.cs index c4c9b2bb..85d34913 100644 --- a/src/SharpCompress/Reader/IReaderExtractionListener.cs +++ b/src/SharpCompress/Reader/IReaderExtractionListener.cs @@ -1,16 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SharpCompress.Archive; -using SharpCompress.Common; +using SharpCompress.Common; namespace SharpCompress.Reader { - internal interface IReaderExtractionListener:IExtractionListener + internal interface IReaderExtractionListener : IExtractionListener { -// void EnsureEntriesLoaded(); + // void EnsureEntriesLoaded(); void FireEntryExtractionBegin(Entry entry); void FireEntryExtractionEnd(Entry entry); } -} +} \ No newline at end of file diff --git a/src/SharpCompress/Reader/Rar/MultiVolumeRarReader.cs b/src/SharpCompress/Reader/Rar/MultiVolumeRarReader.cs index b84fd4dc..5f94830a 100644 --- a/src/SharpCompress/Reader/Rar/MultiVolumeRarReader.cs +++ b/src/SharpCompress/Reader/Rar/MultiVolumeRarReader.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System.Collections; +using System.Collections.Generic; using System.IO; using System.Linq; using SharpCompress.Common; @@ -71,7 +72,7 @@ namespace SharpCompress.Reader.Rar return this; } - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() { return this; } @@ -82,10 +83,7 @@ namespace SharpCompress.Reader.Rar { } - object System.Collections.IEnumerator.Current - { - get { return Current; } - } + object IEnumerator.Current { get { return Current; } } public bool MoveNext() { diff --git a/src/SharpCompress/Reader/Rar/NonSeekableStreamFilePart.cs b/src/SharpCompress/Reader/Rar/NonSeekableStreamFilePart.cs index 1cacba4b..bb283bd1 100644 --- a/src/SharpCompress/Reader/Rar/NonSeekableStreamFilePart.cs +++ b/src/SharpCompress/Reader/Rar/NonSeekableStreamFilePart.cs @@ -16,9 +16,6 @@ namespace SharpCompress.Reader.Rar return FileHeader.PackedStream; } - internal override string FilePartName - { - get { return "Unknown Stream - File Entry: " + FileHeader.FileName; } - } + internal override string FilePartName { get { return "Unknown Stream - File Entry: " + FileHeader.FileName; } } } } \ No newline at end of file diff --git a/src/SharpCompress/Reader/Rar/RarReader.cs b/src/SharpCompress/Reader/Rar/RarReader.cs index bf048beb..83d9ce63 100644 --- a/src/SharpCompress/Reader/Rar/RarReader.cs +++ b/src/SharpCompress/Reader/Rar/RarReader.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; using SharpCompress.Common; @@ -24,10 +23,7 @@ namespace SharpCompress.Reader.Rar internal abstract void ValidateArchive(RarVolume archive); - public override RarVolume Volume - { - get { return volume; } - } + public override RarVolume Volume { get { return volume; } } #region Open @@ -74,8 +70,8 @@ namespace SharpCompress.Reader.Rar protected override EntryStream GetEntryStream() { return CreateEntryStream(new RarStream(pack, Entry.FileHeader, - new MultiVolumeReadOnlyStream( - CreateFilePartEnumerableForCurrentEntry().Cast(), this))); + new MultiVolumeReadOnlyStream( + CreateFilePartEnumerableForCurrentEntry().Cast(), this))); } public static RarReader Open(Stream stream, string password, Options options = Options.KeepStreamsOpen) diff --git a/src/SharpCompress/Reader/Rar/RarReaderEntry.cs b/src/SharpCompress/Reader/Rar/RarReaderEntry.cs index 4300d15a..f8b5d3a4 100644 --- a/src/SharpCompress/Reader/Rar/RarReaderEntry.cs +++ b/src/SharpCompress/Reader/Rar/RarReaderEntry.cs @@ -13,37 +13,22 @@ namespace SharpCompress.Reader.Rar IsSolid = solid; } - internal RarFilePart Part { get; private set; } + internal RarFilePart Part { get; } - internal override IEnumerable Parts - { - get { return Part.AsEnumerable(); } - } + internal override IEnumerable Parts { get { return Part.AsEnumerable(); } } - internal override FileHeader FileHeader - { - get { return Part.FileHeader; } - } + internal override FileHeader FileHeader { get { return Part.FileHeader; } } - public override CompressionType CompressionType - { - get { return CompressionType.Rar; } - } + public override CompressionType CompressionType { get { return CompressionType.Rar; } } /// /// The compressed file size /// - public override long CompressedSize - { - get { return Part.FileHeader.CompressedSize; } - } + public override long CompressedSize { get { return Part.FileHeader.CompressedSize; } } /// /// The uncompressed file size /// - public override long Size - { - get { return Part.FileHeader.UncompressedSize; } - } + public override long Size { get { return Part.FileHeader.UncompressedSize; } } } } \ No newline at end of file diff --git a/src/SharpCompress/Reader/Rar/SingleVolumeRarReader.cs b/src/SharpCompress/Reader/Rar/SingleVolumeRarReader.cs index 7375a254..3945cc1a 100644 --- a/src/SharpCompress/Reader/Rar/SingleVolumeRarReader.cs +++ b/src/SharpCompress/Reader/Rar/SingleVolumeRarReader.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using System.IO; +using System.IO; using SharpCompress.Common; using SharpCompress.Common.Rar; @@ -7,7 +6,6 @@ namespace SharpCompress.Reader.Rar { internal class SingleVolumeRarReader : RarReader { - private readonly Stream stream; internal SingleVolumeRarReader(Stream stream, string password, Options options) @@ -22,7 +20,7 @@ namespace SharpCompress.Reader.Rar if (archive.IsMultiVolume) { throw new MultiVolumeExtractionException( - "Streamed archive is a Multi-volume archive. Use different RarReader method to extract."); + "Streamed archive is a Multi-volume archive. Use different RarReader method to extract."); } } diff --git a/src/SharpCompress/Reader/ReaderFactory.cs b/src/SharpCompress/Reader/ReaderFactory.cs index bc24ee2e..c33780ec 100644 --- a/src/SharpCompress/Reader/ReaderFactory.cs +++ b/src/SharpCompress/Reader/ReaderFactory.cs @@ -7,12 +7,12 @@ using SharpCompress.Archive.Zip; using SharpCompress.Common; using SharpCompress.Compressor; using SharpCompress.Compressor.BZip2; +using SharpCompress.Compressor.Deflate; using SharpCompress.IO; using SharpCompress.Reader.GZip; using SharpCompress.Reader.Rar; using SharpCompress.Reader.Tar; using SharpCompress.Reader.Zip; -using GZipStream = SharpCompress.Compressor.Deflate.GZipStream; namespace SharpCompress.Reader { diff --git a/src/SharpCompress/Reader/Tar/TarReader.cs b/src/SharpCompress/Reader/Tar/TarReader.cs index 36c1b0cf..089979c1 100644 --- a/src/SharpCompress/Reader/Tar/TarReader.cs +++ b/src/SharpCompress/Reader/Tar/TarReader.cs @@ -14,7 +14,6 @@ namespace SharpCompress.Reader.Tar { public class TarReader : AbstractReader { - private readonly TarVolume volume; private readonly CompressionType compressionType; internal TarReader(Stream stream, CompressionType compressionType, @@ -22,13 +21,10 @@ namespace SharpCompress.Reader.Tar : base(options, ArchiveType.Tar) { this.compressionType = compressionType; - volume = new TarVolume(stream, options); + Volume = new TarVolume(stream, options); } - public override TarVolume Volume - { - get { return volume; } - } + public override TarVolume Volume { get; } internal override Stream RequestInitialStream() { @@ -36,21 +32,21 @@ namespace SharpCompress.Reader.Tar switch (compressionType) { case CompressionType.BZip2: - { - return new BZip2Stream(stream, CompressionMode.Decompress, false); - } + { + return new BZip2Stream(stream, CompressionMode.Decompress, false); + } case CompressionType.GZip: - { - return new GZipStream(stream, CompressionMode.Decompress); - } + { + return new GZipStream(stream, CompressionMode.Decompress); + } case CompressionType.None: - { - return stream; - } + { + return stream; + } default: - { - throw new NotSupportedException("Invalid compression type: " + compressionType); - } + { + throw new NotSupportedException("Invalid compression type: " + compressionType); + } } } diff --git a/src/SharpCompress/Reader/Zip/ZipReader.cs b/src/SharpCompress/Reader/Zip/ZipReader.cs index bb2c9956..d1c33293 100644 --- a/src/SharpCompress/Reader/Zip/ZipReader.cs +++ b/src/SharpCompress/Reader/Zip/ZipReader.cs @@ -9,19 +9,15 @@ namespace SharpCompress.Reader.Zip public class ZipReader : AbstractReader { private readonly StreamingZipHeaderFactory headerFactory; - private readonly ZipVolume volume; internal ZipReader(Stream stream, Options options, string password) : base(options, ArchiveType.Zip) { - volume = new ZipVolume(stream, options); + Volume = new ZipVolume(stream, options); headerFactory = new StreamingZipHeaderFactory(password); } - public override ZipVolume Volume - { - get { return volume; } - } + public override ZipVolume Volume { get; } #region Open @@ -50,15 +46,15 @@ namespace SharpCompress.Reader.Zip switch (h.ZipHeaderType) { case ZipHeaderType.LocalEntry: - { - yield return new ZipEntry(new StreamingZipFilePart(h as LocalEntryHeader, - stream)); - } + { + yield return new ZipEntry(new StreamingZipFilePart(h as LocalEntryHeader, + stream)); + } break; case ZipHeaderType.DirectoryEnd: - { - yield break; - } + { + yield break; + } } } } diff --git a/src/SharpCompress/Utility.cs b/src/SharpCompress/Utility.cs index c769e0b5..451075f3 100644 --- a/src/SharpCompress/Utility.cs +++ b/src/SharpCompress/Utility.cs @@ -21,9 +21,10 @@ namespace SharpCompress public static int URShift(int number, int bits) { if (number >= 0) + { return number >> bits; - else - return (number >> bits) + (2 << ~bits); + } + return (number >> bits) + (2 << ~bits); } /// @@ -35,9 +36,10 @@ namespace SharpCompress public static long URShift(long number, int bits) { if (number >= 0) + { return number >> bits; - else - return (number >> bits) + (2L << ~bits); + } + return (number >> bits) + (2L << ~bits); } /// @@ -57,7 +59,7 @@ namespace SharpCompress { throw new ArgumentException(); } - if ((fromindex < 0) || ((System.Array)array).Length < toindex) + if ((fromindex < 0) || array.Length < toindex) { throw new IndexOutOfRangeException(); } @@ -155,7 +157,8 @@ namespace SharpCompress { break; } - } while (true); + } + while (true); } public static void SkipAll(this Stream source) @@ -163,7 +166,8 @@ namespace SharpCompress byte[] buffer = new byte[32 * 1024]; do { - } while (source.Read(buffer, 0, buffer.Length) == buffer.Length); + } + while (source.Read(buffer, 0, buffer.Length) == buffer.Length); } public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime) @@ -209,12 +213,11 @@ namespace SharpCompress var localDateTime = dateTime.Value.ToLocalTime(); return (uint)( - (localDateTime.Second / 2) | (localDateTime.Minute << 5) | (localDateTime.Hour << 11) | - (localDateTime.Day << 16) | (localDateTime.Month << 21) | - ((localDateTime.Year - 1980) << 25)); + (localDateTime.Second / 2) | (localDateTime.Minute << 5) | (localDateTime.Hour << 11) | + (localDateTime.Day << 16) | (localDateTime.Month << 21) | + ((localDateTime.Year - 1980) << 25)); } - public static DateTime DosDateToDateTime(UInt32 iTime) { return DosDateToDateTime((UInt16)(iTime / 65536), @@ -274,7 +277,7 @@ namespace SharpCompress } return true; } - + public static void CopyTo(this byte[] array, byte[] destination, int index) { Array.Copy(array, 0, destination, index, array.Length); diff --git a/src/SharpCompress/Writer/AbstractWriter.cs b/src/SharpCompress/Writer/AbstractWriter.cs index 2c45827f..c04e41e6 100644 --- a/src/SharpCompress/Writer/AbstractWriter.cs +++ b/src/SharpCompress/Writer/AbstractWriter.cs @@ -11,20 +11,20 @@ namespace SharpCompress.Writer protected AbstractWriter(ArchiveType type) { - this.WriterType = type; + WriterType = type; } protected void InitalizeStream(Stream stream, bool closeStream) { - this.OutputStream = stream; + OutputStream = stream; this.closeStream = closeStream; } protected Stream OutputStream { get; private set; } - public ArchiveType WriterType { get; private set; } + public ArchiveType WriterType { get; } - public abstract void Write(string filename, System.IO.Stream source, DateTime? modificationTime); + public abstract void Write(string filename, Stream source, DateTime? modificationTime); protected virtual void Dispose(bool isDisposing) { diff --git a/src/SharpCompress/Writer/IWriter.Extensions.cs b/src/SharpCompress/Writer/IWriter.Extensions.cs index ac158575..a7f36043 100644 --- a/src/SharpCompress/Writer/IWriter.Extensions.cs +++ b/src/SharpCompress/Writer/IWriter.Extensions.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; namespace SharpCompress.Writer { @@ -45,5 +44,5 @@ namespace SharpCompress.Writer } } #endif - } + } } \ No newline at end of file diff --git a/src/SharpCompress/Writer/Tar/TarWriter.cs b/src/SharpCompress/Writer/Tar/TarWriter.cs index e03cda09..2f7600e1 100644 --- a/src/SharpCompress/Writer/Tar/TarWriter.cs +++ b/src/SharpCompress/Writer/Tar/TarWriter.cs @@ -22,19 +22,19 @@ namespace SharpCompress.Writer.Tar case CompressionType.None: break; case CompressionType.BZip2: - { - destination = new BZip2Stream(destination, CompressionMode.Compress, leaveOpen); - } + { + destination = new BZip2Stream(destination, CompressionMode.Compress, leaveOpen); + } break; case CompressionType.GZip: - { - destination = new GZipStream(destination, CompressionMode.Compress, leaveOpen); - } + { + destination = new GZipStream(destination, CompressionMode.Compress, leaveOpen); + } break; default: - { - throw new InvalidFormatException("Tar does not support compression: " + compressionInfo.Type); - } + { + throw new InvalidFormatException("Tar does not support compression: " + compressionInfo.Type); + } } InitalizeStream(destination, !leaveOpen); } @@ -50,7 +50,9 @@ namespace SharpCompress.Writer.Tar int pos = filename.IndexOf(':'); if (pos >= 0) + { filename = filename.Remove(0, pos + 1); + } return filename.Trim('/'); } @@ -64,7 +66,6 @@ namespace SharpCompress.Writer.Tar long realSize = size ?? source.Length; - TarHeader header = new TarHeader(); header.LastModifiedTime = modificationTime ?? TarHeader.Epoch; header.Name = NormalizeFilename(filename); @@ -76,7 +77,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; diff --git a/src/SharpCompress/Writer/WriterFactory.cs b/src/SharpCompress/Writer/WriterFactory.cs index 05691eb4..746137dc 100644 --- a/src/SharpCompress/Writer/WriterFactory.cs +++ b/src/SharpCompress/Writer/WriterFactory.cs @@ -12,9 +12,9 @@ namespace SharpCompress.Writer public static IWriter Open(Stream stream, ArchiveType archiveType, CompressionType compressionType, bool leaveOpen = false) { return Open(stream, archiveType, new CompressionInfo - { - Type = compressionType - }, leaveOpen); + { + Type = compressionType + }, leaveOpen); } public static IWriter Open(Stream stream, ArchiveType archiveType, CompressionInfo compressionInfo, bool leaveOpen = false) @@ -22,25 +22,25 @@ namespace SharpCompress.Writer 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."); - } - return new GZipWriter(stream, leaveOpen); + throw new InvalidFormatException("GZip archives only support GZip compression type."); } + return new GZipWriter(stream, leaveOpen); + } case ArchiveType.Zip: - { - return new ZipWriter(stream, compressionInfo, null, leaveOpen); - } + { + return new ZipWriter(stream, compressionInfo, null, leaveOpen); + } case ArchiveType.Tar: - { - return new TarWriter(stream, compressionInfo, leaveOpen); - } + { + return new TarWriter(stream, compressionInfo, leaveOpen); + } default: - { - throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); - } + { + throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); + } } } } diff --git a/src/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs b/src/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs index d392abf5..5caa5e24 100644 --- a/src/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs +++ b/src/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs @@ -17,7 +17,6 @@ namespace SharpCompress.Writer.Zip internal uint Compressed { get; set; } internal uint Decompressed { get; set; } - internal uint Write(Stream outputStream, ZipCompressionMethod compression) { byte[] encodedFilename = Encoding.UTF8.GetBytes(FileName); @@ -34,29 +33,31 @@ namespace SharpCompress.Writer.Zip flags |= HeaderFlags.Bit1; // eos marker } } - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) flags), 0, 2); - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) compression), 0, 2); // zipping method + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)flags), 0, 2); + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)compression), 0, 2); // zipping method outputStream.Write(DataConverter.LittleEndian.GetBytes(ModificationTime.DateTimeToDosTime()), 0, 4); - // zipping date and time + + // zipping date and time outputStream.Write(DataConverter.LittleEndian.GetBytes(Crc), 0, 4); // file CRC outputStream.Write(DataConverter.LittleEndian.GetBytes(Compressed), 0, 4); // compressed file size outputStream.Write(DataConverter.LittleEndian.GetBytes(Decompressed), 0, 4); // uncompressed file size - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) encodedFilename.Length), 0, 2); // Filename in zip - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) 0), 0, 2); // extra length - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) encodedComment.Length), 0, 2); + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)0), 0, 2); // extra length + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)encodedComment.Length), 0, 2); - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) 0), 0, 2); // disk=0 - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) 0), 0, 2); // file type: binary - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) 0), 0, 2); // Internal file attributes - outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) 0x8100), 0, 2); - // External file attributes (normal/readable) + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)0), 0, 2); // disk=0 + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)0), 0, 2); // file type: binary + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)0), 0, 2); // Internal file attributes + outputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)0x8100), 0, 2); + + // External file attributes (normal/readable) outputStream.Write(DataConverter.LittleEndian.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/src/SharpCompress/Writer/Zip/ZipCompressionInfo.cs b/src/SharpCompress/Writer/Zip/ZipCompressionInfo.cs index 6c163f21..b04523c2 100644 --- a/src/SharpCompress/Writer/Zip/ZipCompressionInfo.cs +++ b/src/SharpCompress/Writer/Zip/ZipCompressionInfo.cs @@ -14,34 +14,34 @@ namespace SharpCompress.Writer.Zip switch (compressionInfo.Type) { case CompressionType.None: - { - this.Compression = ZipCompressionMethod.None; - } + { + Compression = ZipCompressionMethod.None; + } break; case CompressionType.Deflate: - { - this.DeflateCompressionLevel = compressionInfo.DeflateCompressionLevel; - this.Compression = ZipCompressionMethod.Deflate; - } + { + DeflateCompressionLevel = compressionInfo.DeflateCompressionLevel; + Compression = ZipCompressionMethod.Deflate; + } break; case CompressionType.BZip2: - { - this.Compression = ZipCompressionMethod.BZip2; - } + { + Compression = ZipCompressionMethod.BZip2; + } break; case CompressionType.LZMA: - { - this.Compression = ZipCompressionMethod.LZMA; - } + { + Compression = ZipCompressionMethod.LZMA; + } break; case CompressionType.PPMd: - { - this.Compression = ZipCompressionMethod.PPMd; - } + { + Compression = ZipCompressionMethod.PPMd; + } break; default: throw new InvalidFormatException("Invalid compression method: " + compressionInfo.Type); } } } -} +} \ No newline at end of file diff --git a/src/SharpCompress/Writer/Zip/ZipWriter.cs b/src/SharpCompress/Writer/Zip/ZipWriter.cs index 7b8975ae..2c506540 100644 --- a/src/SharpCompress/Writer/Zip/ZipWriter.cs +++ b/src/SharpCompress/Writer/Zip/ZipWriter.cs @@ -12,7 +12,6 @@ using SharpCompress.Compressor.LZMA; using SharpCompress.Compressor.PPMd; using SharpCompress.Converter; using SharpCompress.IO; -using DeflateStream = SharpCompress.Compressor.Deflate.DeflateStream; namespace SharpCompress.Writer.Zip { @@ -29,7 +28,7 @@ namespace SharpCompress.Writer.Zip { this.zipComment = zipComment ?? string.Empty; - this.zipCompressionInfo = new ZipCompressionInfo(compressionInfo); + zipCompressionInfo = new ZipCompressionInfo(compressionInfo); InitalizeStream(destination, !leaveOpen); } @@ -66,12 +65,12 @@ namespace SharpCompress.Writer.Zip modificationTime = modificationTime ?? DateTime.Now; comment = comment ?? ""; var entry = new ZipCentralDirectoryEntry - { - Comment = comment, - FileName = entryPath, - ModificationTime = modificationTime, - HeaderOffset = (uint) streamPosition, - }; + { + Comment = comment, + FileName = entryPath, + ModificationTime = modificationTime, + HeaderOffset = (uint)streamPosition + }; var headersize = (uint)WriteHeader(entryPath, modificationTime, compressionInfo); streamPosition += headersize; @@ -84,26 +83,28 @@ namespace SharpCompress.Writer.Zip int pos = filename.IndexOf(':'); if (pos >= 0) + { filename = filename.Remove(0, pos + 1); + } return filename.Trim('/'); } private int WriteHeader(string filename, DateTime? modificationTime, CompressionInfo compressionInfo = null) { - var explicitZipCompressionInfo = compressionInfo != null ? new ZipCompressionInfo(compressionInfo) : this.zipCompressionInfo; + var explicitZipCompressionInfo = compressionInfo != null ? new ZipCompressionInfo(compressionInfo) : zipCompressionInfo; byte[] encodedFilename = ArchiveEncoding.Default.GetBytes(filename); OutputStream.Write(DataConverter.LittleEndian.GetBytes(ZipHeaderFactory.ENTRY_HEADER_BYTES), 0, 4); - if (explicitZipCompressionInfo.Compression == ZipCompressionMethod.Deflate) - { - OutputStream.Write(new byte[] {20, 0}, 0, 2); //older version which is more compatible - } - else - { - OutputStream.Write(new byte[] {63, 0}, 0, 2); //version says we used PPMd or LZMA - } - HeaderFlags flags = ArchiveEncoding.Default == Encoding.UTF8 ? HeaderFlags.UTF8 : (HeaderFlags)0; + if (explicitZipCompressionInfo.Compression == ZipCompressionMethod.Deflate) + { + OutputStream.Write(new byte[] {20, 0}, 0, 2); //older version which is more compatible + } + else + { + OutputStream.Write(new byte[] {63, 0}, 0, 2); //version says we used PPMd or LZMA + } + HeaderFlags flags = ArchiveEncoding.Default == Encoding.UTF8 ? HeaderFlags.UTF8 : 0; if (!OutputStream.CanSeek) { flags |= HeaderFlags.UsePostDataDescriptor; @@ -112,14 +113,16 @@ namespace SharpCompress.Writer.Zip flags |= HeaderFlags.Bit1; // eos marker } } - OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) flags), 0, 2); + OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)flags), 0, 2); OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)explicitZipCompressionInfo.Compression), 0, 2); // zipping method OutputStream.Write(DataConverter.LittleEndian.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); + // unused CRC, un/compressed size, updated later - OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) encodedFilename.Length), 0, 2); // filename length - OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) 0), 0, 2); // extra length + OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length + OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)0), 0, 2); // extra length OutputStream.Write(encodedFilename, 0, encodedFilename.Length); return 6 + 2 + 2 + 4 + 12 + 2 + 2 + encodedFilename.Length; @@ -137,11 +140,11 @@ namespace SharpCompress.Writer.Zip byte[] encodedComment = ArchiveEncoding.Default.GetBytes(zipComment); OutputStream.Write(new byte[] {80, 75, 5, 6, 0, 0, 0, 0}, 0, 8); - OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) entries.Count), 0, 2); - OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) entries.Count), 0, 2); + OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)entries.Count), 0, 2); + OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)entries.Count), 0, 2); OutputStream.Write(DataConverter.LittleEndian.GetBytes(size), 0, 4); - OutputStream.Write(DataConverter.LittleEndian.GetBytes((uint) streamPosition), 0, 4); - OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort) encodedComment.Length), 0, 2); + OutputStream.Write(DataConverter.LittleEndian.GetBytes((uint)streamPosition), 0, 4); + OutputStream.Write(DataConverter.LittleEndian.GetBytes((ushort)encodedComment.Length), 0, 2); OutputStream.Write(encodedComment, 0, encodedComment.Length); } @@ -164,35 +167,19 @@ namespace SharpCompress.Writer.Zip this.originalStream = originalStream; this.writer = writer; this.entry = entry; - this.compressionInfo = compressionInfo == null ? writer.zipCompressionInfo : new ZipCompressionInfo(compressionInfo); + this.compressionInfo = compressionInfo == null ? writer.zipCompressionInfo : new ZipCompressionInfo(compressionInfo); writeStream = GetWriteStream(originalStream); } - public override bool CanRead - { - get { return false; } - } + public override bool CanRead { get { return false; } } - public override bool CanSeek - { - get { return false; } - } + public override bool CanSeek { get { return false; } } - public override bool CanWrite - { - get { return true; } - } + public override bool CanWrite { get { return true; } } - public override long Length - { - get { throw new NotSupportedException(); } - } + public override long Length { get { throw new NotSupportedException(); } } - public override long Position - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } private Stream GetWriteStream(Stream writeStream) { @@ -201,39 +188,39 @@ namespace SharpCompress.Writer.Zip switch (compressionInfo.Compression) { case ZipCompressionMethod.None: - { - return output; - } + { + return output; + } case ZipCompressionMethod.Deflate: - { - return new DeflateStream(counting, CompressionMode.Compress, compressionInfo.DeflateCompressionLevel, - true); - } + { + return new DeflateStream(counting, CompressionMode.Compress, compressionInfo.DeflateCompressionLevel, + true); + } case ZipCompressionMethod.BZip2: - { - return new BZip2Stream(counting, CompressionMode.Compress, true); - } + { + return new BZip2Stream(counting, CompressionMode.Compress, true); + } case ZipCompressionMethod.LZMA: - { - counting.WriteByte(9); - counting.WriteByte(20); - counting.WriteByte(5); - counting.WriteByte(0); + { + counting.WriteByte(9); + counting.WriteByte(20); + counting.WriteByte(5); + counting.WriteByte(0); - LzmaStream lzmaStream = new LzmaStream(new LzmaEncoderProperties(!originalStream.CanSeek), - false, counting); - counting.Write(lzmaStream.Properties, 0, lzmaStream.Properties.Length); - return lzmaStream; - } + LzmaStream lzmaStream = new LzmaStream(new LzmaEncoderProperties(!originalStream.CanSeek), + false, counting); + counting.Write(lzmaStream.Properties, 0, lzmaStream.Properties.Length); + return lzmaStream; + } case ZipCompressionMethod.PPMd: - { - counting.Write(writer.ppmdProperties.Properties, 0, 2); - return new PpmdStream(writer.ppmdProperties, counting, true); - } + { + counting.Write(writer.ppmdProperties.Properties, 0, 2); + return new PpmdStream(writer.ppmdProperties, counting, true); + } default: - { - throw new NotSupportedException("CompressionMethod: " + compressionInfo.Compression); - } + { + throw new NotSupportedException("CompressionMethod: " + compressionInfo.Compression); + } } } @@ -243,7 +230,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) @@ -287,7 +274,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); } diff --git a/test/SharpCompress.Test/project.json b/test/SharpCompress.Test/project.json index f4e4d395..220ee5c2 100644 --- a/test/SharpCompress.Test/project.json +++ b/test/SharpCompress.Test/project.json @@ -6,18 +6,14 @@ "dependencies": { "Microsoft.NETCore.App": { "type": "platform", - "version": "1.0.0" + "version": "1.0.1" } - }, - "imports": [ - "dnxcore50", - "portable-net451+win8" - ] + } } }, "dependencies": { "Microsoft.Extensions.PlatformAbstractions": "1.0.0", - "SharpCompress": "0.12.2", + "SharpCompress": { "target" : "project"}, "xunit": "2.2.0-beta2-build3300", "dotnet-test-xunit": "2.2.0-preview2-build1029" }