diff --git a/src/SharpCompress/Algorithms/Adler32.cs b/src/SharpCompress/Algorithms/Adler32.cs index 1f094c13..10dbfc4d 100644 --- a/src/SharpCompress/Algorithms/Adler32.cs +++ b/src/SharpCompress/Algorithms/Adler32.cs @@ -62,7 +62,7 @@ private static class Numerics // From https://github.com/SixLabors/ImageSharp/bl public static int ReduceSum(Vector256 accumulator) { // Add upper lane to lower lane. - Vector128 vsum = Sse2.Add(accumulator.GetLower(), accumulator.GetUpper()); + var vsum = Sse2.Add(accumulator.GetLower(), accumulator.GetUpper()); // Add odd to even. vsum = Sse2.Add(vsum, Sse2.Shuffle(vsum, 0b_11_11_01_01)); @@ -81,7 +81,7 @@ public static int ReduceSum(Vector256 accumulator) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int EvenReduceSum(Vector256 accumulator) { - Vector128 vsum = Sse2.Add(accumulator.GetLower(), accumulator.GetUpper()); // add upper lane to lower lane + var vsum = Sse2.Add(accumulator.GetLower(), accumulator.GetUpper()); // add upper lane to lower lane vsum = Sse2.Add(vsum, Sse2.Shuffle(vsum, 0b_11_10_11_10)); // add high to low // Vector128.ToScalar() isn't optimized pre-net5.0 https://github.com/dotnet/runtime/pull/37882 @@ -189,29 +189,29 @@ public static uint Calculate(uint adler, ReadOnlySpan buffer) [MethodImpl(InliningOptions.HotPath | InliningOptions.ShortMethod)] private static unsafe uint CalculateSse(uint adler, ReadOnlySpan buffer) { - uint s1 = adler & 0xFFFF; - uint s2 = (adler >> 16) & 0xFFFF; + var s1 = adler & 0xFFFF; + var s2 = (adler >> 16) & 0xFFFF; // Process the data in blocks. - uint length = (uint)buffer.Length; - uint blocks = length / BlockSize; + var length = (uint)buffer.Length; + var blocks = length / BlockSize; length -= blocks * BlockSize; fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer)) { fixed (byte* tapPtr = &MemoryMarshal.GetReference(Tap1Tap2)) { - byte* localBufferPtr = bufferPtr; + var localBufferPtr = bufferPtr; // _mm_setr_epi8 on x86 - Vector128 tap1 = Sse2.LoadVector128((sbyte*)tapPtr); - Vector128 tap2 = Sse2.LoadVector128((sbyte*)(tapPtr + 0x10)); - Vector128 zero = Vector128.Zero; + var tap1 = Sse2.LoadVector128((sbyte*)tapPtr); + var tap2 = Sse2.LoadVector128((sbyte*)(tapPtr + 0x10)); + var zero = Vector128.Zero; var ones = Vector128.Create((short)1); while (blocks > 0) { - uint n = NMAX / BlockSize; /* The NMAX constraint. */ + var n = NMAX / BlockSize; /* The NMAX constraint. */ if (n > blocks) { n = blocks; @@ -221,15 +221,15 @@ private static unsafe uint CalculateSse(uint adler, ReadOnlySpan buffer) // Process n blocks of data. At most NMAX data bytes can be // processed before s2 must be reduced modulo BASE. - Vector128 v_ps = Vector128.CreateScalar(s1 * n); - Vector128 v_s2 = Vector128.CreateScalar(s2); - Vector128 v_s1 = Vector128.Zero; + var v_ps = Vector128.CreateScalar(s1 * n); + var v_s2 = Vector128.CreateScalar(s2); + var v_s1 = Vector128.Zero; do { // Load 32 input bytes. - Vector128 bytes1 = Sse3.LoadDquVector128(localBufferPtr); - Vector128 bytes2 = Sse3.LoadDquVector128(localBufferPtr + 0x10); + var bytes1 = Sse3.LoadDquVector128(localBufferPtr); + var bytes2 = Sse3.LoadDquVector128(localBufferPtr + 0x10); // Add previous block byte sum to v_ps. v_ps = Sse2.Add(v_ps, v_s1); @@ -237,11 +237,11 @@ private static unsafe uint CalculateSse(uint adler, ReadOnlySpan buffer) // Horizontally add the bytes for s1, multiply-adds the // bytes by [ 32, 31, 30, ... ] for s2. v_s1 = Sse2.Add(v_s1, Sse2.SumAbsoluteDifferences(bytes1, zero).AsUInt32()); - Vector128 mad1 = Ssse3.MultiplyAddAdjacent(bytes1, tap1); + var mad1 = Ssse3.MultiplyAddAdjacent(bytes1, tap1); v_s2 = Sse2.Add(v_s2, Sse2.MultiplyAddAdjacent(mad1, ones).AsUInt32()); v_s1 = Sse2.Add(v_s1, Sse2.SumAbsoluteDifferences(bytes2, zero).AsUInt32()); - Vector128 mad2 = Ssse3.MultiplyAddAdjacent(bytes2, tap2); + var mad2 = Ssse3.MultiplyAddAdjacent(bytes2, tap2); v_s2 = Sse2.Add(v_s2, Sse2.MultiplyAddAdjacent(mad2, ones).AsUInt32()); localBufferPtr += BlockSize; @@ -281,15 +281,15 @@ private static unsafe uint CalculateSse(uint adler, ReadOnlySpan buffer) [MethodImpl(InliningOptions.HotPath | InliningOptions.ShortMethod)] public static unsafe uint CalculateAvx2(uint adler, ReadOnlySpan buffer) { - uint s1 = adler & 0xFFFF; - uint s2 = (adler >> 16) & 0xFFFF; - uint length = (uint)buffer.Length; + var s1 = adler & 0xFFFF; + var s2 = (adler >> 16) & 0xFFFF; + var length = (uint)buffer.Length; fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer)) { - byte* localBufferPtr = bufferPtr; + var localBufferPtr = bufferPtr; - Vector256 zero = Vector256.Zero; + var zero = Vector256.Zero; var dot3v = Vector256.Create((short)1); var dot2v = Vector256.Create( 32, @@ -333,29 +333,29 @@ public static unsafe uint CalculateAvx2(uint adler, ReadOnlySpan buffer) while (length >= 32) { - int k = length < NMAX ? (int)length : (int)NMAX; + var k = length < NMAX ? (int)length : (int)NMAX; k -= k % 32; length -= (uint)k; - Vector256 vs10 = vs1; - Vector256 vs3 = Vector256.Zero; + var vs10 = vs1; + var vs3 = Vector256.Zero; while (k >= 32) { // Load 32 input bytes. - Vector256 block = Avx.LoadVector256(localBufferPtr); + var block = Avx.LoadVector256(localBufferPtr); // Sum of abs diff, resulting in 2 x int32's - Vector256 vs1sad = Avx2.SumAbsoluteDifferences(block, zero); + var vs1sad = Avx2.SumAbsoluteDifferences(block, zero); vs1 = Avx2.Add(vs1, vs1sad.AsUInt32()); vs3 = Avx2.Add(vs3, vs10); // sum 32 uint8s to 16 shorts. - Vector256 vshortsum2 = Avx2.MultiplyAddAdjacent(block, dot2v); + var vshortsum2 = Avx2.MultiplyAddAdjacent(block, dot2v); // sum 16 shorts to 8 uint32s. - Vector256 vsum2 = Avx2.MultiplyAddAdjacent(vshortsum2, dot3v); + var vsum2 = Avx2.MultiplyAddAdjacent(vshortsum2, dot3v); vs2 = Avx2.Add(vsum2.AsUInt32(), vs2); vs10 = vs1; @@ -434,14 +434,14 @@ public static unsafe uint CalculateAvx2(uint adler, ReadOnlySpan buffer) [MethodImpl(InliningOptions.HotPath | InliningOptions.ShortMethod)] private static unsafe uint CalculateScalar(uint adler, ReadOnlySpan buffer) { - uint s1 = adler & 0xFFFF; - uint s2 = (adler >> 16) & 0xFFFF; + var s1 = adler & 0xFFFF; + var s2 = (adler >> 16) & 0xFFFF; uint k; fixed (byte* bufferPtr = buffer) { var localBufferPtr = bufferPtr; - uint length = (uint)buffer.Length; + var length = (uint)buffer.Length; while (length > 0) { diff --git a/src/SharpCompress/Archives/AbstractWritableArchive.cs b/src/SharpCompress/Archives/AbstractWritableArchive.cs index 30083ec7..84ca0b3f 100644 --- a/src/SharpCompress/Archives/AbstractWritableArchive.cs +++ b/src/SharpCompress/Archives/AbstractWritableArchive.cs @@ -31,10 +31,10 @@ public void Dispose() } } - private readonly List newEntries = new List(); - private readonly List removedEntries = new List(); + private readonly List newEntries = new(); + private readonly List removedEntries = new(); - private readonly List modifiedEntries = new List(); + private readonly List modifiedEntries = new(); private bool hasModifications; private bool pauseRebuilding; diff --git a/src/SharpCompress/Archives/ArchiveVolumeFactory.cs b/src/SharpCompress/Archives/ArchiveVolumeFactory.cs index d8f5535f..81a5d4fd 100644 --- a/src/SharpCompress/Archives/ArchiveVolumeFactory.cs +++ b/src/SharpCompress/Archives/ArchiveVolumeFactory.cs @@ -11,7 +11,7 @@ internal abstract class ArchiveVolumeFactory FileInfo? item = null; //split 001, 002 ... - Match m = Regex.Match(part1.Name, @"^(.*\.)([0-9]+)$", RegexOptions.IgnoreCase); + var m = Regex.Match(part1.Name, @"^(.*\.)([0-9]+)$", RegexOptions.IgnoreCase); if (m.Success) item = new FileInfo( Path.Combine( diff --git a/src/SharpCompress/Archives/GZip/GZipArchive.cs b/src/SharpCompress/Archives/GZip/GZipArchive.cs index fb2f7691..70924b04 100644 --- a/src/SharpCompress/Archives/GZip/GZipArchive.cs +++ b/src/SharpCompress/Archives/GZip/GZipArchive.cs @@ -94,7 +94,7 @@ public static GZipArchive Open(Stream stream, ReaderOptions? readerOptions = nul ); } - public static GZipArchive Create() => new GZipArchive(); + public static GZipArchive Create() => new(); /// /// Constructor with a SourceStream able to handle FileInfo and Streams. diff --git a/src/SharpCompress/Archives/Rar/RarArchive.cs b/src/SharpCompress/Archives/Rar/RarArchive.cs index 5d1883f5..b6472407 100644 --- a/src/SharpCompress/Archives/Rar/RarArchive.cs +++ b/src/SharpCompress/Archives/Rar/RarArchive.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -14,9 +15,8 @@ namespace SharpCompress.Archives.Rar; public class RarArchive : AbstractArchive { internal Lazy UnpackV2017 { get; } = - new Lazy(() => new Compressors.Rar.UnpackV2017.Unpack()); - internal Lazy UnpackV1 { get; } = - new Lazy(() => new Compressors.Rar.UnpackV1.Unpack()); + new(() => new Compressors.Rar.UnpackV2017.Unpack()); + internal Lazy UnpackV1 { get; } = new(() => new Compressors.Rar.UnpackV1.Unpack()); /// /// Constructor with a SourceStream able to handle FileInfo and Streams. diff --git a/src/SharpCompress/Archives/Rar/RarArchiveVolumeFactory.cs b/src/SharpCompress/Archives/Rar/RarArchiveVolumeFactory.cs index 72ccf60f..f5ce89b8 100644 --- a/src/SharpCompress/Archives/Rar/RarArchiveVolumeFactory.cs +++ b/src/SharpCompress/Archives/Rar/RarArchiveVolumeFactory.cs @@ -11,7 +11,7 @@ internal static class RarArchiveVolumeFactory FileInfo? item = null; //new style rar - ..part1 | /part01 | part001 .... - Match m = Regex.Match(part1.Name, @"^(.*\.part)([0-9]+)(\.rar)$", RegexOptions.IgnoreCase); + var m = Regex.Match(part1.Name, @"^(.*\.part)([0-9]+)(\.rar)$", RegexOptions.IgnoreCase); if (m.Success) item = new FileInfo( Path.Combine( diff --git a/src/SharpCompress/Archives/Tar/TarArchive.cs b/src/SharpCompress/Archives/Tar/TarArchive.cs index 43184b66..70ac2413 100644 --- a/src/SharpCompress/Archives/Tar/TarArchive.cs +++ b/src/SharpCompress/Archives/Tar/TarArchive.cs @@ -195,7 +195,7 @@ protected override IEnumerable LoadEntries(IEnumerable new TarArchive(); + public static TarArchive Create() => new(); protected override TarArchiveEntry CreateEntryInternal( string filePath, diff --git a/src/SharpCompress/Archives/Zip/ZipArchive.cs b/src/SharpCompress/Archives/Zip/ZipArchive.cs index 14e4a93e..87e9ac25 100644 --- a/src/SharpCompress/Archives/Zip/ZipArchive.cs +++ b/src/SharpCompress/Archives/Zip/ZipArchive.cs @@ -294,7 +294,7 @@ IEnumerable newEntries bool closeStream ) => new ZipWritableArchiveEntry(this, source, filePath, size, modified, closeStream); - public static ZipArchive Create() => new ZipArchive(); + public static ZipArchive Create() => new(); protected override IReader CreateReaderForSolidExtraction() { diff --git a/src/SharpCompress/Archives/Zip/ZipArchiveVolumeFactory.cs b/src/SharpCompress/Archives/Zip/ZipArchiveVolumeFactory.cs index fdaa85b9..1b2f093d 100644 --- a/src/SharpCompress/Archives/Zip/ZipArchiveVolumeFactory.cs +++ b/src/SharpCompress/Archives/Zip/ZipArchiveVolumeFactory.cs @@ -12,7 +12,7 @@ internal static class ZipArchiveVolumeFactory //load files with zip/zipx first. Swapped to end once loaded in ZipArchive //new style .zip, z01.. | .zipx, zx01 - if the numbers go beyond 99 then they use 100 ...1000 etc - Match m = Regex.Match(part1.Name, @"^(.*\.)(zipx?|zx?[0-9]+)$", RegexOptions.IgnoreCase); + var m = Regex.Match(part1.Name, @"^(.*\.)(zipx?|zx?[0-9]+)$", RegexOptions.IgnoreCase); if (m.Success) item = new FileInfo( Path.Combine( diff --git a/src/SharpCompress/Common/ExtractionMethods.cs b/src/SharpCompress/Common/ExtractionMethods.cs index c8e5896e..a470637a 100644 --- a/src/SharpCompress/Common/ExtractionMethods.cs +++ b/src/SharpCompress/Common/ExtractionMethods.cs @@ -16,7 +16,7 @@ internal static class ExtractionMethods ) { string destinationFileName; - string fullDestinationDirectoryPath = Path.GetFullPath(destinationDirectory); + var fullDestinationDirectoryPath = Path.GetFullPath(destinationDirectory); //check for trailing slash. if ( @@ -36,11 +36,11 @@ internal static class ExtractionMethods options ??= new ExtractionOptions() { Overwrite = true }; - string file = Path.GetFileName(entry.Key); + var file = Path.GetFileName(entry.Key); if (options.ExtractFullPath) { - string folder = Path.GetDirectoryName(entry.Key)!; - string destdir = Path.GetFullPath(Path.Combine(fullDestinationDirectoryPath, folder)); + var folder = Path.GetDirectoryName(entry.Key)!; + var destdir = Path.GetFullPath(Path.Combine(fullDestinationDirectoryPath, folder)); if (!Directory.Exists(destdir)) { @@ -102,7 +102,7 @@ internal static class ExtractionMethods } else { - FileMode fm = FileMode.Create; + var fm = FileMode.Create; options ??= new ExtractionOptions() { Overwrite = true }; if (!options.Overwrite) diff --git a/src/SharpCompress/Common/OptionsBase.cs b/src/SharpCompress/Common/OptionsBase.cs index 61a6cb55..8d1cbd1c 100644 --- a/src/SharpCompress/Common/OptionsBase.cs +++ b/src/SharpCompress/Common/OptionsBase.cs @@ -7,5 +7,5 @@ public class OptionsBase /// public bool LeaveStreamOpen { get; set; } = true; - public ArchiveEncoding ArchiveEncoding { get; set; } = new ArchiveEncoding(); + public ArchiveEncoding ArchiveEncoding { get; set; } = new(); } diff --git a/src/SharpCompress/Common/PasswordProtectedException.cs b/src/SharpCompress/Common/PasswordProtectedException.cs deleted file mode 100644 index 9ebe3d65..00000000 --- a/src/SharpCompress/Common/PasswordProtectedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace SharpCompress.Common; - -public class PasswordProtectedException : ExtractionException -{ - public PasswordProtectedException(string message) - : base(message) { } - - public PasswordProtectedException(string message, Exception inner) - : base(message, inner) { } -} diff --git a/src/SharpCompress/Common/Rar/CryptKey3.cs b/src/SharpCompress/Common/Rar/CryptKey3.cs index 254c692f..93e451b1 100644 --- a/src/SharpCompress/Common/Rar/CryptKey3.cs +++ b/src/SharpCompress/Common/Rar/CryptKey3.cs @@ -12,10 +12,7 @@ internal class CryptKey3 : ICryptKey private string _password; - public CryptKey3(string password) - { - _password = password ?? ""; - } + public CryptKey3(string password) => _password = password ?? ""; public ICryptoTransform Transformer(byte[] salt) { diff --git a/src/SharpCompress/Common/Rar/CryptKey5.cs b/src/SharpCompress/Common/Rar/CryptKey5.cs index 5b4d3981..0b802691 100644 --- a/src/SharpCompress/Common/Rar/CryptKey5.cs +++ b/src/SharpCompress/Common/Rar/CryptKey5.cs @@ -34,35 +34,33 @@ public CryptKey5(string password, Rar5CryptoInfo rar5CryptoInfo) int keyLength ) { - using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(password))) - { - byte[] block = hmac.ComputeHash(salt); - byte[] finalHash = (byte[])block.Clone(); + using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(password)); + var block = hmac.ComputeHash(salt); + var finalHash = (byte[])block.Clone(); - var loop = new int[] { iterations, 17, 17 }; - var res = new List { }; + var loop = new int[] { iterations, 17, 17 }; + var res = new List { }; - for (int x = 0; x < 3; x++) + for (var x = 0; x < 3; x++) + { + for (var i = 1; i < loop[x]; i++) { - for (int i = 1; i < loop[x]; i++) + block = hmac.ComputeHash(block); + for (var j = 0; j < finalHash.Length; j++) { - block = hmac.ComputeHash(block); - for (int j = 0; j < finalHash.Length; j++) - { - finalHash[j] ^= block[j]; - } + finalHash[j] ^= block[j]; } - - res.Add((byte[])finalHash.Clone()); } - return res; + res.Add((byte[])finalHash.Clone()); } + + return res; } public ICryptoTransform Transformer(byte[] salt) { - int iterations = (1 << _cryptoInfo.LG2Count); // Adjust the number of iterations as needed + var iterations = (1 << _cryptoInfo.LG2Count); // Adjust the number of iterations as needed var salt_rar5 = salt.Concat(new byte[] { 0, 0, 0, 1 }); var derivedKey = GenerateRarPBKDF2Key( @@ -76,7 +74,7 @@ public ICryptoTransform Transformer(byte[] salt) _pswCheck = new byte[EncryptionConstV5.SIZE_PSWCHECK]; - for (int i = 0; i < SHA256_DIGEST_SIZE; i++) + for (var i = 0; i < SHA256_DIGEST_SIZE; i++) { _pswCheck[i % EncryptionConstV5.SIZE_PSWCHECK] ^= derivedKey[2][i]; } diff --git a/src/SharpCompress/Common/Rar/Headers/ArchiveCryptHeader.cs b/src/SharpCompress/Common/Rar/Headers/ArchiveCryptHeader.cs index 529b85cc..5aa29d49 100644 --- a/src/SharpCompress/Common/Rar/Headers/ArchiveCryptHeader.cs +++ b/src/SharpCompress/Common/Rar/Headers/ArchiveCryptHeader.cs @@ -12,10 +12,8 @@ internal class ArchiveCryptHeader : RarHeader public ArchiveCryptHeader(RarHeader header, RarCrcBinaryReader reader) : base(header, reader, HeaderType.Crypt) { } - public Rar5CryptoInfo CryptInfo = new Rar5CryptoInfo(); + public Rar5CryptoInfo CryptInfo = new(); - protected override void ReadFinish(MarkingBinaryReader reader) - { + protected override void ReadFinish(MarkingBinaryReader reader) => CryptInfo = new Rar5CryptoInfo(reader, false); - } } diff --git a/src/SharpCompress/Common/Rar/Rar5CryptoInfo.cs b/src/SharpCompress/Common/Rar/Rar5CryptoInfo.cs index 28053a3d..7b8edff9 100644 --- a/src/SharpCompress/Common/Rar/Rar5CryptoInfo.cs +++ b/src/SharpCompress/Common/Rar/Rar5CryptoInfo.cs @@ -42,10 +42,8 @@ public Rar5CryptoInfo(MarkingBinaryReader reader, bool readInitV) } } - public void ReadInitV(MarkingBinaryReader reader) - { + public void ReadInitV(MarkingBinaryReader reader) => InitV = reader.ReadBytes(EncryptionConstV5.SIZE_INITV); - } public bool UsePswCheck = false; diff --git a/src/SharpCompress/Common/Rar/RarCryptoBinaryReader.cs b/src/SharpCompress/Common/Rar/RarCryptoBinaryReader.cs index 982821c3..6e44286b 100644 --- a/src/SharpCompress/Common/Rar/RarCryptoBinaryReader.cs +++ b/src/SharpCompress/Common/Rar/RarCryptoBinaryReader.cs @@ -10,7 +10,7 @@ namespace SharpCompress.Common.Rar; internal sealed class RarCryptoBinaryReader : RarCrcBinaryReader { private BlockTransformer _rijndael; - private readonly Queue _data = new Queue(); + private readonly Queue _data = new(); private long _readCount; public RarCryptoBinaryReader(Stream stream, ICryptKey cryptKey) @@ -22,10 +22,7 @@ public RarCryptoBinaryReader(Stream stream, ICryptKey cryptKey) } public RarCryptoBinaryReader(Stream stream, ICryptKey cryptKey, byte[] salt) - : base(stream) - { - _rijndael = new BlockTransformer(cryptKey.Transformer(salt)); - } + : base(stream) => _rijndael = new BlockTransformer(cryptKey.Transformer(salt)); // track read count ourselves rather than using the underlying stream since we buffer public override long CurrentReadByteCount @@ -39,15 +36,9 @@ protected set public override void Mark() => _readCount = 0; - public override byte ReadByte() - { - return ReadAndDecryptBytes(1)[0]; - } + public override byte ReadByte() => ReadAndDecryptBytes(1)[0]; - public override byte[] ReadBytes(int count) - { - return ReadAndDecryptBytes(count); - } + public override byte[] ReadBytes(int count) => ReadAndDecryptBytes(count); private byte[] ReadAndDecryptBytes(int count) { diff --git a/src/SharpCompress/Common/Rar/RarCryptoWrapper.cs b/src/SharpCompress/Common/Rar/RarCryptoWrapper.cs index e3403ecd..a9798609 100644 --- a/src/SharpCompress/Common/Rar/RarCryptoWrapper.cs +++ b/src/SharpCompress/Common/Rar/RarCryptoWrapper.cs @@ -9,7 +9,7 @@ internal sealed class RarCryptoWrapper : Stream { private readonly Stream _actualStream; private BlockTransformer _rijndael; - private readonly Queue _data = new Queue(); + private readonly Queue _data = new(); public RarCryptoWrapper(Stream actualStream, byte[] salt, ICryptKey key) { @@ -23,10 +23,8 @@ public RarCryptoWrapper(Stream actualStream, byte[] salt, ICryptKey key) public override void SetLength(long value) => throw new NotSupportedException(); - public override int Read(byte[] buffer, int offset, int count) - { - return ReadAndDecrypt(buffer, offset, count); - } + public override int Read(byte[] buffer, int offset, int count) => + ReadAndDecrypt(buffer, offset, count); public int ReadAndDecrypt(byte[] buffer, int offset, int count) { diff --git a/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs b/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs index 5e42494a..ee6f6d08 100644 --- a/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs +++ b/src/SharpCompress/Common/SevenZip/ArchiveDatabase.cs @@ -15,15 +15,15 @@ internal class ArchiveDatabase internal long _startPositionAfterHeader; internal long _dataStartPosition; - internal List _packSizes = new List(); - internal List _packCrCs = new List(); - internal List _folders = new List(); + internal List _packSizes = new(); + internal List _packCrCs = new(); + internal List _folders = new(); internal List _numUnpackStreamsVector; - internal List _files = new List(); + internal List _files = new(); - internal List _packStreamStartPositions = new List(); - internal List _folderStartFileIndex = new List(); - internal List _fileIndexToFolderIndexMap = new List(); + internal List _packStreamStartPositions = new(); + internal List _folderStartFileIndex = new(); + internal List _fileIndexToFolderIndexMap = new(); internal IPasswordProvider PasswordProvider { get; } diff --git a/src/SharpCompress/Common/SevenZip/ArchiveReader.cs b/src/SharpCompress/Common/SevenZip/ArchiveReader.cs index c1376ad9..3e506e0e 100644 --- a/src/SharpCompress/Common/SevenZip/ArchiveReader.cs +++ b/src/SharpCompress/Common/SevenZip/ArchiveReader.cs @@ -14,13 +14,13 @@ namespace SharpCompress.Common.SevenZip; internal class ArchiveReader { internal Stream _stream; - internal Stack _readerStack = new Stack(); + internal Stack _readerStack = new(); internal DataReader _currentReader; internal long _streamOrigin; internal long _streamEnding; internal byte[] _header; - private readonly Dictionary _cachedStreams = new Dictionary(); + private readonly Dictionary _cachedStreams = new(); internal void AddByteStream(byte[] buffer, int offset, int length) { @@ -1359,7 +1359,7 @@ internal class CExtractFolderInfo { internal int _fileIndex; internal int _folderIndex; - internal List _extractStatuses = new List(); + internal List _extractStatuses = new(); internal CExtractFolderInfo(int fileIndex, int folderIndex) { diff --git a/src/SharpCompress/Common/SevenZip/CFolder.cs b/src/SharpCompress/Common/SevenZip/CFolder.cs index 9d3516b1..8b0123da 100644 --- a/src/SharpCompress/Common/SevenZip/CFolder.cs +++ b/src/SharpCompress/Common/SevenZip/CFolder.cs @@ -6,11 +6,11 @@ namespace SharpCompress.Common.SevenZip; internal class CFolder { - internal List _coders = new List(); - internal List _bindPairs = new List(); - internal List _packStreams = new List(); + internal List _coders = new(); + internal List _bindPairs = new(); + internal List _packStreams = new(); internal int _firstPackStreamId; - internal List _unpackSizes = new List(); + internal List _unpackSizes = new(); internal uint? _unpackCrc; internal bool UnpackCrcDefined => _unpackCrc != null; diff --git a/src/SharpCompress/Common/SevenZip/CMethodId.cs b/src/SharpCompress/Common/SevenZip/CMethodId.cs index 6dce5773..8494aad5 100644 --- a/src/SharpCompress/Common/SevenZip/CMethodId.cs +++ b/src/SharpCompress/Common/SevenZip/CMethodId.cs @@ -7,10 +7,10 @@ public const ulong K_LZMA2_ID = 0x21; public const ulong K_AES_ID = 0x06F10701; - public static readonly CMethodId K_COPY = new CMethodId(K_COPY_ID); - public static readonly CMethodId K_LZMA = new CMethodId(K_LZMA_ID); - public static readonly CMethodId K_LZMA2 = new CMethodId(K_LZMA2_ID); - public static readonly CMethodId K_AES = new CMethodId(K_AES_ID); + public static readonly CMethodId K_COPY = new(K_COPY_ID); + public static readonly CMethodId K_LZMA = new(K_LZMA_ID); + public static readonly CMethodId K_LZMA2 = new(K_LZMA2_ID); + public static readonly CMethodId K_AES = new(K_AES_ID); public readonly ulong _id; diff --git a/src/SharpCompress/Common/Tar/Headers/TarHeader.cs b/src/SharpCompress/Common/Tar/Headers/TarHeader.cs index 0e379e6b..a59b74f6 100644 --- a/src/SharpCompress/Common/Tar/Headers/TarHeader.cs +++ b/src/SharpCompress/Common/Tar/Headers/TarHeader.cs @@ -9,7 +9,7 @@ namespace SharpCompress.Common.Tar.Headers; internal sealed class TarHeader { - internal static readonly DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + internal static readonly DateTime EPOCH = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public TarHeader(ArchiveEncoding archiveEncoding) => ArchiveEncoding = archiveEncoding; diff --git a/src/SharpCompress/Common/Tar/TarReadOnlySubStream.cs b/src/SharpCompress/Common/Tar/TarReadOnlySubStream.cs index 2a340dea..09a2fdb8 100644 --- a/src/SharpCompress/Common/Tar/TarReadOnlySubStream.cs +++ b/src/SharpCompress/Common/Tar/TarReadOnlySubStream.cs @@ -63,7 +63,7 @@ public override int Read(byte[] buffer, int offset, int count) { count = (int)BytesLeftToRead; } - int read = Stream.Read(buffer, offset, count); + var read = Stream.Read(buffer, offset, count); if (read > 0) { BytesLeftToRead -= read; @@ -78,7 +78,7 @@ public override int ReadByte() { return -1; } - int value = Stream.ReadByte(); + var value = Stream.ReadByte(); if (value != -1) { --BytesLeftToRead; diff --git a/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs b/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs index d6c4e96d..b5d4b0fb 100644 --- a/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs +++ b/src/SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs @@ -6,7 +6,7 @@ namespace SharpCompress.Common.Zip; internal class PkwareTraditionalEncryptionData { - private static readonly CRC32 CRC32 = new CRC32(); + private static readonly CRC32 CRC32 = new(); private readonly uint[] _keys = { 0x12345678, 0x23456789, 0x34567890 }; private readonly ArchiveEncoding _archiveEncoding; diff --git a/src/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs b/src/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs index 34dd8798..68817d27 100644 --- a/src/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs +++ b/src/SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs @@ -15,10 +15,7 @@ internal class StreamingZipHeaderFactory : ZipHeaderFactory ArchiveEncoding archiveEncoding, IEnumerable? entries ) - : base(StreamingMode.Streaming, password, archiveEncoding) - { - _entries = entries; - } + : base(StreamingMode.Streaming, password, archiveEncoding) => _entries = entries; internal IEnumerable ReadStreamHeader(Stream stream) { diff --git a/src/SharpCompress/Common/Zip/ZipEntry.cs b/src/SharpCompress/Common/Zip/ZipEntry.cs index 61e1b6af..80e33360 100644 --- a/src/SharpCompress/Common/Zip/ZipEntry.cs +++ b/src/SharpCompress/Common/Zip/ZipEntry.cs @@ -22,47 +22,18 @@ internal ZipEntry(ZipFilePart filePart) } } - public override CompressionType CompressionType - { - get + public override CompressionType CompressionType => + _filePart.Header.CompressionMethod switch { - switch (_filePart.Header.CompressionMethod) - { - case ZipCompressionMethod.BZip2: - { - return CompressionType.BZip2; - } - case ZipCompressionMethod.Deflate: - { - return CompressionType.Deflate; - } - case ZipCompressionMethod.Deflate64: - { - return CompressionType.Deflate64; - } - case ZipCompressionMethod.LZMA: - { - return CompressionType.LZMA; - } - case ZipCompressionMethod.PPMd: - { - return CompressionType.PPMd; - } - case ZipCompressionMethod.None: - { - return CompressionType.None; - } - case ZipCompressionMethod.Shrink: - { - return CompressionType.Shrink; - } - default: - { - return CompressionType.Unknown; - } - } - } - } + ZipCompressionMethod.BZip2 => CompressionType.BZip2, + ZipCompressionMethod.Deflate => CompressionType.Deflate, + ZipCompressionMethod.Deflate64 => CompressionType.Deflate64, + ZipCompressionMethod.LZMA => CompressionType.LZMA, + ZipCompressionMethod.PPMd => CompressionType.PPMd, + ZipCompressionMethod.None => CompressionType.None, + ZipCompressionMethod.Shrink => CompressionType.Shrink, + _ => CompressionType.Unknown + }; public override long Crc => _filePart.Header.Crc; diff --git a/src/SharpCompress/Compressors/BZip2/CBZip2InputStream.cs b/src/SharpCompress/Compressors/BZip2/CBZip2InputStream.cs index e03a5096..a541a04d 100644 --- a/src/SharpCompress/Compressors/BZip2/CBZip2InputStream.cs +++ b/src/SharpCompress/Compressors/BZip2/CBZip2InputStream.cs @@ -87,7 +87,7 @@ private void MakeMaps() private int bsBuff; private int bsLive; - private readonly CRC mCrc = new CRC(); + private readonly CRC mCrc = new(); private readonly bool[] inUse = new bool[256]; private int nInUse; diff --git a/src/SharpCompress/Compressors/BZip2/CBZip2OutputStream.cs b/src/SharpCompress/Compressors/BZip2/CBZip2OutputStream.cs index a975ffbd..bf01c2c3 100644 --- a/src/SharpCompress/Compressors/BZip2/CBZip2OutputStream.cs +++ b/src/SharpCompress/Compressors/BZip2/CBZip2OutputStream.cs @@ -284,7 +284,7 @@ private static void HbMakeCodeLengths(char[] len, int[] freq, int alphaSize, int private int bytesOut; private int bsBuff; private int bsLive; - private readonly CRC mCrc = new CRC(); + private readonly CRC mCrc = new(); private readonly bool[] inUse = new bool[256]; private int nInUse; diff --git a/src/SharpCompress/Compressors/Deflate/DeflateManager.cs b/src/SharpCompress/Compressors/Deflate/DeflateManager.cs index 06cf0005..cccd0237 100644 --- a/src/SharpCompress/Compressors/Deflate/DeflateManager.cs +++ b/src/SharpCompress/Compressors/Deflate/DeflateManager.cs @@ -342,9 +342,9 @@ DeflateFlavor flavor private readonly short[] dyn_dtree; // distance tree private readonly short[] bl_tree; // Huffman tree for bit lengths - 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 + private readonly Tree treeLiterals = new(); // desc for literal tree + private readonly Tree treeDistances = new(); // desc for distance tree + private readonly Tree treeBitLengths = new(); // desc for bit length tree // number of codes at each bit length for an optimal tree private readonly short[] bl_count = new short[InternalConstants.MAX_BITS + 1]; @@ -1787,21 +1787,14 @@ internal int End() return status == BUSY_STATE ? ZlibConstants.Z_DATA_ERROR : ZlibConstants.Z_OK; } - private void SetDeflater() - { - switch (config.Flavor) + private void SetDeflater() => + DeflateFunction = config.Flavor switch { - case DeflateFlavor.Store: - DeflateFunction = DeflateNone; - break; - case DeflateFlavor.Fast: - DeflateFunction = DeflateFast; - break; - case DeflateFlavor.Slow: - DeflateFunction = DeflateSlow; - break; - } - } + DeflateFlavor.Store => DeflateNone, + DeflateFlavor.Fast => DeflateFast, + DeflateFlavor.Slow => DeflateSlow, + _ => DeflateFunction + }; internal int SetParams(CompressionLevel level, CompressionStrategy strategy) { diff --git a/src/SharpCompress/Compressors/Deflate/DeflateStream.cs b/src/SharpCompress/Compressors/Deflate/DeflateStream.cs index 05003d7f..5566e817 100644 --- a/src/SharpCompress/Compressors/Deflate/DeflateStream.cs +++ b/src/SharpCompress/Compressors/Deflate/DeflateStream.cs @@ -366,9 +366,5 @@ public override void WriteByte(byte value) #endregion public MemoryStream InputBuffer => - new MemoryStream( - _baseStream._z.InputBuffer, - _baseStream._z.NextIn, - _baseStream._z.AvailableBytesIn - ); + new(_baseStream._z.InputBuffer, _baseStream._z.NextIn, _baseStream._z.AvailableBytesIn); } diff --git a/src/SharpCompress/Compressors/Deflate/GZipStream.cs b/src/SharpCompress/Compressors/Deflate/GZipStream.cs index c547df14..0f7beca8 100644 --- a/src/SharpCompress/Compressors/Deflate/GZipStream.cs +++ b/src/SharpCompress/Compressors/Deflate/GZipStream.cs @@ -35,15 +35,7 @@ namespace SharpCompress.Compressors.Deflate; public class GZipStream : Stream { - internal static readonly DateTime UNIX_EPOCH = new DateTime( - 1970, - 1, - 1, - 0, - 0, - 0, - DateTimeKind.Utc - ); + internal static readonly DateTime UNIX_EPOCH = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); private string? _comment; private string? _fileName; diff --git a/src/SharpCompress/Compressors/Deflate/Inflate.cs b/src/SharpCompress/Compressors/Deflate/Inflate.cs index 37227b3d..d768548b 100644 --- a/src/SharpCompress/Compressors/Deflate/Inflate.cs +++ b/src/SharpCompress/Compressors/Deflate/Inflate.cs @@ -105,11 +105,11 @@ internal sealed class InflateBlocks internal int[] blens; // bit lengths of codes internal uint check; // check on output internal object checkfn; // check function - internal InflateCodes codes = new InflateCodes(); // if CODES, current state + internal InflateCodes codes = new(); // if CODES, current state internal int end; // one byte after sliding window internal int[] hufts; // single malloc for tree space internal int index; // index into blens (or border) - internal InfTree inftree = new InfTree(); + internal InfTree inftree = new(); internal int last; // true if this block is the last block internal int left; // if STORED, bytes left to copy private InflateBlockMode mode; // current inflate_block mode diff --git a/src/SharpCompress/Compressors/Deflate/ZlibBaseStream.cs b/src/SharpCompress/Compressors/Deflate/ZlibBaseStream.cs index 8248e900..94b1491d 100644 --- a/src/SharpCompress/Compressors/Deflate/ZlibBaseStream.cs +++ b/src/SharpCompress/Compressors/Deflate/ZlibBaseStream.cs @@ -102,7 +102,7 @@ private ZlibCodec z { if (_z is null) { - bool wantRfc1950Header = (_flavor == ZlibStreamFlavor.ZLIB); + var wantRfc1950Header = (_flavor == ZlibStreamFlavor.ZLIB); _z = new ZlibCodec(); if (_compressionMode == CompressionMode.Decompress) { @@ -147,13 +147,13 @@ public override void Write(byte[] buffer, int offset, int count) z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; - bool done = false; + var done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; - int rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); + var rc = (_wantCompress) ? _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); @@ -181,18 +181,18 @@ private void finish() if (_streamMode == StreamMode.Writer) { - bool done = false; + var done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; - int rc = + var rc = (_wantCompress) ? _z.Deflate(FlushType.Finish) : _z.Inflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) { - string verb = (_wantCompress ? "de" : "in") + "flating"; + var verb = (_wantCompress ? "de" : "in") + "flating"; if (_z.Message is null) { throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc)); @@ -225,7 +225,7 @@ private void finish() Span intBuf = stackalloc byte[4]; BinaryPrimitives.WriteInt32LittleEndian(intBuf, crc.Crc32Result); _stream.Write(intBuf); - int c2 = (int)(crc.TotalBytesRead & 0x00000000FFFFFFFF); + var c2 = (int)(crc.TotalBytesRead & 0x00000000FFFFFFFF); BinaryPrimitives.WriteInt32LittleEndian(intBuf, c2); _stream.Write(intBuf); } @@ -256,8 +256,8 @@ private void finish() { // Make sure we have read to the end of the stream _z.InputBuffer.AsSpan(_z.NextIn, _z.AvailableBytesIn).CopyTo(trailer); - int bytesNeeded = 8 - _z.AvailableBytesIn; - int bytesRead = _stream.Read( + var bytesNeeded = 8 - _z.AvailableBytesIn; + var bytesRead = _stream.Read( trailer.Slice(_z.AvailableBytesIn, bytesNeeded) ); if (bytesNeeded != bytesRead) @@ -275,10 +275,10 @@ private void finish() _z.InputBuffer.AsSpan(_z.NextIn, trailer.Length).CopyTo(trailer); } - Int32 crc32_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer); - Int32 crc32_actual = crc.Crc32Result; - Int32 isize_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer.Slice(4)); - Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); + var crc32_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer); + var crc32_actual = crc.Crc32Result; + var isize_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer.Slice(4)); + var isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); if (crc32_actual != crc32_expected) { @@ -380,11 +380,11 @@ public int Read() private string ReadZeroTerminatedString() { var list = new List(); - bool done = false; + var done = false; do { // workitem 7740 - int n = _stream.Read(_buf1, 0, 1); + var n = _stream.Read(_buf1, 0, 1); if (n != 1) { throw new ZlibException("Unexpected EOF reading GZIP header."); @@ -398,17 +398,17 @@ private string ReadZeroTerminatedString() list.Add(_buf1[0]); } } while (!done); - byte[] buffer = list.ToArray(); + var buffer = list.ToArray(); return _encoding.GetString(buffer, 0, buffer.Length); } private int _ReadAndValidateGzipHeader() { - int totalBytesRead = 0; + var totalBytesRead = 0; // read the header on the first read Span header = stackalloc byte[10]; - int n = _stream.Read(header); + var n = _stream.Read(header); // workitem 8501: handle edge case (decompress empty stream) if (n == 0) @@ -426,7 +426,7 @@ private int _ReadAndValidateGzipHeader() throw new ZlibException("Bad GZIP header."); } - int timet = BinaryPrimitives.ReadInt32LittleEndian(header.Slice(4)); + var timet = BinaryPrimitives.ReadInt32LittleEndian(header.Slice(4)); _GzipMtime = TarHeader.EPOCH.AddSeconds(timet); totalBytesRead += n; if ((header[3] & 0x04) == 0x04) @@ -435,8 +435,8 @@ private int _ReadAndValidateGzipHeader() n = _stream.Read(header.Slice(0, 2)); // 2-byte length field totalBytesRead += n; - short extraLength = (short)(header[0] + header[1] * 256); - byte[] extra = new byte[extraLength]; + var extraLength = (short)(header[0] + header[1] * 256); + var extra = new byte[extraLength]; n = _stream.Read(extra, 0, extra.Length); if (n != extraLength) { @@ -498,7 +498,7 @@ public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count) throw new ZlibException("Cannot Read after Writing."); } - int rc = 0; + var rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; diff --git a/src/SharpCompress/Compressors/Deflate64/Deflate64Stream.cs b/src/SharpCompress/Compressors/Deflate64/Deflate64Stream.cs index 3eda232c..da4117b9 100644 --- a/src/SharpCompress/Compressors/Deflate64/Deflate64Stream.cs +++ b/src/SharpCompress/Compressors/Deflate64/Deflate64Stream.cs @@ -118,8 +118,8 @@ public override int Read(byte[] array, int offset, int count) EnsureNotDisposed(); int bytesRead; - int currentOffset = offset; - int remainingCount = count; + var currentOffset = offset; + var remainingCount = count; while (true) { @@ -142,7 +142,7 @@ public override int Read(byte[] array, int offset, int count) break; } - int bytes = _stream.Read(_buffer, 0, _buffer.Length); + var bytes = _stream.Read(_buffer, 0, _buffer.Length); if (bytes <= 0) { break; diff --git a/src/SharpCompress/Compressors/Deflate64/DeflateInput.cs b/src/SharpCompress/Compressors/Deflate64/DeflateInput.cs index 6a12df3b..304a2a78 100644 --- a/src/SharpCompress/Compressors/Deflate64/DeflateInput.cs +++ b/src/SharpCompress/Compressors/Deflate64/DeflateInput.cs @@ -22,7 +22,7 @@ internal void ConsumeBytes(int n) Debug.Assert(StartIndex + Count <= Buffer.Length, "Input buffer is in invalid state!"); } - internal InputState DumpState() => new InputState(Count, StartIndex); + internal InputState DumpState() => new(Count, StartIndex); internal void RestoreState(InputState state) { diff --git a/src/SharpCompress/Compressors/Deflate64/HuffmanTree.cs b/src/SharpCompress/Compressors/Deflate64/HuffmanTree.cs index 051b613e..e37802bb 100644 --- a/src/SharpCompress/Compressors/Deflate64/HuffmanTree.cs +++ b/src/SharpCompress/Compressors/Deflate64/HuffmanTree.cs @@ -42,11 +42,9 @@ internal sealed class HuffmanTree private readonly int _tableMask; // huffman tree for static block - public static HuffmanTree StaticLiteralLengthTree { get; } = - new HuffmanTree(GetStaticLiteralTreeLength()); + public static HuffmanTree StaticLiteralLengthTree { get; } = new(GetStaticLiteralTreeLength()); - public static HuffmanTree StaticDistanceTree { get; } = - new HuffmanTree(GetStaticDistanceTreeLength()); + public static HuffmanTree StaticDistanceTree { get; } = new(GetStaticDistanceTreeLength()); public HuffmanTree(byte[] codeLengths) { diff --git a/src/SharpCompress/Compressors/Filters/BCJFilterARM.cs b/src/SharpCompress/Compressors/Filters/BCJFilterARM.cs index 86e90b10..5d861621 100644 --- a/src/SharpCompress/Compressors/Filters/BCJFilterARM.cs +++ b/src/SharpCompress/Compressors/Filters/BCJFilterARM.cs @@ -18,7 +18,7 @@ protected override int Transform(byte[] buffer, int offset, int count) { if ((buffer[i + 3] & 0xFF) == 0xEB) { - int src = + var src = ((buffer[i + 2] & 0xFF) << 16) | ((buffer[i + 1] & 0xFF) << 8) | (buffer[i] & 0xFF); diff --git a/src/SharpCompress/Compressors/Filters/BCJFilterARMT.cs b/src/SharpCompress/Compressors/Filters/BCJFilterARMT.cs index d2ad1bbf..db5b36f2 100644 --- a/src/SharpCompress/Compressors/Filters/BCJFilterARMT.cs +++ b/src/SharpCompress/Compressors/Filters/BCJFilterARMT.cs @@ -18,7 +18,7 @@ protected override int Transform(byte[] buffer, int offset, int count) { if ((buffer[i + 1] & 0xF8) == 0xF0 && (buffer[i + 3] & 0xF8) == 0xF8) { - int src = + var src = ((buffer[i + 1] & 0x07) << 19) | ((buffer[i] & 0xFF) << 11) | ((buffer[i + 3] & 0x07) << 8) diff --git a/src/SharpCompress/Compressors/Filters/BCJFilterIA64.cs b/src/SharpCompress/Compressors/Filters/BCJFilterIA64.cs index 4d89ba39..07eaf319 100644 --- a/src/SharpCompress/Compressors/Filters/BCJFilterIA64.cs +++ b/src/SharpCompress/Compressors/Filters/BCJFilterIA64.cs @@ -52,29 +52,29 @@ protected override int Transform(byte[] buffer, int offset, int count) for (i = offset; i <= end; i += 16) { - int instrTemplate = buffer[i] & 0x1F; - int mask = BRANCH_TABLE[instrTemplate]; + var instrTemplate = buffer[i] & 0x1F; + var mask = BRANCH_TABLE[instrTemplate]; for (int slot = 0, bitPos = 5; slot < 3; ++slot, bitPos += 41) { if (((mask >>> slot) & 1) == 0) continue; - int bytePos = bitPos >>> 3; - int bitRes = bitPos & 7; + var bytePos = bitPos >>> 3; + var bitRes = bitPos & 7; long instr = 0; - for (int j = 0; j < 6; ++j) + for (var j = 0; j < 6; ++j) { instr |= (buffer[i + bytePos + j] & 0xFFL) << (8 * j); } - long instrNorm = instr >>> bitRes; + var instrNorm = instr >>> bitRes; if (((instrNorm >>> 37) & 0x0F) != 0x05 || ((instrNorm >>> 9) & 0x07) != 0x00) continue; - int src = (int)((instrNorm >>> 13) & 0x0FFFFF); + var src = (int)((instrNorm >>> 13) & 0x0FFFFF); src |= ((int)(instrNorm >>> 36) & 1) << 20; src <<= 4; @@ -93,7 +93,7 @@ protected override int Transform(byte[] buffer, int offset, int count) instr &= (1 << bitRes) - 1; instr |= instrNorm << bitRes; - for (int j = 0; j < 6; ++j) + for (var j = 0; j < 6; ++j) { buffer[i + bytePos + j] = (byte)(instr >>> (8 * j)); } diff --git a/src/SharpCompress/Compressors/Filters/BCJFilterPPC.cs b/src/SharpCompress/Compressors/Filters/BCJFilterPPC.cs index 11ed61a1..ccfa7480 100644 --- a/src/SharpCompress/Compressors/Filters/BCJFilterPPC.cs +++ b/src/SharpCompress/Compressors/Filters/BCJFilterPPC.cs @@ -18,7 +18,7 @@ protected override int Transform(byte[] buffer, int offset, int count) { if ((buffer[i] & 0xFC) == 0x48 && (buffer[i + 3] & 0x03) == 0x01) { - int src = + var src = ((buffer[i] & 0x03) << 24) | ((buffer[i + 1] & 0xFF) << 16) | ((buffer[i + 2] & 0xFF) << 8) diff --git a/src/SharpCompress/Compressors/Filters/BCJFilterSPARC.cs b/src/SharpCompress/Compressors/Filters/BCJFilterSPARC.cs index 67756d34..db7c75be 100644 --- a/src/SharpCompress/Compressors/Filters/BCJFilterSPARC.cs +++ b/src/SharpCompress/Compressors/Filters/BCJFilterSPARC.cs @@ -21,7 +21,7 @@ protected override int Transform(byte[] buffer, int offset, int count) || (buffer[i] == 0x7F && (buffer[i + 1] & 0xC0) == 0xC0) ) { - int src = + var src = ((buffer[i] & 0xFF) << 24) | ((buffer[i + 1] & 0xFF) << 16) | ((buffer[i + 2] & 0xFF) << 8) diff --git a/src/SharpCompress/Compressors/Filters/BranchExecFilter.cs b/src/SharpCompress/Compressors/Filters/BranchExecFilter.cs index 9fc439d4..d198cf8f 100644 --- a/src/SharpCompress/Compressors/Filters/BranchExecFilter.cs +++ b/src/SharpCompress/Compressors/Filters/BranchExecFilter.cs @@ -24,40 +24,27 @@ public enum Alignment : int } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool X86TestByte(byte b) - { - return b == 0x00 || b == 0xFF; - } + private static bool X86TestByte(byte b) => b == 0x00 || b == 0xFF; //Replaced X86Converter with bcj_x86() - https://github.com/torvalds/linux/blob/master/lib/xz/xz_dec_bcj.c //This was to fix an issue decoding a Test zip made with WinZip (that 7zip was also able to read). //The previous version of the code would corrupt 2 bytes in the Test.exe at 0x6CF9 (3D6D - should be 4000) - Test zip: WinZip27.Xz.zipx public static void X86Converter(byte[] buf, uint ip, ref uint state) { - bool[] mask_to_allowed_status = new[] - { - true, - true, - true, - false, - true, - false, - false, - false - }; - - byte[] mask_to_bit_num = new byte[] { 0, 1, 2, 2, 3, 3, 3, 3 }; + var mask_to_allowed_status = new[] { true, true, true, false, true, false, false, false }; + + var mask_to_bit_num = new byte[] { 0, 1, 2, 2, 3, 3, 3, 3 }; int i; - int prev_pos = -1; - uint prev_mask = state & 7; + var prev_pos = -1; + var prev_mask = state & 7; uint src; uint dest; uint j; byte b; - uint pos = ip; + var pos = ip; - uint size = (uint)buf.Length; + var size = (uint)buf.Length; if (size <= 4) return; diff --git a/src/SharpCompress/Compressors/Filters/DeltaFilter.cs b/src/SharpCompress/Compressors/Filters/DeltaFilter.cs index c5fbeb41..85ec9b15 100644 --- a/src/SharpCompress/Compressors/Filters/DeltaFilter.cs +++ b/src/SharpCompress/Compressors/Filters/DeltaFilter.cs @@ -23,9 +23,9 @@ public DeltaFilter(bool isEncoder, Stream baseStream, byte[] info) protected override int Transform(byte[] buffer, int offset, int count) { - int end = offset + count; + var end = offset + count; - for (int i = offset; i < end; i++) + for (var i = offset; i < end; i++) { buffer[i] += _history[(_distance + _position--) & DISTANCE_MASK]; _history[_position & DISTANCE_MASK] = buffer[i]; diff --git a/src/SharpCompress/Compressors/LZMA/AesDecoderStream.cs b/src/SharpCompress/Compressors/LZMA/AesDecoderStream.cs index 24823c73..8e884c97 100644 --- a/src/SharpCompress/Compressors/LZMA/AesDecoderStream.cs +++ b/src/SharpCompress/Compressors/LZMA/AesDecoderStream.cs @@ -35,10 +35,10 @@ public AesDecoderStream(Stream input, byte[] info, IPasswordProvider pass, long throw new NotSupportedException("AES decoder does not support padding."); } - Init(info, out int numCyclesPower, out byte[] salt, out byte[] seed); + Init(info, out var numCyclesPower, out var salt, out var seed); - byte[] password = Encoding.Unicode.GetBytes(pass.CryptoGetTextPassword()); - byte[]? key = InitKey(numCyclesPower, salt, password); + var password = Encoding.Unicode.GetBytes(pass.CryptoGetTextPassword()); + var key = InitKey(numCyclesPower, salt, password); if (key == null) { throw new InvalidOperationException("Initialized with null key"); @@ -100,7 +100,7 @@ public override int Read(byte[] buffer, int offset, int count) do { - int read = mStream.Read(mBuffer, mEnding, mBuffer.Length - mEnding); + var read = mStream.Read(mBuffer, mEnding, mBuffer.Length - mEnding); if (read == 0) { // We are not done decoding and have less than 16 bytes. @@ -133,7 +133,7 @@ public override int Read(byte[] buffer, int offset, int count) } // Otherwise we transform directly into the target buffer. - int processed = mDecoder.TransformBlock(mBuffer, mOffset, count & ~15, buffer, offset); + var processed = mDecoder.TransformBlock(mBuffer, mOffset, count & ~15, buffer, offset); mOffset += processed; mWritten += processed; return processed; @@ -143,7 +143,7 @@ public override int Read(byte[] buffer, int offset, int count) private void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte[] iv) { - byte bt = info[0]; + var bt = info[0]; numCyclesPower = bt & 0x3F; if ((bt & 0xC0) == 0) @@ -153,14 +153,14 @@ private void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte return; } - int saltSize = (bt >> 7) & 1; - int ivSize = (bt >> 6) & 1; + var saltSize = (bt >> 7) & 1; + var ivSize = (bt >> 6) & 1; if (info.Length == 1) { throw new InvalidOperationException(); } - byte bt2 = info[1]; + var bt2 = info[1]; saltSize += (bt2 >> 4); ivSize += (bt2 & 15); if (info.Length < 2 + saltSize + ivSize) @@ -169,13 +169,13 @@ private void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte } salt = new byte[saltSize]; - for (int i = 0; i < saltSize; i++) + for (var i = 0; i < saltSize; i++) { salt[i] = info[i + 2]; } iv = new byte[16]; - for (int i = 0; i < ivSize; i++) + for (var i = 0; i < ivSize; i++) { iv[i] = info[i + saltSize + 2]; } @@ -198,7 +198,7 @@ private void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte key[pos] = salt[pos]; } - for (int i = 0; i < pass.Length && pos < 32; i++) + for (var i = 0; i < pass.Length && pos < 32; i++) { key[pos++] = pass[i]; } @@ -208,9 +208,9 @@ private void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte else { #if NETSTANDARD2_0 - using IncrementalHash sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - byte[] counter = new byte[8]; - long numRounds = 1L << mNumCyclesPower; + using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var counter = new byte[8]; + var numRounds = 1L << mNumCyclesPower; for (long round = 0; round < numRounds; round++) { sha.AppendData(salt, 0, salt.Length); @@ -219,7 +219,7 @@ private void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte // This mirrors the counter so we don't have to convert long to byte[] each round. // (It also ensures the counter is little endian, which BitConverter does not.) - for (int i = 0; i < 8; i++) + for (var i = 0; i < 8; i++) { if (++counter[i] != 0) { @@ -230,8 +230,8 @@ private void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte return sha.GetHashAndReset(); #else using var sha = SHA256.Create(); - byte[] counter = new byte[8]; - long numRounds = 1L << mNumCyclesPower; + var counter = new byte[8]; + var numRounds = 1L << mNumCyclesPower; for (long round = 0; round < numRounds; round++) { sha.TransformBlock(salt, 0, salt.Length, null, 0); @@ -240,7 +240,7 @@ private void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte // This mirrors the counter so we don't have to convert long to byte[] each round. // (It also ensures the counter is little endian, which BitConverter does not.) - for (int i = 0; i < 8; i++) + for (var i = 0; i < 8; i++) { if (++counter[i] != 0) { @@ -261,7 +261,7 @@ private int HandleUnderflow(byte[] buffer, int offset, int count) // Just transform as much as possible so we can feed from it as long as possible. if (mUnderflow == 0) { - int blockSize = (mEnding - mOffset) & ~15; + var blockSize = (mEnding - mOffset) & ~15; mUnderflow = mDecoder.TransformBlock(mBuffer, mOffset, blockSize, mBuffer, mOffset); } diff --git a/src/SharpCompress/Compressors/LZMA/Log.cs b/src/SharpCompress/Compressors/LZMA/Log.cs index e954e259..1431966c 100644 --- a/src/SharpCompress/Compressors/LZMA/Log.cs +++ b/src/SharpCompress/Compressors/LZMA/Log.cs @@ -6,7 +6,7 @@ namespace SharpCompress.Compressors.LZMA; internal static class Log { - private static readonly Stack INDENT = new Stack(); + private static readonly Stack INDENT = new(); private static bool NEEDS_INDENT = true; static Log() => INDENT.Push(""); diff --git a/src/SharpCompress/Compressors/LZMA/LzmaDecoder.cs b/src/SharpCompress/Compressors/LZMA/LzmaDecoder.cs index b460e1be..1b2fdc81 100644 --- a/src/SharpCompress/Compressors/LZMA/LzmaDecoder.cs +++ b/src/SharpCompress/Compressors/LZMA/LzmaDecoder.cs @@ -11,11 +11,11 @@ public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream { private class LenDecoder { - private BitDecoder _choice = new BitDecoder(); - private BitDecoder _choice2 = new BitDecoder(); + private BitDecoder _choice = new(); + private BitDecoder _choice2 = new(); private readonly BitTreeDecoder[] _lowCoder = new BitTreeDecoder[Base.K_NUM_POS_STATES_MAX]; private readonly BitTreeDecoder[] _midCoder = new BitTreeDecoder[Base.K_NUM_POS_STATES_MAX]; - private BitTreeDecoder _highCoder = new BitTreeDecoder(Base.K_NUM_HIGH_LEN_BITS); + private BitTreeDecoder _highCoder = new(Base.K_NUM_HIGH_LEN_BITS); private uint _numPosStates; public void Create(uint numPosStates) @@ -173,18 +173,18 @@ byte matchByte Base.K_NUM_FULL_DISTANCES - Base.K_END_POS_MODEL_INDEX ]; - private BitTreeDecoder _posAlignDecoder = new BitTreeDecoder(Base.K_NUM_ALIGN_BITS); + private BitTreeDecoder _posAlignDecoder = new(Base.K_NUM_ALIGN_BITS); - private readonly LenDecoder _lenDecoder = new LenDecoder(); - private readonly LenDecoder _repLenDecoder = new LenDecoder(); + private readonly LenDecoder _lenDecoder = new(); + private readonly LenDecoder _repLenDecoder = new(); - private readonly LiteralDecoder _literalDecoder = new LiteralDecoder(); + private readonly LiteralDecoder _literalDecoder = new(); private int _dictionarySize; private uint _posStateMask; - private Base.State _state = new Base.State(); + private Base.State _state = new(); private uint _rep0, _rep1, _rep2, diff --git a/src/SharpCompress/Compressors/LZMA/LzmaEncoder.cs b/src/SharpCompress/Compressors/LZMA/LzmaEncoder.cs index e42f8069..509e54c8 100644 --- a/src/SharpCompress/Compressors/LZMA/LzmaEncoder.cs +++ b/src/SharpCompress/Compressors/LZMA/LzmaEncoder.cs @@ -61,7 +61,7 @@ private static uint GetPosSlot2(uint pos) return (uint)(G_FAST_POS[pos >> 26] + 52); } - private Base.State _state = new Base.State(); + private Base.State _state = new(); private byte _previousByte; private readonly uint[] _repDistances = new uint[Base.K_NUM_REP_DISTANCES]; @@ -191,15 +191,15 @@ public void Init() private class LenEncoder { - private BitEncoder _choice = new BitEncoder(); - private BitEncoder _choice2 = new BitEncoder(); + private BitEncoder _choice = new(); + private BitEncoder _choice2 = new(); private readonly BitTreeEncoder[] _lowCoder = new BitTreeEncoder[ Base.K_NUM_POS_STATES_ENCODING_MAX ]; private readonly BitTreeEncoder[] _midCoder = new BitTreeEncoder[ Base.K_NUM_POS_STATES_ENCODING_MAX ]; - private BitTreeEncoder _highCoder = new BitTreeEncoder(Base.K_NUM_HIGH_LEN_BITS); + private BitTreeEncoder _highCoder = new(Base.K_NUM_HIGH_LEN_BITS); public LenEncoder() { @@ -359,7 +359,7 @@ public void MakeAsShortRep() private readonly Optimal[] _optimum = new Optimal[K_NUM_OPTS]; private BinTree _matchFinder; - private readonly RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); + private readonly RangeCoder.Encoder _rangeEncoder = new(); private readonly BitEncoder[] _isMatch = new BitEncoder[ Base.K_NUM_STATES << Base.K_NUM_POS_STATES_BITS_MAX @@ -382,12 +382,12 @@ public void MakeAsShortRep() Base.K_NUM_FULL_DISTANCES - Base.K_END_POS_MODEL_INDEX ]; - private BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.K_NUM_ALIGN_BITS); + private BitTreeEncoder _posAlignEncoder = new(Base.K_NUM_ALIGN_BITS); - private readonly LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); - private readonly LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); + private readonly LenPriceTableEncoder _lenEncoder = new(); + private readonly LenPriceTableEncoder _repMatchLenEncoder = new(); - private readonly LiteralEncoder _literalEncoder = new LiteralEncoder(); + private readonly LiteralEncoder _literalEncoder = new(); private readonly uint[] _matchDistances = new uint[(Base.K_MATCH_MAX_LEN * 2) + 2]; @@ -1727,7 +1727,7 @@ private static int FindMatchFinder(string s) ReadOnlySpan properties ) { - for (int i = 0; i < properties.Length; i++) + for (var i = 0; i < properties.Length; i++) { var prop = properties[i]; switch (propIDs[i]) diff --git a/src/SharpCompress/Compressors/LZMA/LzmaStream.cs b/src/SharpCompress/Compressors/LZMA/LzmaStream.cs index 8e7d4adc..043cbbad 100644 --- a/src/SharpCompress/Compressors/LZMA/LzmaStream.cs +++ b/src/SharpCompress/Compressors/LZMA/LzmaStream.cs @@ -14,8 +14,8 @@ public class LzmaStream : Stream private readonly long _outputSize; private readonly int _dictionarySize; - private readonly OutWindow _outWindow = new OutWindow(); - private readonly RangeCoder.Decoder _rangeDecoder = new RangeCoder.Decoder(); + private readonly OutWindow _outWindow = new(); + private readonly RangeCoder.Decoder _rangeDecoder = new(); private Decoder _decoder; private long _position; diff --git a/src/SharpCompress/Compressors/PPMd/H/ModelPPM.cs b/src/SharpCompress/Compressors/PPMd/H/ModelPPM.cs index 3b2d22ba..d4e91921 100644 --- a/src/SharpCompress/Compressors/PPMd/H/ModelPPM.cs +++ b/src/SharpCompress/Compressors/PPMd/H/ModelPPM.cs @@ -22,7 +22,7 @@ private void InitBlock() } } - public SubAllocator SubAlloc { get; } = new SubAllocator(); + public SubAllocator SubAlloc { get; } = new(); public virtual See2Context DummySee2Cont => _dummySee2Cont; @@ -137,34 +137,34 @@ public virtual int HiBitsFlag // 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 readonly State _tempState1 = new State(null); + private readonly State _tempState1 = new(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 readonly State _tempState2 = new State(null); + private readonly State _tempState2 = new(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 readonly State _tempState3 = new State(null); + private readonly State _tempState3 = new(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 readonly State _tempState4 = new State(null); + private readonly State _tempState4 = new(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 readonly StateRef _tempStateRef1 = new StateRef(); + private readonly StateRef _tempStateRef1 = new(); //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 readonly StateRef _tempStateRef2 = new StateRef(); + private readonly StateRef _tempStateRef2 = new(); //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 readonly PpmContext _tempPpmContext1 = new PpmContext(null); + private readonly PpmContext _tempPpmContext1 = new(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 readonly PpmContext _tempPpmContext2 = new PpmContext(null); + private readonly PpmContext _tempPpmContext2 = new(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 readonly PpmContext _tempPpmContext3 = new PpmContext(null); + private readonly PpmContext _tempPpmContext3 = new(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 readonly PpmContext _tempPpmContext4 = new PpmContext(null); + private readonly PpmContext _tempPpmContext4 = new(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 readonly int[] _ps = new int[MAX_O]; diff --git a/src/SharpCompress/Compressors/PPMd/H/PPMContext.cs b/src/SharpCompress/Compressors/PPMd/H/PPMContext.cs index ab00615d..e4f98c71 100644 --- a/src/SharpCompress/Compressors/PPMd/H/PPMContext.cs +++ b/src/SharpCompress/Compressors/PPMd/H/PPMContext.cs @@ -64,19 +64,19 @@ public virtual int NumStats // 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 readonly State _tempState1 = new State(null); + private readonly State _tempState1 = new(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 readonly State _tempState2 = new State(null); + private readonly State _tempState2 = new(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 readonly State _tempState3 = new State(null); + private readonly State _tempState3 = new(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 readonly State _tempState4 = new State(null); + private readonly State _tempState4 = new(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 readonly State _tempState5 = new State(null); + private readonly State _tempState5 = new(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'" diff --git a/src/SharpCompress/Compressors/PPMd/I1/MemoryNode.cs b/src/SharpCompress/Compressors/PPMd/I1/MemoryNode.cs index 5e978c5c..c8b411d8 100644 --- a/src/SharpCompress/Compressors/PPMd/I1/MemoryNode.cs +++ b/src/SharpCompress/Compressors/PPMd/I1/MemoryNode.cs @@ -27,7 +27,7 @@ internal struct MemoryNode { public uint _address; public byte[] _memory; - public static readonly MemoryNode ZERO = new MemoryNode(0, null); + public static readonly MemoryNode ZERO = new(0, null); public const int SIZE = 12; /// @@ -64,7 +64,7 @@ public uint Stamp public MemoryNode Next { get => - new MemoryNode( + new( _memory[_address + 4] | (((uint)_memory[_address + 5]) << 8) | (((uint)_memory[_address + 6]) << 16) @@ -150,7 +150,7 @@ public MemoryNode Remove() /// /// public static implicit operator MemoryNode(Pointer pointer) => - new MemoryNode(pointer._address, pointer._memory); + new(pointer._address, pointer._memory); /// /// Allow pointer-like addition on a memory node. diff --git a/src/SharpCompress/Compressors/PPMd/I1/Pointer.cs b/src/SharpCompress/Compressors/PPMd/I1/Pointer.cs index 72c557ba..d1a89545 100644 --- a/src/SharpCompress/Compressors/PPMd/I1/Pointer.cs +++ b/src/SharpCompress/Compressors/PPMd/I1/Pointer.cs @@ -22,7 +22,7 @@ internal struct Pointer { public uint _address; public byte[] _memory; - public static readonly Pointer ZERO = new Pointer(0, null); + public static readonly Pointer ZERO = new(0, null); public const int SIZE = 1; /// @@ -69,7 +69,7 @@ public Pointer(uint address, byte[] memory) /// /// public static implicit operator Pointer(MemoryNode memoryNode) => - new Pointer(memoryNode._address, memoryNode._memory); + new(memoryNode._address, memoryNode._memory); /// /// Allow a to be implicitly converted to a . @@ -77,15 +77,14 @@ public Pointer(uint address, byte[] memory) /// /// public static implicit operator Pointer(Model.PpmContext context) => - new Pointer(context._address, context._memory); + new(context._address, context._memory); /// /// Allow a to be implicitly converted to a . /// /// /// - public static implicit operator Pointer(PpmState state) => - new Pointer(state._address, state._memory); + public static implicit operator Pointer(PpmState state) => new(state._address, state._memory); /// /// Increase the address of a pointer by the given number of bytes. diff --git a/src/SharpCompress/Compressors/PPMd/I1/PpmContext.cs b/src/SharpCompress/Compressors/PPMd/I1/PpmContext.cs index a37d278d..701039c2 100644 --- a/src/SharpCompress/Compressors/PPMd/I1/PpmContext.cs +++ b/src/SharpCompress/Compressors/PPMd/I1/PpmContext.cs @@ -21,7 +21,7 @@ internal struct PpmContext { public uint _address; public byte[] _memory; - public static readonly PpmContext ZERO = new PpmContext(0, null); + public static readonly PpmContext ZERO = new(0, null); public const int SIZE = 12; /// @@ -70,7 +70,7 @@ public ushort SummaryFrequency public PpmState Statistics { get => - new PpmState( + new( _memory[_address + 4] | (((uint)_memory[_address + 5]) << 8) | (((uint)_memory[_address + 6]) << 16) @@ -92,7 +92,7 @@ public PpmState Statistics public PpmContext Suffix { get => - new PpmContext( + new( _memory[_address + 8] | (((uint)_memory[_address + 9]) << 8) | (((uint)_memory[_address + 10]) << 16) @@ -133,7 +133,7 @@ public PpmContext Suffix /// /// /// - public PpmState FirstState => new PpmState(_address + 2, _memory); + public PpmState FirstState => new(_address + 2, _memory); /// /// Gets or sets the symbol of the first PPM state. This is provided for convenience. The same @@ -164,7 +164,7 @@ public byte FirstStateFrequency public PpmContext FirstStateSuccessor { get => - new PpmContext( + new( _memory[_address + 4] | (((uint)_memory[_address + 5]) << 8) | (((uint)_memory[_address + 6]) << 16) @@ -186,7 +186,7 @@ public PpmContext FirstStateSuccessor /// /// public static implicit operator PpmContext(Pointer pointer) => - new PpmContext(pointer._address, pointer._memory); + new(pointer._address, pointer._memory); /// /// Allow pointer-like addition on a PPM context. diff --git a/src/SharpCompress/Compressors/PPMd/I1/PpmState.cs b/src/SharpCompress/Compressors/PPMd/I1/PpmState.cs index 757afd00..02e79a34 100644 --- a/src/SharpCompress/Compressors/PPMd/I1/PpmState.cs +++ b/src/SharpCompress/Compressors/PPMd/I1/PpmState.cs @@ -19,7 +19,7 @@ internal struct PpmState { public uint _address; public byte[] _memory; - public static readonly PpmState ZERO = new PpmState(0, null); + public static readonly PpmState ZERO = new(0, null); public const int SIZE = 6; /// @@ -55,7 +55,7 @@ public byte Frequency public Model.PpmContext Successor { get => - new Model.PpmContext( + new( _memory[_address + 2] | (((uint)_memory[_address + 3]) << 8) | (((uint)_memory[_address + 4]) << 16) @@ -77,7 +77,7 @@ public Model.PpmContext Successor /// /// /// - public PpmState this[int offset] => new PpmState((uint)(_address + (offset * SIZE)), _memory); + public PpmState this[int offset] => new((uint)(_address + (offset * SIZE)), _memory); /// /// Allow a pointer to be implicitly converted to a PPM state. @@ -85,7 +85,7 @@ public Model.PpmContext Successor /// /// public static implicit operator PpmState(Pointer pointer) => - new PpmState(pointer._address, pointer._memory); + new(pointer._address, pointer._memory); /// /// Allow pointer-like addition on a PPM state. diff --git a/src/SharpCompress/Compressors/Rar/RarBLAKE2spStream.cs b/src/SharpCompress/Compressors/Rar/RarBLAKE2spStream.cs index d3e90c4c..7c897176 100644 --- a/src/SharpCompress/Compressors/Rar/RarBLAKE2spStream.cs +++ b/src/SharpCompress/Compressors/Rar/RarBLAKE2spStream.cs @@ -73,7 +73,7 @@ internal class BLAKE2SP public BLAKE2SP() { S = new BLAKE2S[BLAKE2SP_PARALLEL_DEGREE]; - for (int i = 0; i < S.Length; i++) + for (var i = 0; i < S.Length; i++) { S[i] = new BLAKE2S(); } @@ -141,15 +141,15 @@ internal void ResetCrc(BLAKE2S hash) internal void Compress(BLAKE2S hash) { - UInt32[] m = new UInt32[16]; - UInt32[] v = new UInt32[16]; + var m = new UInt32[16]; + var v = new UInt32[16]; - for (int i = 0; i < 16; i++) + for (var i = 0; i < 16; i++) { m[i] = BitConverter.ToUInt32(hash.b, i * 4); } - for (int i = 0; i < 8; i++) + for (var i = 0; i < 8; i++) { v[i] = hash.h[i]; } @@ -164,7 +164,7 @@ internal void Compress(BLAKE2S hash) v[14] = hash.f[0] ^ k_BLAKE2S_IV[6]; v[15] = hash.f[1] ^ k_BLAKE2S_IV[7]; - for (int r = 0; r < BLAKE2S_NUM_ROUNDS; r++) + for (var r = 0; r < BLAKE2S_NUM_ROUNDS; r++) { ref byte[] sigma = ref k_BLAKE2S_Sigma[r]; @@ -178,7 +178,7 @@ internal void Compress(BLAKE2S hash) G(ref m, ref sigma, 7, ref v[3], ref v[4], ref v[9], ref v[14]); } - for (int i = 0; i < 8; i++) + for (var i = 0; i < 8; i++) { hash.h[i] ^= v[i] ^ v[i + 8]; } @@ -186,7 +186,7 @@ internal void Compress(BLAKE2S hash) internal void Update(BLAKE2S hash, ReadOnlySpan data, int size) { - int i = 0; + var i = 0; while (size != 0) { var pos = hash.bufferPosition; @@ -219,7 +219,7 @@ internal byte[] Final(BLAKE2S hash) var mem = new MemoryStream(); - for (int i = 0; i < 8; i++) + for (var i = 0; i < 8; i++) { mem.Write(BitConverter.GetBytes(hash.h[i]), 0, 4); } @@ -245,7 +245,7 @@ public void ResetCrc() internal void Update(BLAKE2SP hash, ReadOnlySpan data, int size) { - int i = 0; + var i = 0; var pos = hash.bufferPosition; while (size != 0) { @@ -274,7 +274,7 @@ internal byte[] Final(BLAKE2SP hash) h.h[3] ^= (1 << 16 | BLAKE2S_DIGEST_SIZE << 24); h.lastNodeFlag = BLAKE2S_FINAL_FLAG; - for (int i = 0; i < BLAKE2SP_PARALLEL_DEGREE; i++) + for (var i = 0; i < BLAKE2SP_PARALLEL_DEGREE; i++) { var digest = Final(_blake2sp.S[i]); Update(h, digest, BLAKE2S_DIGEST_SIZE); diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack.cs index 2ca62d6b..e6d4153d 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack.cs @@ -52,19 +52,19 @@ public int Char public int PpmEscChar { get; set; } - private readonly ModelPpm ppm = new ModelPpm(); + private readonly ModelPpm ppm = new(); - private readonly RarVM rarVM = new RarVM(); + private readonly RarVM rarVM = new(); // Filters code, one entry per filter - private readonly List filters = new List(); + private readonly List filters = new(); // Filters stack, several entrances of same filter are possible - private readonly List prgStack = new List(); + private readonly List prgStack = new(); // lengths of preceding blocks, one length per filter. Used to reduce size // required to write block length if lengths are repeating - private readonly List oldFilterLengths = new List(); + private readonly List oldFilterLengths = new(); private int lastFilter; diff --git a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs index 15b980da..3a5d008d 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs @@ -25,15 +25,15 @@ internal partial class Unpack private readonly AudioVariables[] AudV = new AudioVariables[4]; - private readonly LitDecode LD = new LitDecode(); + private readonly LitDecode LD = new(); - private readonly DistDecode DD = new DistDecode(); + private readonly DistDecode DD = new(); - private readonly LowDistDecode LDD = new LowDistDecode(); + private readonly LowDistDecode LDD = new(); - private readonly RepDecode RD = new RepDecode(); + private readonly RepDecode RD = new(); - private readonly BitDecode BD = new BitDecode(); + private readonly BitDecode BD = new(); private static readonly int[] LDecode = { diff --git a/src/SharpCompress/Compressors/Rar/UnpackV2017/unpack_hpp.cs b/src/SharpCompress/Compressors/Rar/UnpackV2017/unpack_hpp.cs index 4f77fc07..3bba4c94 100644 --- a/src/SharpCompress/Compressors/Rar/UnpackV2017/unpack_hpp.cs +++ b/src/SharpCompress/Compressors/Rar/UnpackV2017/unpack_hpp.cs @@ -269,7 +269,7 @@ internal partial class Unpack private byte[] FilterDstMemory = Array.Empty(); // Filters code, one entry per filter. - private readonly List Filters = new List(); + private readonly List Filters = new(); private readonly uint[] OldDist = new uint[4]; private uint OldDistPtr; @@ -297,7 +297,7 @@ internal partial class Unpack private byte[] Window; - private readonly FragmentedWindow FragWindow = new FragmentedWindow(); + private readonly FragmentedWindow FragWindow = new(); private bool Fragmented; private int64 DestUnpSize; @@ -393,18 +393,18 @@ internal partial class Unpack // Buffer to read VM filters code. We moved it here from AddVMCode // function to reduce time spent in BitInput constructor. - private readonly BitInput VMCodeInp = new BitInput(true); + private readonly BitInput VMCodeInp = new(true); // Filters code, one entry per filter. - private readonly List Filters30 = new List(); + private readonly List Filters30 = new(); // Filters stack, several entrances of same filter are possible. - private readonly List PrgStack = new List(); + private readonly List PrgStack = new(); // Lengths of preceding data blocks, one length of one last block // for every filter. Used to reduce the size required to write // the data block length if lengths are repeating. - private readonly List OldFilterLengths = new List(); + private readonly List OldFilterLengths = new(); /*#if RarV2017_RAR_SMP // More than 8 threads are unlikely to provide a noticeable gain diff --git a/src/SharpCompress/Compressors/Rar/VM/RarVM.cs b/src/SharpCompress/Compressors/Rar/VM/RarVM.cs index 48b25c5c..185b24d4 100644 --- a/src/SharpCompress/Compressors/Rar/VM/RarVM.cs +++ b/src/SharpCompress/Compressors/Rar/VM/RarVM.cs @@ -1131,13 +1131,13 @@ private VMStandardFilters IsStandardFilter(byte[] code, int codeSize) { 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) + new(53, 0xad576887, VMStandardFilters.VMSF_E8), + new(57, 0x3cd7e57e, VMStandardFilters.VMSF_E8E9), + new(120, 0x3769893f, VMStandardFilters.VMSF_ITANIUM), + new(29, 0x0e06077d, VMStandardFilters.VMSF_DELTA), + new(149, 0x1c2c5dc8, VMStandardFilters.VMSF_RGB), + new(216, 0xbc85e701, VMStandardFilters.VMSF_AUDIO), + new(40, 0x46b9c560, VMStandardFilters.VMSF_UPCASE) }; var CodeCRC = RarCRC.CheckCrc(0xffffffff, code, 0, code.Length) ^ 0xffffffff; for (var i = 0; i < stdList.Length; i++) diff --git a/src/SharpCompress/Compressors/Rar/VM/VMPreparedProgram.cs b/src/SharpCompress/Compressors/Rar/VM/VMPreparedProgram.cs index c0006e09..f1f9e0aa 100644 --- a/src/SharpCompress/Compressors/Rar/VM/VMPreparedProgram.cs +++ b/src/SharpCompress/Compressors/Rar/VM/VMPreparedProgram.cs @@ -4,13 +4,13 @@ namespace SharpCompress.Compressors.Rar.VM; internal class VMPreparedProgram { - internal List Commands = new List(); - internal List AltCommands = new List(); + internal List Commands = new(); + internal List AltCommands = new(); public int CommandCount { get; set; } - internal List GlobalData = new List(); - internal List StaticData = new List(); + internal List GlobalData = new(); + internal List StaticData = new(); // static data contained in DB operators internal int[] InitR = new int[7]; diff --git a/src/SharpCompress/Compressors/Shrink/BitStream.cs b/src/SharpCompress/Compressors/Shrink/BitStream.cs index ef01e2af..949ee6c3 100644 --- a/src/SharpCompress/Compressors/Shrink/BitStream.cs +++ b/src/SharpCompress/Compressors/Shrink/BitStream.cs @@ -57,7 +57,7 @@ private int NextByte() public int NextBits(int nbits) { - int result = 0; + var result = 0; if (nbits > _bitsLeft) { int num; diff --git a/src/SharpCompress/Compressors/Shrink/HwUnshrink.cs b/src/SharpCompress/Compressors/Shrink/HwUnshrink.cs index 04f38c2b..6ad5ab7c 100644 --- a/src/SharpCompress/Compressors/Shrink/HwUnshrink.cs +++ b/src/SharpCompress/Compressors/Shrink/HwUnshrink.cs @@ -27,14 +27,14 @@ private struct CodeTabEntry private static void CodeTabInit(CodeTabEntry[] codeTab) { - for (int i = 0; i <= byte.MaxValue; i++) + for (var i = 0; i <= byte.MaxValue; i++) { codeTab[i].prefixCode = (ushort)i; codeTab[i].extByte = (byte)i; codeTab[i].len = 1; } - for (int i = byte.MaxValue + 1; i <= MAX_CODE; i++) + for (var i = byte.MaxValue + 1; i <= MAX_CODE; i++) { codeTab[i].prefixCode = INVALID_CODE; } @@ -42,11 +42,11 @@ private static void CodeTabInit(CodeTabEntry[] codeTab) private static void UnshrinkPartialClear(CodeTabEntry[] codeTab, ref CodeQueue queue) { - bool[] isPrefix = new bool[MAX_CODE + 1]; + var isPrefix = new bool[MAX_CODE + 1]; int codeQueueSize; // Scan for codes that have been used as a prefix. - for (int i = CONTROL_CODE + 1; i <= MAX_CODE; i++) + for (var i = CONTROL_CODE + 1; i <= MAX_CODE; i++) { if (codeTab[i].prefixCode != INVALID_CODE) { @@ -56,7 +56,7 @@ private static void UnshrinkPartialClear(CodeTabEntry[] codeTab, ref CodeQueue q // Clear "non-prefix" codes in the table; populate the code queue. codeQueueSize = 0; - for (int i = CONTROL_CODE + 1; i <= MAX_CODE; i++) + for (var i = CONTROL_CODE + 1; i <= MAX_CODE; i++) { if (!isPrefix[i]) { @@ -240,8 +240,8 @@ private static void CopyFromPrevPos(byte[] dst, int prevPos, int dstPos, int len out int dstUsed ) { - CodeTabEntry[] codeTab = new CodeTabEntry[HASHTAB_SIZE]; - CodeQueue queue = new CodeQueue(); + var codeTab = new CodeTabEntry[HASHTAB_SIZE]; + var queue = new CodeQueue(); var stream = new BitStream(src, srcLen); int codeSize, dstPos, @@ -323,7 +323,7 @@ private static void CopyFromPrevPos(byte[] dst, int prevPos, int dstPos, int len } // Output the string represented by the current code. - UnshrnkStatus status = OutputCode( + var status = OutputCode( currCode, dst, dstPos, @@ -343,7 +343,7 @@ out len // Verify that the output matches walking the prefixes. var c = currCode; - for (int i = 0; i < len; i++) + for (var i = 0; i < len; i++) { // assert(codeTab[c].len == len - i); //assert(codeTab[c].extByte == dst[dstPos + len - i - 1]); @@ -414,15 +414,13 @@ private static void CodeQueueInit(ref CodeQueue q) q.nextIdx = 0; } - private static ushort CodeQueueNext(ref CodeQueue q) - { + private static ushort CodeQueueNext(ref CodeQueue q) => //assert(q.nextIdx < q.codes.Length); - return q.codes[q.nextIdx]; - } + q.codes[q.nextIdx]; private static ushort CodeQueueRemoveNext(ref CodeQueue q) { - ushort code = CodeQueueNext(ref q); + var code = CodeQueueNext(ref q); if (code != INVALID_CODE) { q.nextIdx++; diff --git a/src/SharpCompress/Compressors/Shrink/ShrinkStream.cs b/src/SharpCompress/Compressors/Shrink/ShrinkStream.cs index 52bba1ad..65b2eb37 100644 --- a/src/SharpCompress/Compressors/Shrink/ShrinkStream.cs +++ b/src/SharpCompress/Compressors/Shrink/ShrinkStream.cs @@ -55,10 +55,10 @@ public override int Read(byte[] buffer, int offset, int count) { return 0; } - byte[] src = new byte[_compressedSize]; + var src = new byte[_compressedSize]; inStream.Read(src, offset, (int)_compressedSize); - int srcUsed = 0; - int dstUsed = 0; + var srcUsed = 0; + var dstUsed = 0; HwUnshrink.Unshrink( src, @@ -70,7 +70,7 @@ out dstUsed ); _outBytesCount = _byteOut.Length; - for (int index = 0; index < _outBytesCount; ++index) + for (var index = 0; index < _outBytesCount; ++index) { buffer[offset + index] = _byteOut[index]; } diff --git a/src/SharpCompress/Compressors/Xz/XZBlock.cs b/src/SharpCompress/Compressors/Xz/XZBlock.cs index ea907609..ddd7eaf3 100644 --- a/src/SharpCompress/Compressors/Xz/XZBlock.cs +++ b/src/SharpCompress/Compressors/Xz/XZBlock.cs @@ -14,7 +14,7 @@ public sealed class XZBlock : XZReadOnlyStream public int BlockHeaderSize => (_blockHeaderSizeByte + 1) * 4; public ulong? CompressedSize { get; private set; } public ulong? UncompressedSize { get; private set; } - public Stack Filters { get; private set; } = new Stack(); + public Stack Filters { get; private set; } = new(); public bool HeaderIsLoaded { get; private set; } private CheckType _checkType; private readonly int _checkSize; diff --git a/src/SharpCompress/Compressors/Xz/XZIndex.cs b/src/SharpCompress/Compressors/Xz/XZIndex.cs index 631f27b2..ddfd7c99 100644 --- a/src/SharpCompress/Compressors/Xz/XZIndex.cs +++ b/src/SharpCompress/Compressors/Xz/XZIndex.cs @@ -13,7 +13,7 @@ public class XZIndex private readonly BinaryReader _reader; public long StreamStartPosition { get; private set; } public ulong NumberOfRecords { get; private set; } - public List Records { get; } = new List(); + public List Records { get; } = new(); private readonly bool _indexMarkerAlreadyVerified; diff --git a/src/SharpCompress/Crypto/BlockTransformer.cs b/src/SharpCompress/Crypto/BlockTransformer.cs index bcb937d0..ed9ead44 100644 --- a/src/SharpCompress/Crypto/BlockTransformer.cs +++ b/src/SharpCompress/Crypto/BlockTransformer.cs @@ -5,25 +5,12 @@ namespace SharpCompress.Crypto; -internal class BlockTransformer : IDisposable +internal class BlockTransformer(ICryptoTransform transformer) : IDisposable { - private ICryptoTransform _transform; - - public BlockTransformer(ICryptoTransform transformer) - { - _transform = transformer; - } - public byte[] ProcessBlock(ReadOnlySpan cipherText) { var decryptedBytes = new byte[cipherText.Length]; - var bytes = _transform.TransformBlock( - cipherText.ToArray(), - 0, - cipherText.Length, - decryptedBytes, - 0 - ); + transformer.TransformBlock(cipherText.ToArray(), 0, cipherText.Length, decryptedBytes, 0); return decryptedBytes; } diff --git a/src/SharpCompress/Crypto/Crc32Stream.cs b/src/SharpCompress/Crypto/Crc32Stream.cs index 7f0af6ca..5f5ccd87 100644 --- a/src/SharpCompress/Crypto/Crc32Stream.cs +++ b/src/SharpCompress/Crypto/Crc32Stream.cs @@ -6,27 +6,17 @@ namespace SharpCompress.Crypto; [CLSCompliant(false)] -public sealed class Crc32Stream : Stream +public sealed class Crc32Stream(Stream stream, uint polynomial, uint seed) : Stream { - public const uint DefaultPolynomial = 0xedb88320u; - public const uint DefaultSeed = 0xffffffffu; + public const uint DEFAULT_POLYNOMIAL = 0xedb88320u; + public const uint DEFAULT_SEED = 0xffffffffu; - private static uint[] defaultTable; + private static uint[] _defaultTable; - private readonly uint[] table; - private uint hash; - - private readonly Stream stream; + private readonly uint[] _table = InitializeTable(polynomial); public Crc32Stream(Stream stream) - : this(stream, DefaultPolynomial, DefaultSeed) { } - - public Crc32Stream(Stream stream, uint polynomial, uint seed) - { - this.stream = stream; - table = InitializeTable(polynomial); - hash = seed; - } + : this(stream, DEFAULT_POLYNOMIAL, DEFAULT_SEED) { } public Stream WrappedStream => stream; @@ -45,20 +35,20 @@ public override void Write(ReadOnlySpan buffer) { stream.Write(buffer); - hash = CalculateCrc(table, hash, buffer); + seed = CalculateCrc(_table, seed, buffer); } #endif public override void Write(byte[] buffer, int offset, int count) { stream.Write(buffer, offset, count); - hash = CalculateCrc(table, hash, buffer.AsSpan(offset, count)); + seed = CalculateCrc(_table, seed, buffer.AsSpan(offset, count)); } public override void WriteByte(byte value) { stream.WriteByte(value); - hash = CalculateCrc(table, hash, value); + seed = CalculateCrc(_table, seed, value); } public override bool CanRead => stream.CanRead; @@ -71,21 +61,21 @@ public override long Position set => throw new NotSupportedException(); } - public uint Crc => ~hash; + public uint Crc => ~seed; - public static uint Compute(byte[] buffer) => Compute(DefaultSeed, buffer); + public static uint Compute(byte[] buffer) => Compute(DEFAULT_SEED, buffer); public static uint Compute(uint seed, byte[] buffer) => - Compute(DefaultPolynomial, seed, buffer); + Compute(DEFAULT_POLYNOMIAL, seed, buffer); public static uint Compute(uint polynomial, uint seed, ReadOnlySpan buffer) => ~CalculateCrc(InitializeTable(polynomial), seed, buffer); private static uint[] InitializeTable(uint polynomial) { - if (polynomial == DefaultPolynomial && defaultTable != null) + if (polynomial == DEFAULT_POLYNOMIAL && _defaultTable != null) { - return defaultTable; + return _defaultTable; } var createTable = new uint[256]; @@ -107,9 +97,9 @@ private static uint[] InitializeTable(uint polynomial) createTable[i] = entry; } - if (polynomial == DefaultPolynomial) + if (polynomial == DEFAULT_POLYNOMIAL) { - defaultTable = createTable; + _defaultTable = createTable; } return createTable; diff --git a/src/SharpCompress/Crypto/CryptoException.cs b/src/SharpCompress/Crypto/CryptoException.cs deleted file mode 100644 index 234fd5e5..00000000 --- a/src/SharpCompress/Crypto/CryptoException.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace SharpCompress.Crypto; - -public class CryptoException : Exception -{ - public CryptoException() { } - - public CryptoException(string message) - : base(message) { } - - public CryptoException(string message, Exception exception) - : base(message, exception) { } -} diff --git a/src/SharpCompress/Crypto/DataLengthException.cs b/src/SharpCompress/Crypto/DataLengthException.cs deleted file mode 100644 index 828c1a8f..00000000 --- a/src/SharpCompress/Crypto/DataLengthException.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace SharpCompress.Crypto; - -public class DataLengthException : CryptoException -{ - /** - * base constructor. - */ - - public DataLengthException() { } - - /** - * create a DataLengthException with the given message. - * - * @param message the message to be carried with the exception. - */ - - public DataLengthException(string message) - : base(message) { } - - public DataLengthException(string message, Exception exception) - : base(message, exception) { } -} diff --git a/src/SharpCompress/Crypto/IBlockCipher.cs b/src/SharpCompress/Crypto/IBlockCipher.cs deleted file mode 100644 index 50eb5fb3..00000000 --- a/src/SharpCompress/Crypto/IBlockCipher.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; - -namespace SharpCompress.Crypto; - -/// Base interface for a symmetric key block cipher. -public interface IBlockCipher -{ - /// The name of the algorithm this cipher implements. - string AlgorithmName { get; } - - /// Initialise the cipher. - /// Initialise for encryption if true, for decryption if false. - /// The key or other data required by the cipher. - void Init(bool forEncryption, ICipherParameters parameters); - - /// The block size for this cipher, in bytes. - int GetBlockSize(); - - /// Indicates whether this cipher can handle partial blocks. - bool IsPartialBlockOkay { get; } - - /// Process a block. - /// The input buffer. - /// The output buffer. - /// If input block is wrong size, or outBuf too small. - /// The number of bytes processed and produced. - int ProcessBlock(ReadOnlySpan inBuf, Span outBuf); - - /// - /// Reset the cipher to the same state as it was after the last init (if there was one). - /// - void Reset(); -} diff --git a/src/SharpCompress/Crypto/ICipherParameters.cs b/src/SharpCompress/Crypto/ICipherParameters.cs deleted file mode 100644 index 9934637a..00000000 --- a/src/SharpCompress/Crypto/ICipherParameters.cs +++ /dev/null @@ -1,3 +0,0 @@ -namespace SharpCompress.Crypto; - -public interface ICipherParameters { } diff --git a/src/SharpCompress/Crypto/KeyParameter.cs b/src/SharpCompress/Crypto/KeyParameter.cs deleted file mode 100644 index fce334f9..00000000 --- a/src/SharpCompress/Crypto/KeyParameter.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -namespace SharpCompress.Crypto; - -public class KeyParameter : ICipherParameters -{ - private readonly byte[] key; - - public KeyParameter(byte[] key) - { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - - this.key = (byte[])key.Clone(); - } - - public KeyParameter(byte[] key, int keyOff, int keyLen) - { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - if (keyOff < 0 || keyOff > key.Length) - { - throw new ArgumentOutOfRangeException(nameof(keyOff)); - } - if (keyLen < 0 || (keyOff + keyLen) > key.Length) - { - throw new ArgumentOutOfRangeException(nameof(keyLen)); - } - - this.key = new byte[keyLen]; - Array.Copy(key, keyOff, this.key, 0, keyLen); - } - - public byte[] GetKey() => (byte[])key.Clone(); -} diff --git a/src/SharpCompress/Factories/Factory.cs b/src/SharpCompress/Factories/Factory.cs index 7ec68508..baef3b85 100644 --- a/src/SharpCompress/Factories/Factory.cs +++ b/src/SharpCompress/Factories/Factory.cs @@ -19,7 +19,7 @@ static Factory() RegisterFactory(new TarFactory()); } - private static readonly HashSet _factories = new HashSet(); + private static readonly HashSet _factories = new(); /// /// Gets the collection of registered . diff --git a/src/SharpCompress/IO/BufferedSubStream.cs b/src/SharpCompress/IO/BufferedSubStream.cs index 0b98f9d0..243d1ca9 100644 --- a/src/SharpCompress/IO/BufferedSubStream.cs +++ b/src/SharpCompress/IO/BufferedSubStream.cs @@ -3,22 +3,14 @@ namespace SharpCompress.IO; -internal class BufferedSubStream : NonDisposingStream +internal class BufferedSubStream(Stream stream, long origin, long bytesToRead) + : NonDisposingStream(stream, throwOnDispose: false) { - private long position; - private int cacheOffset; - private int cacheLength; - private readonly byte[] cache; + private int _cacheOffset; + private int _cacheLength; + private readonly byte[] _cache = new byte[32 << 10]; - public BufferedSubStream(Stream stream, long origin, long bytesToRead) - : base(stream, throwOnDispose: false) - { - position = origin; - BytesLeftToRead = bytesToRead; - cache = new byte[32 << 10]; - } - - private long BytesLeftToRead { get; set; } + private long BytesLeftToRead { get; set; } = bytesToRead; public override bool CanRead => true; @@ -45,22 +37,22 @@ public override int Read(byte[] buffer, int offset, int count) if (count > 0) { - if (cacheLength == 0) + if (_cacheLength == 0) { - cacheOffset = 0; - Stream.Position = position; - cacheLength = Stream.Read(cache, 0, cache.Length); - position += cacheLength; + _cacheOffset = 0; + Stream.Position = origin; + _cacheLength = Stream.Read(_cache, 0, _cache.Length); + origin += _cacheLength; } - if (count > cacheLength) + if (count > _cacheLength) { - count = cacheLength; + count = _cacheLength; } - Buffer.BlockCopy(cache, cacheOffset, buffer, offset, count); - cacheOffset += count; - cacheLength -= count; + Buffer.BlockCopy(_cache, _cacheOffset, buffer, offset, count); + _cacheOffset += count; + _cacheLength -= count; BytesLeftToRead -= count; } diff --git a/src/SharpCompress/IO/DataDescriptorStream.cs b/src/SharpCompress/IO/DataDescriptorStream.cs index b4af4b53..1802556c 100644 --- a/src/SharpCompress/IO/DataDescriptorStream.cs +++ b/src/SharpCompress/IO/DataDescriptorStream.cs @@ -8,18 +8,18 @@ public class DataDescriptorStream : Stream { private readonly Stream _stream; private long _start; - private int _search_position; + private int _searchPosition; private bool _isDisposed; private bool _done; - private static byte[] DataDescriptorMarker = new byte[] { 0x50, 0x4b, 0x07, 0x08 }; - private static long DataDescriptorSize = 24; + private static byte[] _dataDescriptorMarker = new byte[] { 0x50, 0x4b, 0x07, 0x08 }; + private static long _dataDescriptorSize = 24; public DataDescriptorStream(Stream stream) { _stream = stream; _start = _stream.Position; - _search_position = 0; + _searchPosition = 0; _done = false; } @@ -60,20 +60,20 @@ private bool validate_data_descriptor(Stream stream, long size) var br = new BinaryReader(stream); br.ReadUInt32(); br.ReadUInt32(); // CRC32 can be checked if we calculate it - var compressed_size = br.ReadUInt32(); - var uncompressed_size = br.ReadUInt32(); - var uncompressed_64bit = br.ReadInt64(); + var compressedSize = br.ReadUInt32(); + var uncompressedSize = br.ReadUInt32(); + var uncompressed64Bit = br.ReadInt64(); - stream.Position -= DataDescriptorSize; + stream.Position -= _dataDescriptorSize; - var test_64bit = ((long)uncompressed_size << 32) | compressed_size; + var test64Bit = ((long)uncompressedSize << 32) | compressedSize; - if (test_64bit == size && test_64bit == uncompressed_64bit) + if (test64Bit == size && test64Bit == uncompressed64Bit) { return true; } - if (compressed_size == size && compressed_size == uncompressed_size) + if (compressedSize == size && compressedSize == uncompressedSize) { return true; } @@ -88,24 +88,24 @@ public override int Read(byte[] buffer, int offset, int count) return 0; } - int read = _stream.Read(buffer, offset, count); + var read = _stream.Read(buffer, offset, count); - for (int i = 0; i < read; i++) + for (var i = 0; i < read; i++) { - if (buffer[offset + i] == DataDescriptorMarker[_search_position]) + if (buffer[offset + i] == _dataDescriptorMarker[_searchPosition]) { - _search_position++; + _searchPosition++; - if (_search_position == 4) + if (_searchPosition == 4) { - _search_position = 0; + _searchPosition = 0; - if (read - i > DataDescriptorSize) + if (read - i > _dataDescriptorSize) { var check = new MemoryStream( buffer, offset + i - 3, - (int)DataDescriptorSize + (int)_dataDescriptorSize ); _done = validate_data_descriptor( check, @@ -131,15 +131,15 @@ public override int Read(byte[] buffer, int offset, int count) } else { - _search_position = 0; + _searchPosition = 0; } } - if (_search_position > 0) + if (_searchPosition > 0) { - read -= _search_position; - _stream.Position -= _search_position; - _search_position = 0; + read -= _searchPosition; + _stream.Position -= _searchPosition; + _searchPosition = 0; } return read; diff --git a/src/SharpCompress/IO/ListeningStream.cs b/src/SharpCompress/IO/ListeningStream.cs index a1bf715b..0acf1056 100644 --- a/src/SharpCompress/IO/ListeningStream.cs +++ b/src/SharpCompress/IO/ListeningStream.cs @@ -5,13 +5,13 @@ namespace SharpCompress.IO; internal class ListeningStream : Stream { - private long currentEntryTotalReadBytes; - private readonly IExtractionListener listener; + private long _currentEntryTotalReadBytes; + private readonly IExtractionListener _listener; public ListeningStream(IExtractionListener listener, Stream stream) { Stream = stream; - this.listener = listener; + this._listener = listener; } protected override void Dispose(bool disposing) @@ -44,8 +44,8 @@ public override long Position public override int Read(byte[] buffer, int offset, int count) { var read = Stream.Read(buffer, offset, count); - currentEntryTotalReadBytes += read; - listener.FireCompressedBytesRead(currentEntryTotalReadBytes, currentEntryTotalReadBytes); + _currentEntryTotalReadBytes += read; + _listener.FireCompressedBytesRead(_currentEntryTotalReadBytes, _currentEntryTotalReadBytes); return read; } @@ -57,8 +57,8 @@ public override int ReadByte() return -1; } - ++currentEntryTotalReadBytes; - listener.FireCompressedBytesRead(currentEntryTotalReadBytes, currentEntryTotalReadBytes); + ++_currentEntryTotalReadBytes; + _listener.FireCompressedBytesRead(_currentEntryTotalReadBytes, _currentEntryTotalReadBytes); return value; } diff --git a/src/SharpCompress/IO/ReadOnlySubStream.cs b/src/SharpCompress/IO/ReadOnlySubStream.cs index 55c5b575..cd39335e 100644 --- a/src/SharpCompress/IO/ReadOnlySubStream.cs +++ b/src/SharpCompress/IO/ReadOnlySubStream.cs @@ -72,8 +72,8 @@ public override int ReadByte() #if !NETFRAMEWORK && !NETSTANDARD2_0 public override int Read(Span buffer) { - var slice_len = BytesLeftToRead < buffer.Length ? BytesLeftToRead : buffer.Length; - var read = Stream.Read(buffer.Slice(0, (int)slice_len)); + var sliceLen = BytesLeftToRead < buffer.Length ? BytesLeftToRead : buffer.Length; + var read = Stream.Read(buffer.Slice(0, (int)sliceLen)); if (read > 0) { BytesLeftToRead -= read; diff --git a/src/SharpCompress/IO/RewindableStream.cs b/src/SharpCompress/IO/RewindableStream.cs index ff7fe3d0..c7febd1d 100644 --- a/src/SharpCompress/IO/RewindableStream.cs +++ b/src/SharpCompress/IO/RewindableStream.cs @@ -5,98 +5,98 @@ namespace SharpCompress.IO; public class RewindableStream : Stream { - private readonly Stream stream; - private MemoryStream bufferStream = new MemoryStream(); - private bool isRewound; - private bool isDisposed; + private readonly Stream _stream; + private MemoryStream _bufferStream = new(); + private bool _isRewound; + private bool _isDisposed; - public RewindableStream(Stream stream) => this.stream = stream; + public RewindableStream(Stream stream) => this._stream = stream; internal bool IsRecording { get; private set; } protected override void Dispose(bool disposing) { - if (isDisposed) + if (_isDisposed) { return; } - isDisposed = true; + _isDisposed = true; base.Dispose(disposing); if (disposing) { - stream.Dispose(); + _stream.Dispose(); } } public void Rewind(bool stopRecording) { - isRewound = true; + _isRewound = true; IsRecording = !stopRecording; - bufferStream.Position = 0; + _bufferStream.Position = 0; } public void Rewind(MemoryStream buffer) { - if (bufferStream.Position >= buffer.Length) + if (_bufferStream.Position >= buffer.Length) { - bufferStream.Position -= buffer.Length; + _bufferStream.Position -= buffer.Length; } else { - bufferStream.TransferTo(buffer); + _bufferStream.TransferTo(buffer); //create new memorystream to allow proper resizing as memorystream could be a user provided buffer //https://github.com/adamhathcock/sharpcompress/issues/306 - bufferStream = new MemoryStream(); + _bufferStream = new MemoryStream(); buffer.Position = 0; - buffer.TransferTo(bufferStream); - bufferStream.Position = 0; + buffer.TransferTo(_bufferStream); + _bufferStream.Position = 0; } - isRewound = true; + _isRewound = true; } public void StartRecording() { //if (isRewound && bufferStream.Position != 0) // throw new System.NotImplementedException(); - if (bufferStream.Position != 0) + if (_bufferStream.Position != 0) { - var data = bufferStream.ToArray(); - var position = bufferStream.Position; - bufferStream.SetLength(0); - bufferStream.Write(data, (int)position, data.Length - (int)position); - bufferStream.Position = 0; + var data = _bufferStream.ToArray(); + var position = _bufferStream.Position; + _bufferStream.SetLength(0); + _bufferStream.Write(data, (int)position, data.Length - (int)position); + _bufferStream.Position = 0; } IsRecording = true; } public override bool CanRead => true; - public override bool CanSeek => stream.CanSeek; + public override bool CanSeek => _stream.CanSeek; public override bool CanWrite => false; public override void Flush() { } - public override long Length => stream.Length; + public override long Length => _stream.Length; public override long Position { - get => stream.Position + bufferStream.Position - bufferStream.Length; + get => _stream.Position + _bufferStream.Position - _bufferStream.Length; set { - if (!isRewound) + if (!_isRewound) { - stream.Position = value; + _stream.Position = value; } - else if (value < stream.Position - bufferStream.Length || value >= stream.Position) + else if (value < _stream.Position - _bufferStream.Length || value >= _stream.Position) { - stream.Position = value; - isRewound = false; - bufferStream.SetLength(0); + _stream.Position = value; + _isRewound = false; + _bufferStream.SetLength(0); } else { - bufferStream.Position = value - stream.Position + bufferStream.Length; + _bufferStream.Position = value - _stream.Position + _bufferStream.Length; } } } @@ -110,32 +110,32 @@ public override int Read(byte[] buffer, int offset, int count) return 0; } int read; - if (isRewound && bufferStream.Position != bufferStream.Length) + if (_isRewound && _bufferStream.Position != _bufferStream.Length) { // don't read more than left - var readCount = Math.Min(count, (int)(bufferStream.Length - bufferStream.Position)); - read = bufferStream.Read(buffer, offset, readCount); + var readCount = Math.Min(count, (int)(_bufferStream.Length - _bufferStream.Position)); + read = _bufferStream.Read(buffer, offset, readCount); if (read < readCount) { - var tempRead = stream.Read(buffer, offset + read, count - read); + var tempRead = _stream.Read(buffer, offset + read, count - read); if (IsRecording) { - bufferStream.Write(buffer, offset + read, tempRead); + _bufferStream.Write(buffer, offset + read, tempRead); } read += tempRead; } - if (bufferStream.Position == bufferStream.Length && !IsRecording) + if (_bufferStream.Position == _bufferStream.Length && !IsRecording) { - isRewound = false; - bufferStream.SetLength(0); + _isRewound = false; + _bufferStream.SetLength(0); } return read; } - read = stream.Read(buffer, offset, count); + read = _stream.Read(buffer, offset, count); if (IsRecording) { - bufferStream.Write(buffer, offset, read); + _bufferStream.Write(buffer, offset, read); } return read; } diff --git a/src/SharpCompress/Lazy.cs b/src/SharpCompress/Lazy.cs deleted file mode 100644 index 7a6abd55..00000000 --- a/src/SharpCompress/Lazy.cs +++ /dev/null @@ -1,27 +0,0 @@ -#nullable disable - -using System; - -namespace SharpCompress; - -public class Lazy -{ - private readonly Func _lazyFunc; - private bool _evaluated; - private T _value; - - public Lazy(Func lazyFunc) => _lazyFunc = lazyFunc; - - public T Value - { - get - { - if (!_evaluated) - { - _value = _lazyFunc(); - _evaluated = true; - } - return _value; - } - } -} diff --git a/src/SharpCompress/LazyReadOnlyCollection.cs b/src/SharpCompress/LazyReadOnlyCollection.cs index 8f5ee834..cc9cb3fd 100644 --- a/src/SharpCompress/LazyReadOnlyCollection.cs +++ b/src/SharpCompress/LazyReadOnlyCollection.cs @@ -8,7 +8,7 @@ namespace SharpCompress; internal sealed class LazyReadOnlyCollection : ICollection { - private readonly List backing = new List(); + private readonly List backing = new(); private readonly IEnumerator source; private bool fullyLoaded; diff --git a/src/SharpCompress/Readers/AbstractReader.cs b/src/SharpCompress/Readers/AbstractReader.cs index 285f0f84..53069414 100644 --- a/src/SharpCompress/Readers/AbstractReader.cs +++ b/src/SharpCompress/Readers/AbstractReader.cs @@ -190,8 +190,7 @@ public EntryStream OpenEntryStream() /// /// Retains a reference to the entry stream, so we can check whether it completed later. /// - protected EntryStream CreateEntryStream(Stream decompressed) => - new EntryStream(this, decompressed); + protected EntryStream CreateEntryStream(Stream decompressed) => new(this, decompressed); protected virtual EntryStream GetEntryStream() => CreateEntryStream(Entry.Parts.First().GetCompressedStream()); diff --git a/src/SharpCompress/Readers/Rar/RarReader.cs b/src/SharpCompress/Readers/Rar/RarReader.cs index ac346262..a46d2852 100644 --- a/src/SharpCompress/Readers/Rar/RarReader.cs +++ b/src/SharpCompress/Readers/Rar/RarReader.cs @@ -15,9 +15,8 @@ public abstract class RarReader : AbstractReader { private RarVolume? volume; internal Lazy UnpackV2017 { get; } = - new Lazy(() => new Compressors.Rar.UnpackV2017.Unpack()); - internal Lazy UnpackV1 { get; } = - new Lazy(() => new Compressors.Rar.UnpackV1.Unpack()); + new(() => new Compressors.Rar.UnpackV2017.Unpack()); + internal Lazy UnpackV1 { get; } = new(() => new Compressors.Rar.UnpackV1.Unpack()); internal RarReader(ReaderOptions options) : base(options, ArchiveType.Rar) { } diff --git a/src/SharpCompress/Readers/Tar/TarReader.cs b/src/SharpCompress/Readers/Tar/TarReader.cs index 34f337a6..55ef132f 100644 --- a/src/SharpCompress/Readers/Tar/TarReader.cs +++ b/src/SharpCompress/Readers/Tar/TarReader.cs @@ -30,33 +30,15 @@ internal TarReader(Stream stream, ReaderOptions options, CompressionType compres protected override Stream RequestInitialStream() { var stream = base.RequestInitialStream(); - switch (compressionType) + return compressionType switch { - case CompressionType.BZip2: - { - return new BZip2Stream(stream, CompressionMode.Decompress, false); - } - case CompressionType.GZip: - { - return new GZipStream(stream, CompressionMode.Decompress); - } - case CompressionType.LZip: - { - return new LZipStream(stream, CompressionMode.Decompress); - } - case CompressionType.Xz: - { - return new XZStream(stream); - } - case CompressionType.None: - { - return stream; - } - default: - { - throw new NotSupportedException("Invalid compression type: " + compressionType); - } - } + CompressionType.BZip2 => new BZip2Stream(stream, CompressionMode.Decompress, false), + CompressionType.GZip => new GZipStream(stream, CompressionMode.Decompress), + CompressionType.LZip => new LZipStream(stream, CompressionMode.Decompress), + CompressionType.Xz => new XZStream(stream), + CompressionType.None => stream, + _ => throw new NotSupportedException("Invalid compression type: " + compressionType) + }; } #region Open @@ -71,12 +53,12 @@ public static TarReader Open(Stream stream, ReaderOptions? options = null) { stream.CheckNotNull(nameof(stream)); options = options ?? new ReaderOptions(); - RewindableStream rewindableStream = new RewindableStream(stream); + var rewindableStream = new RewindableStream(stream); rewindableStream.StartRecording(); if (GZipArchive.IsGZipFile(rewindableStream)) { rewindableStream.Rewind(false); - GZipStream testStream = new GZipStream(rewindableStream, CompressionMode.Decompress); + var testStream = new GZipStream(rewindableStream, CompressionMode.Decompress); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); @@ -89,11 +71,7 @@ public static TarReader Open(Stream stream, ReaderOptions? options = null) if (BZip2Stream.IsBZip2(rewindableStream)) { rewindableStream.Rewind(false); - BZip2Stream testStream = new BZip2Stream( - rewindableStream, - CompressionMode.Decompress, - false - ); + var testStream = new BZip2Stream(rewindableStream, CompressionMode.Decompress, false); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); @@ -106,7 +84,7 @@ public static TarReader Open(Stream stream, ReaderOptions? options = null) if (LZipStream.IsLZipFile(rewindableStream)) { rewindableStream.Rewind(false); - LZipStream testStream = new LZipStream(rewindableStream, CompressionMode.Decompress); + var testStream = new LZipStream(rewindableStream, CompressionMode.Decompress); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); diff --git a/src/SharpCompress/Utility.cs b/src/SharpCompress/Utility.cs index 9471c3e1..f7e0b17d 100644 --- a/src/SharpCompress/Utility.cs +++ b/src/SharpCompress/Utility.cs @@ -9,8 +9,7 @@ namespace SharpCompress; [CLSCompliant(false)] public static class Utility { - public static ReadOnlyCollection ToReadOnly(this ICollection items) => - new ReadOnlyCollection(items); + public static ReadOnlyCollection ToReadOnly(this ICollection items) => new(items); /// /// Performs an unsigned bitwise right shift with the specified number diff --git a/src/SharpCompress/Writers/WriterOptions.cs b/src/SharpCompress/Writers/WriterOptions.cs index 9d323c2b..e71f86f6 100644 --- a/src/SharpCompress/Writers/WriterOptions.cs +++ b/src/SharpCompress/Writers/WriterOptions.cs @@ -9,5 +9,5 @@ public class WriterOptions : OptionsBase public CompressionType CompressionType { get; set; } public static implicit operator WriterOptions(CompressionType compressionType) => - new WriterOptions(compressionType); + new(compressionType); } diff --git a/src/SharpCompress/Writers/Zip/ZipWriter.cs b/src/SharpCompress/Writers/Zip/ZipWriter.cs index e1bb53e9..9dc094e2 100644 --- a/src/SharpCompress/Writers/Zip/ZipWriter.cs +++ b/src/SharpCompress/Writers/Zip/ZipWriter.cs @@ -19,7 +19,7 @@ public class ZipWriter : AbstractWriter { private readonly CompressionType compressionType; private readonly CompressionLevel compressionLevel; - private readonly List entries = new List(); + private readonly List entries = new(); private readonly string zipComment; private long streamPosition; private PpmdProperties? ppmdProps; @@ -61,34 +61,16 @@ protected override void Dispose(bool isDisposing) base.Dispose(isDisposing); } - private static ZipCompressionMethod ToZipCompressionMethod(CompressionType compressionType) - { - switch (compressionType) + private static ZipCompressionMethod ToZipCompressionMethod(CompressionType compressionType) => + compressionType switch { - case CompressionType.None: - { - return ZipCompressionMethod.None; - } - case CompressionType.Deflate: - { - return ZipCompressionMethod.Deflate; - } - case CompressionType.BZip2: - { - return ZipCompressionMethod.BZip2; - } - case CompressionType.LZMA: - { - return ZipCompressionMethod.LZMA; - } - case CompressionType.PPMd: - { - return ZipCompressionMethod.PPMd; - } - default: - throw new InvalidFormatException("Invalid compression method: " + compressionType); - } - } + CompressionType.None => ZipCompressionMethod.None, + CompressionType.Deflate => ZipCompressionMethod.Deflate, + CompressionType.BZip2 => ZipCompressionMethod.BZip2, + CompressionType.LZMA => ZipCompressionMethod.LZMA, + CompressionType.PPMd => ZipCompressionMethod.PPMd, + _ => throw new InvalidFormatException("Invalid compression method: " + compressionType) + }; public override void Write(string entryPath, Stream source, DateTime? modificationTime) => Write( @@ -324,7 +306,7 @@ private void WriteEndRecord(ulong size) internal class ZipWritingStream : Stream { - private readonly CRC32 crc = new CRC32(); + private readonly CRC32 crc = new(); private readonly ZipCentralDirectoryEntry entry; private readonly Stream originalStream; private readonly Stream writeStream; diff --git a/tests/SharpCompress.Test/ADCTest.cs b/tests/SharpCompress.Test/ADCTest.cs index 11bb2fb0..8ef40a17 100644 --- a/tests/SharpCompress.Test/ADCTest.cs +++ b/tests/SharpCompress.Test/ADCTest.cs @@ -24,7 +24,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.IO; -using SharpCompress.Compressors; using SharpCompress.Compressors.ADC; using SharpCompress.Compressors.Deflate; using SharpCompress.Crypto; @@ -32,7 +31,7 @@ namespace SharpCompress.Test; -public class ADCTest : TestBase +public class AdcTest : TestBase { [Fact] public void TestBuffer() @@ -65,14 +64,14 @@ public void TestBaseStream() } [Fact] - public void TestADCStreamWholeChunk() + public void TestAdcStreamWholeChunk() { using var decFs = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "adc_decompressed.bin")); var decompressed = new byte[decFs.Length]; decFs.Read(decompressed, 0, decompressed.Length); using var cmpFs = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "adc_compressed.bin")); - using var decStream = new ADCStream(cmpFs, CompressionMode.Decompress); + using var decStream = new ADCStream(cmpFs); var test = new byte[262144]; decStream.Read(test, 0, test.Length); @@ -81,14 +80,14 @@ public void TestADCStreamWholeChunk() } [Fact] - public void TestADCStream() + public void TestAdcStream() { using var decFs = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "adc_decompressed.bin")); var decompressed = new byte[decFs.Length]; decFs.Read(decompressed, 0, decompressed.Length); using var cmpFs = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "adc_compressed.bin")); - using var decStream = new ADCStream(cmpFs, CompressionMode.Decompress); + using var decStream = new ADCStream(cmpFs); using var decMs = new MemoryStream(); var test = new byte[512]; var count = 0; @@ -115,11 +114,11 @@ public void TestCrc32Stream() decFs.Seek(0, SeekOrigin.Begin); - var crc32a = crcStream.Crc; + var crc32A = crcStream.Crc; - var crc32b = Crc32Stream.Compute(memory.ToArray()); + var crc32B = Crc32Stream.Compute(memory.ToArray()); - Assert.Equal(crc32, crc32a); - Assert.Equal(crc32, crc32b); + Assert.Equal(crc32, crc32A); + Assert.Equal(crc32, crc32B); } } diff --git a/tests/SharpCompress.Test/ArchiveTests.cs b/tests/SharpCompress.Test/ArchiveTests.cs index ca9a4a16..41135e7d 100644 --- a/tests/SharpCompress.Test/ArchiveTests.cs +++ b/tests/SharpCompress.Test/ArchiveTests.cs @@ -101,7 +101,7 @@ protected void ArchiveStreamRead(ReaderOptions? readerOptions, IEnumerable testArchives ) ) { - try - { - foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) - { - entry.WriteToDirectory( - SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } - ); - } - } - catch (IndexOutOfRangeException) + foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { - throw; + entry.WriteToDirectory( + SCRATCH_FILES_PATH, + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } + ); } } VerifyFiles(); @@ -177,19 +170,12 @@ IEnumerable testArchives ) ) { - try - { - foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) - { - entry.WriteToDirectory( - SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } - ); - } - } - catch (IndexOutOfRangeException) + foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { - throw; + entry.WriteToDirectory( + SCRATCH_FILES_PATH, + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } + ); } } VerifyFiles(); @@ -206,39 +192,29 @@ IEnumerable testArchives testArchives.Select(x => Path.Combine(TEST_ARCHIVES_PATH, x)) ); - protected void ArchiveOpenEntryVolumeIndexTest( + private void ArchiveOpenEntryVolumeIndexTest( int[][] results, ReaderOptions? readerOptions, IEnumerable testArchives ) { var src = testArchives.ToArray(); - using var archive = ArchiveFactory.Open( - testArchives.Select(f => new FileInfo(f)), - readerOptions - ); - try + using var archive = ArchiveFactory.Open(src.Select(f => new FileInfo(f)), readerOptions); + var idx = 0; + foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { - var idx = 0; - foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) - { - Assert.Equal(entry.VolumeIndexFirst, results[idx][0]); - Assert.Equal(entry.VolumeIndexLast, results[idx][1]); - Assert.Equal( - src[entry.VolumeIndexFirst], - archive.Volumes.First(a => a.Index == entry.VolumeIndexFirst).FileName - ); - Assert.Equal( - src[entry.VolumeIndexLast], - archive.Volumes.First(a => a.Index == entry.VolumeIndexLast).FileName - ); + Assert.Equal(entry.VolumeIndexFirst, results[idx][0]); + Assert.Equal(entry.VolumeIndexLast, results[idx][1]); + Assert.Equal( + src[entry.VolumeIndexFirst], + archive.Volumes.First(a => a.Index == entry.VolumeIndexFirst).FileName + ); + Assert.Equal( + src[entry.VolumeIndexLast], + archive.Volumes.First(a => a.Index == entry.VolumeIndexLast).FileName + ); - idx++; - } - } - catch (IndexOutOfRangeException) - { - throw; + idx++; } } @@ -251,7 +227,7 @@ protected void ArchiveFileRead(string testArchive, ReaderOptions? readerOptions { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -272,12 +248,10 @@ protected void ArchiveFileRead(string testArchive, ReaderOptions? readerOptions #endif var expected = new Stack(fileOrder.Split(' ')); testArchive = Path.Combine(TEST_ARCHIVES_PATH, testArchive); - using (var archive = ArchiveFactory.Open(testArchive, readerOptions)) + using var archive = ArchiveFactory.Open(testArchive, readerOptions); + foreach (var entry in archive.Entries) { - foreach (var entry in archive.Entries) - { - Assert.Equal(expected.Pop(), entry.Key); - } + Assert.Equal(expected.Pop(), entry.Key); } } @@ -293,7 +267,7 @@ protected void ArchiveFileReadEx(string testArchive) { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() + new ExtractionOptions { ExtractFullPath = true, Overwrite = true, @@ -309,25 +283,25 @@ protected void ArchiveFileReadEx(string testArchive) protected void ArchiveDeltaDistanceRead(string testArchive) { testArchive = Path.Combine(TEST_ARCHIVES_PATH, testArchive); - using (var archive = Archives.ArchiveFactory.Open(testArchive, null)) - using (var reader = archive.ExtractAllEntries()) - while (reader.MoveToNextEntry()) + using var archive = ArchiveFactory.Open(testArchive); + using var reader = archive.ExtractAllEntries(); + while (reader.MoveToNextEntry()) + { + if (!reader.Entry.IsDirectory) { - if (!reader.Entry.IsDirectory) - { - var memory = new MemoryStream(); - reader.WriteEntryTo(memory); + var memory = new MemoryStream(); + reader.WriteEntryTo(memory); - memory.Position = 0; + memory.Position = 0; - for (int y = 0; y < 9; y++) - for (int x = 0; x < 256; x++) - { - Assert.Equal(x, memory.ReadByte()); - } - - Assert.Equal((int)-1, memory.ReadByte()); + for (var y = 0; y < 9; y++) + for (var x = 0; x < 256; x++) + { + Assert.Equal(x, memory.ReadByte()); } + + Assert.Equal(-1, memory.ReadByte()); } + } } } diff --git a/tests/SharpCompress.Test/Filters/BranchExecTests.cs b/tests/SharpCompress.Test/Filters/BranchExecTests.cs index 5c576dcc..ca9686a4 100644 --- a/tests/SharpCompress.Test/Filters/BranchExecTests.cs +++ b/tests/SharpCompress.Test/Filters/BranchExecTests.cs @@ -12,9 +12,8 @@ namespace SharpCompress.Test.Filters; public class BranchExecTests { - private static byte[] x86resultData { get; } = - new byte[] - { + private static byte[] X86ResultData { get; } = + [ 0x12, 0x00, 0x00, @@ -92,12 +91,11 @@ public class BranchExecTests 0x00, 0x00, 0x1C, - 0x00, - }; + 0x00 + ]; - private static byte[] x86Data { get; } = - new byte[] - { + private static byte[] X86Data { get; } = + [ 0x12, 0x00, 0x00, @@ -175,12 +173,11 @@ public class BranchExecTests 0x00, 0x00, 0x1C, - 0x00, - }; + 0x00 + ]; - private static byte[] ppcResultData { get; } = - new byte[] - { + private static byte[] PpcResultData { get; } = + [ 0xF8, 0x6B, 0x2E, @@ -277,11 +274,10 @@ public class BranchExecTests 0xB2, 0xD4, 0xED - }; + ]; - private static byte[] ppcData { get; } = - new byte[] - { + private static byte[] PpcData { get; } = + [ 0xF8, 0x6B, 0x2E, @@ -378,11 +374,10 @@ public class BranchExecTests 0xB2, 0xD4, 0xED - }; + ]; - private static byte[] armResultData { get; } = - new byte[] - { + private static byte[] ArmResultData { get; } = + [ 0x7C, 0xFC, 0x0A, @@ -479,11 +474,10 @@ public class BranchExecTests 0xC6, 0x8F, 0xE2 - }; + ]; - private static byte[] armData { get; } = - new byte[] - { + private static byte[] ArmData { get; } = + [ 0x7C, 0xFC, 0x0A, @@ -580,11 +574,10 @@ public class BranchExecTests 0xC6, 0x8F, 0xE2 - }; + ]; - private static byte[] armtResultData { get; } = - new byte[] - { + private static byte[] ArmtResultData { get; } = + [ 0x95, 0x23, 0xB6, @@ -697,11 +690,10 @@ public class BranchExecTests 0xED, 0x11, 0x0F - }; + ]; - private static byte[] armtData { get; } = - new byte[] - { + private static byte[] ArmtData { get; } = + [ 0x95, 0x23, 0xB6, @@ -814,11 +806,10 @@ public class BranchExecTests 0xED, 0x11, 0x0F - }; + ]; - private static byte[] ia64ResultData { get; } = - new byte[] - { + private static byte[] Ia64ResultData { get; } = + [ 0x4D, 0xF8, 0xF2, @@ -915,11 +906,10 @@ public class BranchExecTests 0x72, 0xD5, 0x0D - }; + ]; - private static byte[] ia64Data { get; } = - new byte[] - { + private static byte[] Ia64Data { get; } = + [ 0x4D, 0xF8, 0xF2, @@ -1016,11 +1006,10 @@ public class BranchExecTests 0x72, 0xD5, 0x0D - }; + ]; - private static byte[] sparcResultData { get; } = - new byte[] - { + private static byte[] SparcResultData { get; } = + [ 0x78, 0x2E, 0x73, @@ -1098,12 +1087,11 @@ public class BranchExecTests 0x91, 0x00, 0x10, - 0x00, - }; + 0x00 + ]; - private static byte[] sparcData { get; } = - new byte[] - { + private static byte[] SparcData { get; } = + [ 0x78, 0x2E, 0x73, @@ -1181,8 +1169,8 @@ public class BranchExecTests 0x91, 0x00, 0x10, - 0x00, - }; + 0x00 + ]; private void CompareBuffer(byte[] testBuffer, byte[] targetBuffer) => Assert.Equal(testBuffer, targetBuffer); @@ -1192,53 +1180,53 @@ public void X86ConverterDecodeTest() { uint state = 0; uint ip = 0x2000; - var testData = x86Data; + var testData = X86Data; BranchExecFilter.X86Converter(testData, ip, ref state); - CompareBuffer(testData, x86resultData); + CompareBuffer(testData, X86ResultData); } [Fact] - public void PowerPCConverterDecodeTest() + public void PowerPcConverterDecodeTest() { uint ip = 0x6A0; - var testData = ppcData; + var testData = PpcData; BranchExecFilter.PowerPCConverter(testData, ip); - CompareBuffer(testData, ppcResultData); + CompareBuffer(testData, PpcResultData); } [Fact] - public void ARMConverteDecoderTest() + public void ArmConverteDecoderTest() { uint ip = 0x3C00; - var testData = armData; + var testData = ArmData; BranchExecFilter.ARMConverter(testData, ip); - CompareBuffer(testData, armResultData); + CompareBuffer(testData, ArmResultData); } [Fact] - public void ARMTConverterDecodeTest() + public void ArmtConverterDecodeTest() { uint ip = 0xA00; - var testData = armtData; + var testData = ArmtData; BranchExecFilter.ARMTConverter(testData, ip); - CompareBuffer(testData, armtResultData); + CompareBuffer(testData, ArmtResultData); } [Fact] - public void IA64ConverterDecodeTest() + public void Ia64ConverterDecodeTest() { uint ip = 0xAA0; - var testData = ia64Data; + var testData = Ia64Data; BranchExecFilter.IA64Converter(testData, ip); - CompareBuffer(testData, ia64ResultData); + CompareBuffer(testData, Ia64ResultData); } [Fact] - public void SPARCConverterDecodeTest() + public void SparcConverterDecodeTest() { uint ip = 0x100; - var testData = sparcData; + var testData = SparcData; BranchExecFilter.SPARCConverter(testData, ip); - CompareBuffer(testData, sparcResultData); + CompareBuffer(testData, SparcResultData); } } diff --git a/tests/SharpCompress.Test/GZip/GZipArchiveTests.cs b/tests/SharpCompress.Test/GZip/GZipArchiveTests.cs index e47c339c..5b497d9f 100644 --- a/tests/SharpCompress.Test/GZip/GZipArchiveTests.cs +++ b/tests/SharpCompress.Test/GZip/GZipArchiveTests.cs @@ -3,6 +3,7 @@ using System.Linq; using SharpCompress.Archives; using SharpCompress.Archives.GZip; +using SharpCompress.Archives.Tar; using Xunit; namespace SharpCompress.Test.GZip; @@ -92,7 +93,7 @@ public void GZip_Archive_Multiple_Reads() Assert.Equal(size, tarStream.Length); using (var entryStream = archiveEntry.OpenEntryStream()) { - var result = Archives.Tar.TarArchive.IsTarFile(entryStream); + var result = TarArchive.IsTarFile(entryStream); } Assert.Equal(size, tarStream.Length); using (var entryStream = archiveEntry.OpenEntryStream()) diff --git a/tests/SharpCompress.Test/GZip/GZipReaderTests.cs b/tests/SharpCompress.Test/GZip/GZipReaderTests.cs index b5a3d501..9d475fd5 100644 --- a/tests/SharpCompress.Test/GZip/GZipReaderTests.cs +++ b/tests/SharpCompress.Test/GZip/GZipReaderTests.cs @@ -1,6 +1,7 @@ using System.IO; using SharpCompress.Common; using SharpCompress.IO; +using SharpCompress.Readers.GZip; using Xunit; namespace SharpCompress.Test.GZip; @@ -17,7 +18,7 @@ public void GZip_Reader_Generic2() { //read only as GZip itme using Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar.gz")); - using var reader = Readers.GZip.GZipReader.Open(new RewindableStream(stream)); + using var reader = GZipReader.Open(new RewindableStream(stream)); while (reader.MoveToNextEntry()) // Crash here { Assert.NotEqual(0, reader.Entry.Size); diff --git a/tests/SharpCompress.Test/Mocks/FlushOnDisposeStream.cs b/tests/SharpCompress.Test/Mocks/FlushOnDisposeStream.cs index 062351a1..56cd0161 100644 --- a/tests/SharpCompress.Test/Mocks/FlushOnDisposeStream.cs +++ b/tests/SharpCompress.Test/Mocks/FlushOnDisposeStream.cs @@ -7,30 +7,26 @@ namespace SharpCompress.Test.Mocks; // CryptoStream doesn't always trigger the Flush, so this class is used instead // See https://referencesource.microsoft.com/#mscorlib/system/security/cryptography/cryptostream.cs,141 -public class FlushOnDisposeStream : Stream, IDisposable +public class FlushOnDisposeStream(Stream innerStream) : Stream { - private Stream inner; - - public FlushOnDisposeStream(Stream innerStream) => inner = innerStream; - - public override bool CanRead => inner.CanRead; + public override bool CanRead => innerStream.CanRead; public override bool CanSeek => false; public override bool CanWrite => false; - public override long Length => inner.Length; + public override long Length => innerStream.Length; public override long Position { - get => inner.Position; - set => inner.Position = value; + get => innerStream.Position; + set => innerStream.Position = value; } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) => - inner.Read(buffer, offset, count); + innerStream.Read(buffer, offset, count); public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); @@ -44,8 +40,8 @@ protected override void Dispose(bool disposing) { if (disposing) { - inner.Flush(); - inner.Close(); + innerStream.Flush(); + innerStream.Close(); } base.Dispose(disposing); diff --git a/tests/SharpCompress.Test/Mocks/ForwardOnlyStream.cs b/tests/SharpCompress.Test/Mocks/ForwardOnlyStream.cs index e18bd707..180b8416 100644 --- a/tests/SharpCompress.Test/Mocks/ForwardOnlyStream.cs +++ b/tests/SharpCompress.Test/Mocks/ForwardOnlyStream.cs @@ -3,14 +3,10 @@ namespace SharpCompress.Test.Mocks; -public class ForwardOnlyStream : Stream +public class ForwardOnlyStream(Stream stream) : Stream { - private readonly Stream stream; - public bool IsDisposed { get; private set; } - public ForwardOnlyStream(Stream stream) => this.stream = stream; - protected override void Dispose(bool disposing) { if (!IsDisposed) diff --git a/tests/SharpCompress.Test/Mocks/TestStream.cs b/tests/SharpCompress.Test/Mocks/TestStream.cs index 66923df3..da7d65cc 100644 --- a/tests/SharpCompress.Test/Mocks/TestStream.cs +++ b/tests/SharpCompress.Test/Mocks/TestStream.cs @@ -2,23 +2,13 @@ namespace SharpCompress.Test.Mocks; -public class TestStream : Stream +public class TestStream(Stream stream, bool read, bool write, bool seek) : Stream { - private readonly Stream stream; - public TestStream(Stream stream) : this(stream, stream.CanRead, stream.CanWrite, stream.CanSeek) { } public bool IsDisposed { get; private set; } - public TestStream(Stream stream, bool read, bool write, bool seek) - { - this.stream = stream; - CanRead = read; - CanWrite = write; - CanSeek = seek; - } - protected override void Dispose(bool disposing) { base.Dispose(disposing); @@ -26,11 +16,11 @@ protected override void Dispose(bool disposing) IsDisposed = true; } - public override bool CanRead { get; } + public override bool CanRead { get; } = read; - public override bool CanSeek { get; } + public override bool CanSeek { get; } = seek; - public override bool CanWrite { get; } + public override bool CanWrite { get; } = write; public override void Flush() => stream.Flush(); diff --git a/tests/SharpCompress.Test/Rar/RarArchiveTests.cs b/tests/SharpCompress.Test/Rar/RarArchiveTests.cs index 729b7425..373af692 100644 --- a/tests/SharpCompress.Test/Rar/RarArchiveTests.cs +++ b/tests/SharpCompress.Test/Rar/RarArchiveTests.cs @@ -68,7 +68,7 @@ private void ReadRarPassword(string testArchive, string? password) using ( var archive = RarArchive.Open( stream, - new ReaderOptions() { Password = password, LeaveStreamOpen = true } + new ReaderOptions { Password = password, LeaveStreamOpen = true } ) ) { @@ -79,7 +79,7 @@ private void ReadRarPassword(string testArchive, string? password) Assert.Equal(CompressionType.Rar, entry.CompressionType); entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -98,7 +98,7 @@ protected void ArchiveFileReadPassword(string archiveName, string password) using ( var archive = RarArchive.Open( Path.Combine(TEST_ARCHIVES_PATH, archiveName), - new ReaderOptions() { Password = password, LeaveStreamOpen = true } + new ReaderOptions { Password = password, LeaveStreamOpen = true } ) ) { @@ -106,7 +106,7 @@ protected void ArchiveFileReadPassword(string archiveName, string password) { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -137,7 +137,7 @@ private void DoRar_test_invalid_exttime_ArchiveStreamRead(string filename) { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -146,13 +146,13 @@ private void DoRar_test_invalid_exttime_ArchiveStreamRead(string filename) public void Rar_Jpg_ArchiveStreamRead() { using var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Rar.jpeg.jpg")); - using (var archive = RarArchive.Open(stream, new ReaderOptions() { LookForHeader = true })) + using (var archive = RarArchive.Open(stream, new ReaderOptions { LookForHeader = true })) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -175,7 +175,7 @@ private void DoRar_IsSolidArchiveCheck(string filename) { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -229,30 +229,28 @@ private void DoRar_IsSolidEntryStreamCheck(string filename) [Fact] public void Rar_Multi_ArchiveStreamRead() => DoRar_Multi_ArchiveStreamRead( - new[] - { + [ "Rar.multi.part01.rar", "Rar.multi.part02.rar", "Rar.multi.part03.rar", "Rar.multi.part04.rar", "Rar.multi.part05.rar", "Rar.multi.part06.rar" - }, + ], false ); [Fact] public void Rar5_Multi_ArchiveStreamRead() => DoRar_Multi_ArchiveStreamRead( - new[] - { + [ "Rar5.multi.part01.rar", "Rar5.multi.part02.rar", "Rar5.multi.part03.rar", "Rar5.multi.part04.rar", "Rar5.multi.part05.rar", "Rar5.multi.part06.rar" - }, + ], false ); @@ -266,7 +264,7 @@ private void DoRar_Multi_ArchiveStreamRead(string[] archives, bool isSolid) { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -274,15 +272,14 @@ private void DoRar_Multi_ArchiveStreamRead(string[] archives, bool isSolid) [Fact] public void Rar5_MultiSolid_ArchiveStreamRead() => DoRar_Multi_ArchiveStreamRead( - new[] - { + [ "Rar.multi.solid.part01.rar", "Rar.multi.solid.part02.rar", "Rar.multi.solid.part03.rar", "Rar.multi.solid.part04.rar", "Rar.multi.solid.part05.rar", "Rar.multi.solid.part06.rar" - }, + ], true ); @@ -320,7 +317,7 @@ public void Rar_Jpg_ArchiveFileRead() using ( var archive = RarArchive.Open( Path.Combine(TEST_ARCHIVES_PATH, "Rar.jpeg.jpg"), - new ReaderOptions() { LookForHeader = true } + new ReaderOptions { LookForHeader = true } ) ) { @@ -328,7 +325,7 @@ public void Rar_Jpg_ArchiveFileRead() { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -344,8 +341,7 @@ public void Rar_Jpg_ArchiveFileRead() [Fact] public void Rar2_Multi_ArchiveStreamRead() => DoRar_Multi_ArchiveStreamRead( - new[] - { + [ "Rar2.multi.rar", "Rar2.multi.r00", "Rar2.multi.r01", @@ -353,7 +349,7 @@ public void Rar_Jpg_ArchiveFileRead() "Rar2.multi.r03", "Rar2.multi.r04", "Rar2.multi.r05" - }, + ], false ); @@ -467,8 +463,7 @@ public void Rar5_ArchiveVersionTest() [Fact] public void Rar4_Multi_ArchiveStreamRead() => DoRar_Multi_ArchiveStreamRead( - new[] - { + [ "Rar4.multi.part01.rar", "Rar4.multi.part02.rar", "Rar4.multi.part03.rar", @@ -476,7 +471,7 @@ public void Rar5_ArchiveVersionTest() "Rar4.multi.part05.rar", "Rar4.multi.part06.rar", "Rar4.multi.part07.rar" - }, + ], false ); @@ -485,15 +480,14 @@ public void Rar5_ArchiveVersionTest() public void Rar4_Split_ArchiveStreamRead() => ArchiveStreamMultiRead( null, - new[] - { + [ "Rar4.split.001", "Rar4.split.002", "Rar4.split.003", "Rar4.split.004", "Rar4.split.005", "Rar4.split.006" - } + ] ); //will detect and load other files @@ -520,15 +514,14 @@ public void Rar5_ArchiveVersionTest() public void Rar4_Split_ArchiveStreamFirstFileRead() => ArchiveStreamMultiRead( null, - new[] - { - "Rar4.split.001", + [ + "Rar4.split.001" //"Rar4.split.002", //"Rar4.split.003", //"Rar4.split.004", //"Rar4.split.005", //"Rar4.split.006" - } + ] ); //open with ArchiveFactory.Open and stream @@ -561,12 +554,11 @@ public void Rar5_ArchiveVersionTest() [Fact] public void Rar4_Multi_ArchiveOpenEntryVolumeIndexTest() => ArchiveOpenEntryVolumeIndexTest( - new[] - { - new[] { 0, 1 }, //exe - Rar4.multi.part01.rar to Rar4.multi.part02.rar - new[] { 1, 5 }, //jpg - Rar4.multi.part02.rar to Rar4.multi.part06.rar - new[] { 5, 6 } //txt - Rar4.multi.part06.rar to Rar4.multi.part07.rar - }, + [ + [0, 1], //exe - Rar4.multi.part01.rar to Rar4.multi.part02.rar + [1, 5], //jpg - Rar4.multi.part02.rar to Rar4.multi.part06.rar + [5, 6] //txt - Rar4.multi.part06.rar to Rar4.multi.part07.rar + ], null, "Rar4.multi.part01.rar", "Rar4.multi.part02.rar", diff --git a/tests/SharpCompress.Test/Rar/RarHeaderFactoryTest.cs b/tests/SharpCompress.Test/Rar/RarHeaderFactoryTest.cs index f2b1913c..70015fcf 100644 --- a/tests/SharpCompress.Test/Rar/RarHeaderFactoryTest.cs +++ b/tests/SharpCompress.Test/Rar/RarHeaderFactoryTest.cs @@ -11,10 +11,10 @@ namespace SharpCompress.Test.Rar; /// public class RarHeaderFactoryTest : TestBase { - private readonly RarHeaderFactory rarHeaderFactory; + private readonly RarHeaderFactory _rarHeaderFactory; public RarHeaderFactoryTest() => - rarHeaderFactory = new RarHeaderFactory( + _rarHeaderFactory = new RarHeaderFactory( StreamingMode.Seekable, new ReaderOptions { LeaveStreamOpen = true } ); @@ -40,11 +40,11 @@ private void ReadEncryptedFlag(string testArchive, bool isEncrypted) FileMode.Open, FileAccess.Read ); - foreach (var header in rarHeaderFactory.ReadHeaders(stream)) + foreach (var header in _rarHeaderFactory.ReadHeaders(stream)) { if (header.HeaderType == HeaderType.Archive || header.HeaderType == HeaderType.Crypt) { - Assert.Equal(isEncrypted, rarHeaderFactory.IsEncrypted); + Assert.Equal(isEncrypted, _rarHeaderFactory.IsEncrypted); break; } } diff --git a/tests/SharpCompress.Test/Rar/RarReaderTests.cs b/tests/SharpCompress.Test/Rar/RarReaderTests.cs index 2690148c..e2b100f6 100644 --- a/tests/SharpCompress.Test/Rar/RarReaderTests.cs +++ b/tests/SharpCompress.Test/Rar/RarReaderTests.cs @@ -13,29 +13,27 @@ public class RarReaderTests : ReaderTests [Fact] public void Rar_Multi_Reader() => DoRar_Multi_Reader( - new[] - { + [ "Rar.multi.part01.rar", "Rar.multi.part02.rar", "Rar.multi.part03.rar", "Rar.multi.part04.rar", "Rar.multi.part05.rar", "Rar.multi.part06.rar" - } + ] ); [Fact] public void Rar5_Multi_Reader() => DoRar_Multi_Reader( - new[] - { + [ "Rar5.multi.part01.rar", "Rar5.multi.part02.rar", "Rar5.multi.part03.rar", "Rar5.multi.part04.rar", "Rar5.multi.part05.rar", "Rar5.multi.part06.rar" - } + ] ); private void DoRar_Multi_Reader(string[] archives) @@ -52,7 +50,7 @@ private void DoRar_Multi_Reader(string[] archives) { reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -62,15 +60,14 @@ private void DoRar_Multi_Reader(string[] archives) [Fact] public void Rar_Multi_Reader_Encrypted() => DoRar_Multi_Reader_Encrypted( - new[] - { + [ "Rar.EncryptedParts.part01.rar", "Rar.EncryptedParts.part02.rar", "Rar.EncryptedParts.part03.rar", "Rar.EncryptedParts.part04.rar", "Rar.EncryptedParts.part05.rar", "Rar.EncryptedParts.part06.rar" - } + ] ); private void DoRar_Multi_Reader_Encrypted(string[] archives) => @@ -81,7 +78,7 @@ private void DoRar_Multi_Reader(string[] archives) archives .Select(s => Path.Combine(TEST_ARCHIVES_PATH, s)) .Select(p => File.OpenRead(p)), - new ReaderOptions() { Password = "test" } + new ReaderOptions { Password = "test" } ) ) { @@ -89,7 +86,7 @@ private void DoRar_Multi_Reader(string[] archives) { reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -99,29 +96,27 @@ private void DoRar_Multi_Reader(string[] archives) [Fact] public void Rar_Multi_Reader_Delete_Files() => DoRar_Multi_Reader_Delete_Files( - new[] - { + [ "Rar.multi.part01.rar", "Rar.multi.part02.rar", "Rar.multi.part03.rar", "Rar.multi.part04.rar", "Rar.multi.part05.rar", "Rar.multi.part06.rar" - } + ] ); [Fact] public void Rar5_Multi_Reader_Delete_Files() => DoRar_Multi_Reader_Delete_Files( - new[] - { + [ "Rar5.multi.part01.rar", "Rar5.multi.part02.rar", "Rar5.multi.part03.rar", "Rar5.multi.part04.rar", "Rar5.multi.part05.rar", "Rar5.multi.part06.rar" - } + ] ); private void DoRar_Multi_Reader_Delete_Files(string[] archives) @@ -143,7 +138,7 @@ private void DoRar_Multi_Reader_Delete_Files(string[] archives) { reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -239,16 +234,14 @@ public void Rar_Reader_Audio_program() using ( var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Rar.Audio_program.rar")) ) - using ( - var reader = ReaderFactory.Open(stream, new ReaderOptions() { LookForHeader = true }) - ) + using (var reader = ReaderFactory.Open(stream, new ReaderOptions { LookForHeader = true })) { while (reader.MoveToNextEntry()) { Assert.Equal(CompressionType.Rar, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -262,14 +255,14 @@ public void Rar_Reader_Audio_program() public void Rar_Jpg_Reader() { using (var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Rar.jpeg.jpg"))) - using (var reader = RarReader.Open(stream, new ReaderOptions() { LookForHeader = true })) + using (var reader = RarReader.Open(stream, new ReaderOptions { LookForHeader = true })) { while (reader.MoveToNextEntry()) { Assert.Equal(CompressionType.Rar, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -297,7 +290,7 @@ public void Rar_Jpg_Reader() private void DoRar_Solid_Skip_Reader(string filename) { using var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, filename)); - using var reader = ReaderFactory.Open(stream, new ReaderOptions() { LookForHeader = true }); + using var reader = ReaderFactory.Open(stream, new ReaderOptions { LookForHeader = true }); while (reader.MoveToNextEntry()) { if (reader.Entry.Key.Contains("jpg")) @@ -305,7 +298,7 @@ private void DoRar_Solid_Skip_Reader(string filename) Assert.Equal(CompressionType.Rar, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -320,7 +313,7 @@ private void DoRar_Solid_Skip_Reader(string filename) private void DoRar_Reader_Skip(string filename) { using var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, filename)); - using var reader = ReaderFactory.Open(stream, new ReaderOptions() { LookForHeader = true }); + using var reader = ReaderFactory.Open(stream, new ReaderOptions { LookForHeader = true }); while (reader.MoveToNextEntry()) { if (reader.Entry.Key.Contains("jpg")) @@ -328,7 +321,7 @@ private void DoRar_Reader_Skip(string filename) Assert.Equal(CompressionType.Rar, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -348,19 +341,15 @@ public void Rar_NullReference() "Rar.EncryptedParts.part06.rar" }; - using ( - var reader = RarReader.Open( - archives - .Select(s => Path.Combine(TEST_ARCHIVES_PATH, s)) - .Select(p => File.OpenRead(p)), - new ReaderOptions() { Password = "test" } - ) - ) + using var reader = RarReader.Open( + archives + .Select(s => Path.Combine(TEST_ARCHIVES_PATH, s)) + .Select(p => File.OpenRead(p)), + new ReaderOptions { Password = "test" } + ); + while (reader.MoveToNextEntry()) { - while (reader.MoveToNextEntry()) - { - // - } + // } } @@ -370,7 +359,7 @@ public void Rar_NullReference() ); using var reader = ReaderFactory.Open( stream, - new ReaderOptions() { LookForHeader = true } + new ReaderOptions { LookForHeader = true } ); while (reader.MoveToNextEntry()) { diff --git a/tests/SharpCompress.Test/ReaderTests.cs b/tests/SharpCompress.Test/ReaderTests.cs index 00ad69e9..b62dd4d2 100644 --- a/tests/SharpCompress.Test/ReaderTests.cs +++ b/tests/SharpCompress.Test/ReaderTests.cs @@ -64,7 +64,7 @@ public void UseReader(IReader reader, CompressionType expectedCompression) Assert.Equal(expectedCompression, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -88,13 +88,11 @@ public void UseReader(IReader reader, CompressionType expectedCompression) testArchive = Path.Combine(TEST_ARCHIVES_PATH, testArchive); using var file = File.OpenRead(testArchive); using var forward = new ForwardOnlyStream(file); - using (var reader = ReaderFactory.Open(forward, options)) + using var reader = ReaderFactory.Open(forward, options); + while (reader.MoveToNextEntry()) { - while (reader.MoveToNextEntry()) - { - Assert.Equal(expectedCompression, reader.Entry.CompressionType); - Assert.Equal(expected.Pop(), reader.Entry.Key); - } + Assert.Equal(expectedCompression, reader.Entry.CompressionType); + Assert.Equal(expected.Pop(), reader.Entry.Key); } } } diff --git a/tests/SharpCompress.Test/SevenZip/SevenZipArchiveTests.cs b/tests/SharpCompress.Test/SevenZip/SevenZipArchiveTests.cs index 184559d1..226ba4d8 100644 --- a/tests/SharpCompress.Test/SevenZip/SevenZipArchiveTests.cs +++ b/tests/SharpCompress.Test/SevenZip/SevenZipArchiveTests.cs @@ -25,17 +25,17 @@ public class SevenZipArchiveTests : ArchiveTests [Fact] public void SevenZipArchive_LZMAAES_StreamRead() => - ArchiveStreamRead("7Zip.LZMA.Aes.7z", new ReaderOptions() { Password = "testpassword" }); + ArchiveStreamRead("7Zip.LZMA.Aes.7z", new ReaderOptions { Password = "testpassword" }); [Fact] public void SevenZipArchive_LZMAAES_PathRead() => - ArchiveFileRead("7Zip.LZMA.Aes.7z", new ReaderOptions() { Password = "testpassword" }); + ArchiveFileRead("7Zip.LZMA.Aes.7z", new ReaderOptions { Password = "testpassword" }); [Fact] public void SevenZipArchive_LZMAAES_NoPasswordExceptionTest() => Assert.Throws( typeof(CryptographicException), - () => ArchiveFileRead("7Zip.LZMA.Aes.7z", new ReaderOptions() { Password = null }) + () => ArchiveFileRead("7Zip.LZMA.Aes.7z", new ReaderOptions { Password = null }) ); //was failing with ArgumentNullException not CryptographicException like rar [Fact] diff --git a/tests/SharpCompress.Test/Streams/LzmaStreamTests.cs b/tests/SharpCompress.Test/Streams/LzmaStreamTests.cs index 2f336329..2eea6607 100644 --- a/tests/SharpCompress.Test/Streams/LzmaStreamTests.cs +++ b/tests/SharpCompress.Test/Streams/LzmaStreamTests.cs @@ -1,6 +1,5 @@ using System; using System.Buffers; -using System.Buffers.Binary; using System.IO; using SharpCompress.Compressors.LZMA; using Xunit; @@ -20,9 +19,8 @@ public void TestLzma2Decompress1Byte() Assert.Equal('X', decompressor.ReadByte()); } - private static byte[] lzmaData { get; } = - new byte[] - { + private static byte[] LzmaData { get; } = + [ 0x5D, 0x00, 0x20, @@ -177,14 +175,13 @@ public void TestLzma2Decompress1Byte() 0x76, 0x03, 0x90 - }; + ]; /// - /// The decoded data for . + /// The decoded data for . /// - private static byte[] lzmaResultData { get; } = - new byte[] - { + private static byte[] LzmaResultData { get; } = + [ 0x01, 0x00, 0xFD, @@ -513,12 +510,12 @@ public void TestLzma2Decompress1Byte() 0x00, 0x00, 0x00 - }; + ]; [Fact] public void TestLzmaBuffer() { - var input = new MemoryStream(lzmaData); + var input = new MemoryStream(LzmaData); using var output = new MemoryStream(); var properties = new byte[5]; input.Read(properties, 0, 5); @@ -531,19 +528,15 @@ public void TestLzmaBuffer() coder.SetDecoderProperties(properties); coder.Code(input, output, input.Length, fileLength, null); - Assert.Equal(output.ToArray(), lzmaResultData); + Assert.Equal(output.ToArray(), LzmaResultData); } [Fact] public void TestLzmaStreamEncodingWritesData() { - using MemoryStream inputStream = new MemoryStream(lzmaResultData); + using var inputStream = new MemoryStream(LzmaResultData); using MemoryStream outputStream = new(); - using LzmaStream lzmaStream = new LzmaStream( - LzmaEncoderProperties.Default, - false, - outputStream - ); + using var lzmaStream = new LzmaStream(LzmaEncoderProperties.Default, false, outputStream); inputStream.CopyTo(lzmaStream); lzmaStream.Close(); Assert.NotEqual(0, outputStream.Length); @@ -552,13 +545,9 @@ public void TestLzmaStreamEncodingWritesData() [Fact] public void TestLzmaEncodingAccuracy() { - var input = new MemoryStream(lzmaResultData); + var input = new MemoryStream(LzmaResultData); var compressed = new MemoryStream(); - LzmaStream lzmaEncodingStream = new LzmaStream( - LzmaEncoderProperties.Default, - false, - compressed - ); + var lzmaEncodingStream = new LzmaStream(LzmaEncoderProperties.Default, false, compressed); input.CopyTo(lzmaEncodingStream); lzmaEncodingStream.Close(); compressed.Position = 0; @@ -569,10 +558,10 @@ public void TestLzmaEncodingAccuracy() compressed, compressed.Length, output, - lzmaResultData.LongLength + LzmaResultData.LongLength ); - Assert.Equal(output.ToArray(), lzmaResultData); + Assert.Equal(output.ToArray(), LzmaResultData); } private static void DecompressLzmaStream( @@ -583,7 +572,7 @@ public void TestLzmaEncodingAccuracy() long decompressedSize ) { - LzmaStream lzmaStream = new LzmaStream( + var lzmaStream = new LzmaStream( properties, compressedStream, compressedSize, @@ -592,12 +581,12 @@ long decompressedSize false ); - byte[] buffer = ArrayPool.Shared.Rent(1024); + var buffer = ArrayPool.Shared.Rent(1024); long totalRead = 0; while (totalRead < decompressedSize) { - int toRead = (int)Math.Min(buffer.Length, decompressedSize - totalRead); - int read = lzmaStream.Read(buffer, 0, toRead); + var toRead = (int)Math.Min(buffer.Length, decompressedSize - totalRead); + var read = lzmaStream.Read(buffer, 0, toRead); if (read > 0) { decompressedStream.Write(buffer, 0, read); diff --git a/tests/SharpCompress.Test/Tar/TarArchiveTests.cs b/tests/SharpCompress.Test/Tar/TarArchiveTests.cs index f1eba627..1ee6b783 100644 --- a/tests/SharpCompress.Test/Tar/TarArchiveTests.cs +++ b/tests/SharpCompress.Test/Tar/TarArchiveTests.cs @@ -26,10 +26,10 @@ public class TarArchiveTests : ArchiveTests [Fact] public void Tar_FileName_Exactly_100_Characters() { - string archive = "Tar_FileName_Exactly_100_Characters.tar"; + var archive = "Tar_FileName_Exactly_100_Characters.tar"; // create the 100 char filename - string filename = + var filename = "filename_with_exactly_100_characters_______________________________________________________________X"; // Step 1: create a tar file containing a file with the test name @@ -37,7 +37,7 @@ public void Tar_FileName_Exactly_100_Characters() using (var writer = WriterFactory.Open(stream, ArchiveType.Tar, CompressionType.None)) using (Stream inputStream = new MemoryStream()) { - StreamWriter sw = new StreamWriter(inputStream); + var sw = new StreamWriter(inputStream); sw.Write("dummy filecontent"); sw.Flush(); @@ -46,7 +46,7 @@ public void Tar_FileName_Exactly_100_Characters() } // Step 2: check if the written tar file can be read correctly - string unmodified = Path.Combine(SCRATCH2_FILES_PATH, archive); + var unmodified = Path.Combine(SCRATCH2_FILES_PATH, archive); using (var archive2 = TarArchive.Open(unmodified)) { Assert.Equal(1, archive2.Entries.Count); @@ -65,29 +65,27 @@ public void Tar_FileName_Exactly_100_Characters() [Fact] public void Tar_NonUstarArchiveWithLongNameDoesNotSkipEntriesAfterTheLongOne() { - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "very long filename.tar"); - using (var archive = TarArchive.Open(unmodified)) - { - Assert.Equal(5, archive.Entries.Count); - Assert.Contains("very long filename/", archive.Entries.Select(entry => entry.Key)); - Assert.Contains( - "very long filename/very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename.jpg", - archive.Entries.Select(entry => entry.Key) - ); - Assert.Contains("z_file 1.txt", archive.Entries.Select(entry => entry.Key)); - Assert.Contains("z_file 2.txt", archive.Entries.Select(entry => entry.Key)); - Assert.Contains("z_file 3.txt", archive.Entries.Select(entry => entry.Key)); - } + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "very long filename.tar"); + using var archive = TarArchive.Open(unmodified); + Assert.Equal(5, archive.Entries.Count); + Assert.Contains("very long filename/", archive.Entries.Select(entry => entry.Key)); + Assert.Contains( + "very long filename/very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename.jpg", + archive.Entries.Select(entry => entry.Key) + ); + Assert.Contains("z_file 1.txt", archive.Entries.Select(entry => entry.Key)); + Assert.Contains("z_file 2.txt", archive.Entries.Select(entry => entry.Key)); + Assert.Contains("z_file 3.txt", archive.Entries.Select(entry => entry.Key)); } [Fact] public void Tar_VeryLongFilepathReadback() { - string archive = "Tar_VeryLongFilepathReadback.tar"; + var archive = "Tar_VeryLongFilepathReadback.tar"; // create a very long filename - string longFilename = ""; - for (int i = 0; i < 600; i = longFilename.Length) + var longFilename = ""; + for (var i = 0; i < 600; i = longFilename.Length) { longFilename += i.ToString("D10") + "-"; } @@ -99,7 +97,7 @@ public void Tar_VeryLongFilepathReadback() using (var writer = WriterFactory.Open(stream, ArchiveType.Tar, CompressionType.None)) using (Stream inputStream = new MemoryStream()) { - StreamWriter sw = new StreamWriter(inputStream); + var sw = new StreamWriter(inputStream); sw.Write("dummy filecontent"); sw.Flush(); @@ -108,7 +106,7 @@ public void Tar_VeryLongFilepathReadback() } // Step 2: check if the written tar file can be read correctly - string unmodified = Path.Combine(SCRATCH2_FILES_PATH, archive); + var unmodified = Path.Combine(SCRATCH2_FILES_PATH, archive); using (var archive2 = TarArchive.Open(unmodified)) { Assert.Equal(1, archive2.Entries.Count); @@ -127,39 +125,37 @@ public void Tar_VeryLongFilepathReadback() [Fact] public void Tar_UstarArchivePathReadLongName() { - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "ustar with long names.tar"); - using (var archive = TarArchive.Open(unmodified)) - { - Assert.Equal(6, archive.Entries.Count); - Assert.Contains("Directory/", archive.Entries.Select(entry => entry.Key)); - Assert.Contains( - "Directory/Some file with veeeeeeeeeery loooooooooong name", - archive.Entries.Select(entry => entry.Key) - ); - Assert.Contains( - "Directory/Directory with veeeeeeeeeery loooooooooong name/", - archive.Entries.Select(entry => entry.Key) - ); - Assert.Contains( - "Directory/Directory with veeeeeeeeeery loooooooooong name/Some file with veeeeeeeeeery loooooooooong name", - archive.Entries.Select(entry => entry.Key) - ); - Assert.Contains( - "Directory/Directory with veeeeeeeeeery loooooooooong name/Directory with veeeeeeeeeery loooooooooong name/", - archive.Entries.Select(entry => entry.Key) - ); - Assert.Contains( - "Directory/Directory with veeeeeeeeeery loooooooooong name/Directory with veeeeeeeeeery loooooooooong name/Some file with veeeeeeeeeery loooooooooong name", - archive.Entries.Select(entry => entry.Key) - ); - } + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "ustar with long names.tar"); + using var archive = TarArchive.Open(unmodified); + Assert.Equal(6, archive.Entries.Count); + Assert.Contains("Directory/", archive.Entries.Select(entry => entry.Key)); + Assert.Contains( + "Directory/Some file with veeeeeeeeeery loooooooooong name", + archive.Entries.Select(entry => entry.Key) + ); + Assert.Contains( + "Directory/Directory with veeeeeeeeeery loooooooooong name/", + archive.Entries.Select(entry => entry.Key) + ); + Assert.Contains( + "Directory/Directory with veeeeeeeeeery loooooooooong name/Some file with veeeeeeeeeery loooooooooong name", + archive.Entries.Select(entry => entry.Key) + ); + Assert.Contains( + "Directory/Directory with veeeeeeeeeery loooooooooong name/Directory with veeeeeeeeeery loooooooooong name/", + archive.Entries.Select(entry => entry.Key) + ); + Assert.Contains( + "Directory/Directory with veeeeeeeeeery loooooooooong name/Directory with veeeeeeeeeery loooooooooong name/Some file with veeeeeeeeeery loooooooooong name", + archive.Entries.Select(entry => entry.Key) + ); } [Fact] public void Tar_Create_New() { - string scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.tar"); - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar"); + var scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.tar"); + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar"); // var aropt = new Ar @@ -167,7 +163,7 @@ public void Tar_Create_New() { archive.AddAllFromDirectory(ORIGINAL_FILES_PATH); var twopt = new TarWriterOptions(CompressionType.None, true); - twopt.ArchiveEncoding = new ArchiveEncoding() { Default = Encoding.GetEncoding(866) }; + twopt.ArchiveEncoding = new ArchiveEncoding { Default = Encoding.GetEncoding(866) }; archive.SaveTo(scratchPath, twopt); } CompareArchivesByPath(unmodified, scratchPath); @@ -176,10 +172,10 @@ public void Tar_Create_New() [Fact] public void Tar_Random_Write_Add() { - string jpg = Path.Combine(ORIGINAL_FILES_PATH, "jpg", "test.jpg"); - string scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.mod.tar"); - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.mod.tar"); - string modified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar"); + var jpg = Path.Combine(ORIGINAL_FILES_PATH, "jpg", "test.jpg"); + var scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.mod.tar"); + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.mod.tar"); + var modified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar"); using (var archive = TarArchive.Open(unmodified)) { @@ -192,9 +188,9 @@ public void Tar_Random_Write_Add() [Fact] public void Tar_Random_Write_Remove() { - string scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.mod.tar"); - string modified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.mod.tar"); - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar"); + var scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.mod.tar"); + var modified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.mod.tar"); + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar"); using (var archive = TarArchive.Open(unmodified)) { @@ -210,23 +206,19 @@ public void Tar_Random_Write_Remove() [Fact] public void Tar_Containing_Rar_Archive() { - string archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.ContainsRar.tar"); - using (Stream stream = File.OpenRead(archiveFullPath)) - using (IArchive archive = ArchiveFactory.Open(stream)) - { - Assert.True(archive.Type == ArchiveType.Tar); - } + var archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.ContainsRar.tar"); + using Stream stream = File.OpenRead(archiveFullPath); + using var archive = ArchiveFactory.Open(stream); + Assert.True(archive.Type == ArchiveType.Tar); } [Fact] public void Tar_Empty_Archive() { - string archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.Empty.tar"); - using (Stream stream = File.OpenRead(archiveFullPath)) - using (IArchive archive = ArchiveFactory.Open(stream)) - { - Assert.True(archive.Type == ArchiveType.Tar); - } + var archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.Empty.tar"); + using Stream stream = File.OpenRead(archiveFullPath); + using var archive = ArchiveFactory.Open(stream); + Assert.True(archive.Type == ArchiveType.Tar); } [Theory] @@ -234,26 +226,24 @@ public void Tar_Empty_Archive() [InlineData(128)] public void Tar_Japanese_Name(int length) { - using (var mstm = new MemoryStream()) + using var mstm = new MemoryStream(); + var enc = new ArchiveEncoding { Default = Encoding.UTF8 }; + var twopt = new TarWriterOptions(CompressionType.None, true); + twopt.ArchiveEncoding = enc; + var fname = new string((char)0x3042, length); + using (var tw = new TarWriter(mstm, twopt)) + using (var input = new MemoryStream(new byte[32])) { - var enc = new ArchiveEncoding() { Default = Encoding.UTF8 }; - var twopt = new TarWriterOptions(CompressionType.None, true); - twopt.ArchiveEncoding = enc; - var fname = new string((char)0x3042, length); - using (var tw = new TarWriter(mstm, twopt)) - using (var input = new MemoryStream(new byte[32])) - { - tw.Write(fname, input, null); - } - using (var inputMemory = new MemoryStream(mstm.ToArray())) + tw.Write(fname, input, null); + } + using (var inputMemory = new MemoryStream(mstm.ToArray())) + { + var tropt = new ReaderOptions { ArchiveEncoding = enc }; + using (var tr = TarReader.Open(inputMemory, tropt)) { - var tropt = new ReaderOptions() { ArchiveEncoding = enc }; - using (var tr = TarReader.Open(inputMemory, tropt)) + while (tr.MoveToNextEntry()) { - while (tr.MoveToNextEntry()) - { - Assert.Equal(fname, tr.Entry.Key); - } + Assert.Equal(fname, tr.Entry.Key); } } } @@ -269,36 +259,32 @@ public void Tar_Read_One_At_A_Time() }; var testBytes = Encoding.UTF8.GetBytes("This is a test."); - using (var memoryStream = new MemoryStream()) + using var memoryStream = new MemoryStream(); + using (var tarWriter = new TarWriter(memoryStream, tarWriterOptions)) + using (var testFileStream = new MemoryStream(testBytes)) { - using (var tarWriter = new TarWriter(memoryStream, tarWriterOptions)) - using (var testFileStream = new MemoryStream(testBytes)) - { - tarWriter.Write("test1.txt", testFileStream); - testFileStream.Position = 0; - tarWriter.Write("test2.txt", testFileStream); - } + tarWriter.Write("test1.txt", testFileStream); + testFileStream.Position = 0; + tarWriter.Write("test2.txt", testFileStream); + } - memoryStream.Position = 0; + memoryStream.Position = 0; - var numberOfEntries = 0; + var numberOfEntries = 0; - using (var archiveFactory = TarArchive.Open(memoryStream)) + using (var archiveFactory = TarArchive.Open(memoryStream)) + { + foreach (var entry in archiveFactory.Entries) { - foreach (var entry in archiveFactory.Entries) - { - ++numberOfEntries; - - using (var tarEntryStream = entry.OpenEntryStream()) - using (var testFileStream = new MemoryStream()) - { - tarEntryStream.CopyTo(testFileStream); - Assert.Equal(testBytes.Length, testFileStream.Length); - } - } - } + ++numberOfEntries; - Assert.Equal(2, numberOfEntries); + using var tarEntryStream = entry.OpenEntryStream(); + using var testFileStream = new MemoryStream(); + tarEntryStream.CopyTo(testFileStream); + Assert.Equal(testBytes.Length, testFileStream.Length); + } } + + Assert.Equal(2, numberOfEntries); } } diff --git a/tests/SharpCompress.Test/Tar/TarReaderTests.cs b/tests/SharpCompress.Test/Tar/TarReaderTests.cs index e3a27296..56ea72ed 100644 --- a/tests/SharpCompress.Test/Tar/TarReaderTests.cs +++ b/tests/SharpCompress.Test/Tar/TarReaderTests.cs @@ -19,26 +19,22 @@ public class TarReaderTests : ReaderTests [Fact] public void Tar_Skip() { - using ( - Stream stream = new ForwardOnlyStream( - File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar")) - ) - ) - using (IReader reader = ReaderFactory.Open(stream)) + using Stream stream = new ForwardOnlyStream( + File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar")) + ); + using var reader = ReaderFactory.Open(stream); + var x = 0; + while (reader.MoveToNextEntry()) { - int x = 0; - while (reader.MoveToNextEntry()) + if (!reader.Entry.IsDirectory) { - if (!reader.Entry.IsDirectory) + x++; + if (x % 2 == 0) { - x++; - if (x % 2 == 0) - { - reader.WriteEntryToDirectory( - SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } - ); - } + reader.WriteEntryToDirectory( + SCRATCH_FILES_PATH, + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } + ); } } } @@ -70,24 +66,20 @@ public void Tar_BZip2_Entry_Stream() if (!reader.Entry.IsDirectory) { Assert.Equal(CompressionType.BZip2, reader.Entry.CompressionType); - using (var entryStream = reader.OpenEntryStream()) + using var entryStream = reader.OpenEntryStream(); + var file = Path.GetFileName(reader.Entry.Key); + var folder = + Path.GetDirectoryName(reader.Entry.Key) + ?? throw new ArgumentNullException(); + var destdir = Path.Combine(SCRATCH_FILES_PATH, folder); + if (!Directory.Exists(destdir)) { - string file = Path.GetFileName(reader.Entry.Key); - string folder = - Path.GetDirectoryName(reader.Entry.Key) - ?? throw new ArgumentNullException(); - string destdir = Path.Combine(SCRATCH_FILES_PATH, folder); - if (!Directory.Exists(destdir)) - { - Directory.CreateDirectory(destdir); - } - string destinationFileName = Path.Combine(destdir, file); - - using (FileStream fs = File.OpenWrite(destinationFileName)) - { - entryStream.TransferTo(fs); - } + Directory.CreateDirectory(destdir); } + var destinationFileName = Path.Combine(destdir, file); + + using var fs = File.OpenWrite(destinationFileName); + entryStream.TransferTo(fs); } } } @@ -130,79 +122,62 @@ public void Tar_LongNamesWithLongNameExtension() [Fact] public void Tar_BZip2_Skip_Entry_Stream() { - using (Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar.bz2"))) - using (var reader = TarReader.Open(stream)) + using Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar.bz2")); + using var reader = TarReader.Open(stream); + var names = new List(); + while (reader.MoveToNextEntry()) { - List names = new List(); - while (reader.MoveToNextEntry()) + if (!reader.Entry.IsDirectory) { - if (!reader.Entry.IsDirectory) - { - Assert.Equal(CompressionType.BZip2, reader.Entry.CompressionType); - using (var entryStream = reader.OpenEntryStream()) - { - entryStream.SkipEntry(); - names.Add(reader.Entry.Key); - } - } + Assert.Equal(CompressionType.BZip2, reader.Entry.CompressionType); + using var entryStream = reader.OpenEntryStream(); + entryStream.SkipEntry(); + names.Add(reader.Entry.Key); } - Assert.Equal(3, names.Count); } + Assert.Equal(3, names.Count); } [Fact] public void Tar_Containing_Rar_Reader() { - string archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.ContainsRar.tar"); - using (Stream stream = File.OpenRead(archiveFullPath)) - using (IReader reader = ReaderFactory.Open(stream)) - { - Assert.True(reader.ArchiveType == ArchiveType.Tar); - } + var archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.ContainsRar.tar"); + using Stream stream = File.OpenRead(archiveFullPath); + using var reader = ReaderFactory.Open(stream); + Assert.True(reader.ArchiveType == ArchiveType.Tar); } [Fact] public void Tar_With_TarGz_With_Flushed_EntryStream() { - string archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.ContainsTarGz.tar"); - using (Stream stream = File.OpenRead(archiveFullPath)) - using (IReader reader = ReaderFactory.Open(stream)) - { - Assert.True(reader.MoveToNextEntry()); - Assert.Equal("inner.tar.gz", reader.Entry.Key); - - using (var entryStream = reader.OpenEntryStream()) - { - using (FlushOnDisposeStream flushingStream = new FlushOnDisposeStream(entryStream)) - { - // Extract inner.tar.gz - using (var innerReader = ReaderFactory.Open(flushingStream)) - { - Assert.True(innerReader.MoveToNextEntry()); - Assert.Equal("test", innerReader.Entry.Key); - } - } - } - } + var archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.ContainsTarGz.tar"); + using Stream stream = File.OpenRead(archiveFullPath); + using var reader = ReaderFactory.Open(stream); + Assert.True(reader.MoveToNextEntry()); + Assert.Equal("inner.tar.gz", reader.Entry.Key); + + using var entryStream = reader.OpenEntryStream(); + using var flushingStream = new FlushOnDisposeStream(entryStream); + + // Extract inner.tar.gz + using var innerReader = ReaderFactory.Open(flushingStream); + Assert.True(innerReader.MoveToNextEntry()); + Assert.Equal("test", innerReader.Entry.Key); } [Fact] public void Tar_Broken_Stream() { - string archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar"); - using (Stream stream = File.OpenRead(archiveFullPath)) - using (IReader reader = ReaderFactory.Open(stream)) - { - var memoryStream = new MemoryStream(); - - Action action = () => reader.MoveToNextEntry(); - var exception = Record.Exception(action); - Assert.Null(exception); - reader.MoveToNextEntry(); - reader.WriteEntryTo(memoryStream); - stream.Close(); - Assert.Throws(action); - } + var archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar"); + using Stream stream = File.OpenRead(archiveFullPath); + using var reader = ReaderFactory.Open(stream); + var memoryStream = new MemoryStream(); + + Assert.True(reader.MoveToNextEntry()); + Assert.True(reader.MoveToNextEntry()); + reader.WriteEntryTo(memoryStream); + stream.Close(); + Assert.Throws(() => reader.MoveToNextEntry()); } #if !NETFRAMEWORK @@ -212,61 +187,55 @@ public void Tar_GZip_With_Symlink_Entries() var isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform( System.Runtime.InteropServices.OSPlatform.Windows ); - using ( - Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "TarWithSymlink.tar.gz")) - ) - using (var reader = TarReader.Open(stream)) + using Stream stream = File.OpenRead( + Path.Combine(TEST_ARCHIVES_PATH, "TarWithSymlink.tar.gz") + ); + using var reader = TarReader.Open(stream); + while (reader.MoveToNextEntry()) { - List names = new List(); - while (reader.MoveToNextEntry()) + if (reader.Entry.IsDirectory) { - if (reader.Entry.IsDirectory) + continue; + } + reader.WriteEntryToDirectory( + SCRATCH_FILES_PATH, + new ExtractionOptions { - continue; - } - reader.WriteEntryToDirectory( - SCRATCH_FILES_PATH, - new ExtractionOptions() + ExtractFullPath = true, + Overwrite = true, + WriteSymbolicLink = (sourcePath, targetPath) => { - ExtractFullPath = true, - Overwrite = true, - WriteSymbolicLink = (sourcePath, targetPath) => + if (!isWindows) { - if (!isWindows) + var link = new Mono.Unix.UnixSymbolicLinkInfo(sourcePath); + if (File.Exists(sourcePath)) { - var link = new Mono.Unix.UnixSymbolicLinkInfo(sourcePath); - if (File.Exists(sourcePath)) - { - link.Delete(); // equivalent to ln -s -f - } - link.CreateSymbolicLinkTo(targetPath); + link.Delete(); // equivalent to ln -s -f } + link.CreateSymbolicLinkTo(targetPath); } } - ); - if (!isWindows) + } + ); + if (!isWindows) + { + if (reader.Entry.LinkTarget != null) { - if (reader.Entry.LinkTarget != null) + var path = Path.Combine(SCRATCH_FILES_PATH, reader.Entry.Key); + var link = new Mono.Unix.UnixSymbolicLinkInfo(path); + if (link.HasContents) { - var path = System.IO.Path.Combine(SCRATCH_FILES_PATH, reader.Entry.Key); - var link = new Mono.Unix.UnixSymbolicLinkInfo(path); - if (link.HasContents) - { - // need to convert the link to an absolute path for comparison - var target = reader.Entry.LinkTarget; - var realTarget = System.IO.Path.GetFullPath( - System.IO.Path.Combine( - $"{System.IO.Path.GetDirectoryName(path)}", - target - ) - ); + // need to convert the link to an absolute path for comparison + var target = reader.Entry.LinkTarget; + var realTarget = Path.GetFullPath( + Path.Combine($"{Path.GetDirectoryName(path)}", target) + ); - Assert.Equal(realTarget, link.GetContents().ToString()); - } - else - { - Assert.True(false, "Symlink has no target"); - } + Assert.Equal(realTarget, link.GetContents().ToString()); + } + else + { + Assert.True(false, "Symlink has no target"); } } } diff --git a/tests/SharpCompress.Test/TestBase.cs b/tests/SharpCompress.Test/TestBase.cs index 3ad1fe79..ad39b2d7 100644 --- a/tests/SharpCompress.Test/TestBase.cs +++ b/tests/SharpCompress.Test/TestBase.cs @@ -10,15 +10,15 @@ namespace SharpCompress.Test; public class TestBase : IDisposable { - private string SOLUTION_BASE_PATH; - protected string TEST_ARCHIVES_PATH; - protected string ORIGINAL_FILES_PATH; - protected string MISC_TEST_FILES_PATH; - private string SCRATCH_BASE_PATH; - public string SCRATCH_FILES_PATH; - protected string SCRATCH2_FILES_PATH; - - public TestBase() + private readonly string SOLUTION_BASE_PATH; + protected readonly string TEST_ARCHIVES_PATH; + protected readonly string ORIGINAL_FILES_PATH; + protected readonly string MISC_TEST_FILES_PATH; + private readonly string SCRATCH_BASE_PATH; + protected readonly string SCRATCH_FILES_PATH; + protected readonly string SCRATCH2_FILES_PATH; + + protected TestBase() { var index = AppDomain.CurrentDomain.BaseDirectory.IndexOf( "SharpCompress.Test", @@ -110,14 +110,14 @@ protected void VerifyFilesByNameEx() Assert.True(extracted.Contains(orig.Key)); CompareFilesByPath(orig.Single(), extracted[orig.Key].Single()); - CompareFilesByTimeAndAttribut(orig.Single(), extracted[orig.Key].Single()); + CompareFilesByTimeAndAttribute(orig.Single(), extracted[orig.Key].Single()); } } /// /// Verifies the files by extension also check modified time and attributes. /// - protected void VerifyFilesByExtensionEx() + private void VerifyFilesByExtensionEx() { var extracted = Directory .EnumerateFiles(SCRATCH_FILES_PATH, "*.*", SearchOption.AllDirectories) @@ -133,7 +133,7 @@ protected void VerifyFilesByExtensionEx() Assert.True(extracted.Contains(orig.Key)); CompareFilesByPath(orig.Single(), extracted[orig.Key].Single()); - CompareFilesByTimeAndAttribut(orig.Single(), extracted[orig.Key].Single()); + CompareFilesByTimeAndAttribute(orig.Single(), extracted[orig.Key].Single()); } } @@ -194,7 +194,7 @@ protected void CompareFilesByPath(string file1, string file2) } } - protected void CompareFilesByTimeAndAttribut(string file1, string file2) + private void CompareFilesByTimeAndAttribute(string file1, string file2) { var fi1 = new FileInfo(file1); var fi2 = new FileInfo(file2); diff --git a/tests/SharpCompress.Test/WriterTests.cs b/tests/SharpCompress.Test/WriterTests.cs index 64ed6d2c..50695ef1 100644 --- a/tests/SharpCompress.Test/WriterTests.cs +++ b/tests/SharpCompress.Test/WriterTests.cs @@ -9,9 +9,9 @@ namespace SharpCompress.Test; public class WriterTests : TestBase { - private readonly ArchiveType type; + private readonly ArchiveType _type; - protected WriterTests(ArchiveType type) => this.type = type; + protected WriterTests(ArchiveType type) => _type = type; protected void Write( CompressionType compressionType, @@ -26,7 +26,7 @@ public class WriterTests : TestBase writerOptions.ArchiveEncoding.Default = encoding ?? Encoding.Default; - using var writer = WriterFactory.Open(stream, type, writerOptions); + using var writer = WriterFactory.Open(stream, _type, writerOptions); writer.WriteAll(ORIGINAL_FILES_PATH, "*", SearchOption.AllDirectories); } CompareArchivesByPath( @@ -43,7 +43,7 @@ public class WriterTests : TestBase using var reader = ReaderFactory.Open(NonDisposingStream.Create(stream), readerOptions); reader.WriteAllToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true } + new ExtractionOptions { ExtractFullPath = true } ); } VerifyFiles(); diff --git a/tests/SharpCompress.Test/Xz/Crc32Tests.cs b/tests/SharpCompress.Test/Xz/Crc32Tests.cs index 52b71078..eaa0b100 100644 --- a/tests/SharpCompress.Test/Xz/Crc32Tests.cs +++ b/tests/SharpCompress.Test/Xz/Crc32Tests.cs @@ -6,16 +6,16 @@ namespace SharpCompress.Test.Xz; public class Crc32Tests { - private const string SimpleString = @"The quick brown fox jumps over the lazy dog."; - private readonly byte[] SimpleBytes = Encoding.ASCII.GetBytes(SimpleString); - private const string SimpleString2 = + private const string SIMPLE_STRING = @"The quick brown fox jumps over the lazy dog."; + private readonly byte[] _simpleBytes = Encoding.ASCII.GetBytes(SIMPLE_STRING); + private const string SIMPLE_STRING2 = @"Life moves pretty fast. If you don't stop and look around once in a while, you could miss it."; - private readonly byte[] SimpleBytes2 = Encoding.ASCII.GetBytes(SimpleString2); + private readonly byte[] _simpleBytes2 = Encoding.ASCII.GetBytes(SIMPLE_STRING2); [Fact] public void ShortAsciiString() { - var actual = Crc32.Compute(SimpleBytes); + var actual = Crc32.Compute(_simpleBytes); Assert.Equal((uint)0x519025e9, actual); } @@ -23,7 +23,7 @@ public void ShortAsciiString() [Fact] public void ShortAsciiString2() { - var actual = Crc32.Compute(SimpleBytes2); + var actual = Crc32.Compute(_simpleBytes2); Assert.Equal((uint)0x6ee3ad88, actual); } diff --git a/tests/SharpCompress.Test/Xz/Crc64Tests.cs b/tests/SharpCompress.Test/Xz/Crc64Tests.cs index 79912e48..8cf71e1e 100644 --- a/tests/SharpCompress.Test/Xz/Crc64Tests.cs +++ b/tests/SharpCompress.Test/Xz/Crc64Tests.cs @@ -6,16 +6,16 @@ namespace SharpCompress.Test.Xz; public class Crc64Tests { - private const string SimpleString = @"The quick brown fox jumps over the lazy dog."; - private readonly byte[] SimpleBytes = Encoding.ASCII.GetBytes(SimpleString); - private const string SimpleString2 = + private const string SIMPLE_STRING = @"The quick brown fox jumps over the lazy dog."; + private readonly byte[] _simpleBytes = Encoding.ASCII.GetBytes(SIMPLE_STRING); + private const string SIMPLE_STRING2 = @"Life moves pretty fast. If you don't stop and look around once in a while, you could miss it."; - private readonly byte[] SimpleBytes2 = Encoding.ASCII.GetBytes(SimpleString2); + private readonly byte[] _simpleBytes2 = Encoding.ASCII.GetBytes(SIMPLE_STRING2); [Fact] public void ShortAsciiString() { - var actual = Crc64.Compute(SimpleBytes); + var actual = Crc64.Compute(_simpleBytes); Assert.Equal((ulong)0x7E210EB1B03E5A1D, actual); } @@ -23,7 +23,7 @@ public void ShortAsciiString() [Fact] public void ShortAsciiString2() { - var actual = Crc64.Compute(SimpleBytes2); + var actual = Crc64.Compute(_simpleBytes2); Assert.Equal((ulong)0x416B4150508661EE, actual); } diff --git a/tests/SharpCompress.Test/Xz/Filters/BCJTests.cs b/tests/SharpCompress.Test/Xz/Filters/BCJTests.cs index 427a7b98..bc16789d 100644 --- a/tests/SharpCompress.Test/Xz/Filters/BCJTests.cs +++ b/tests/SharpCompress.Test/Xz/Filters/BCJTests.cs @@ -9,56 +9,56 @@ namespace SharpCompress.Test.Xz.Filters; -public class BCJTests : XZTestsBase +public class BcjTests : XzTestsBase { - private readonly ArmFilter armFilter; - private readonly ArmThumbFilter armtFilter; - private readonly IA64Filter ia64Filter; - private readonly PowerPCFilter ppcFilter; - private readonly SparcFilter sparcFilter; - private readonly X86Filter x86Filter; - - public BCJTests() + private readonly ArmFilter _armFilter; + private readonly ArmThumbFilter _armtFilter; + private readonly IA64Filter _ia64Filter; + private readonly PowerPCFilter _ppcFilter; + private readonly SparcFilter _sparcFilter; + private readonly X86Filter _x86Filter; + + public BcjTests() { - armFilter = new ArmFilter(); - armtFilter = new ArmThumbFilter(); - ia64Filter = new IA64Filter(); - ppcFilter = new PowerPCFilter(); - sparcFilter = new SparcFilter(); - x86Filter = new X86Filter(); + _armFilter = new ArmFilter(); + _armtFilter = new ArmThumbFilter(); + _ia64Filter = new IA64Filter(); + _ppcFilter = new PowerPCFilter(); + _sparcFilter = new SparcFilter(); + _x86Filter = new X86Filter(); } [Fact] public void IsOnlyAllowedLast() { - Assert.False(armFilter.AllowAsLast); - Assert.True(armFilter.AllowAsNonLast); + Assert.False(_armFilter.AllowAsLast); + Assert.True(_armFilter.AllowAsNonLast); - Assert.False(armtFilter.AllowAsLast); - Assert.True(armtFilter.AllowAsNonLast); + Assert.False(_armtFilter.AllowAsLast); + Assert.True(_armtFilter.AllowAsNonLast); - Assert.False(ia64Filter.AllowAsLast); - Assert.True(ia64Filter.AllowAsNonLast); + Assert.False(_ia64Filter.AllowAsLast); + Assert.True(_ia64Filter.AllowAsNonLast); - Assert.False(ppcFilter.AllowAsLast); - Assert.True(ppcFilter.AllowAsNonLast); + Assert.False(_ppcFilter.AllowAsLast); + Assert.True(_ppcFilter.AllowAsNonLast); - Assert.False(sparcFilter.AllowAsLast); - Assert.True(sparcFilter.AllowAsNonLast); + Assert.False(_sparcFilter.AllowAsLast); + Assert.True(_sparcFilter.AllowAsNonLast); - Assert.False(x86Filter.AllowAsLast); - Assert.True(x86Filter.AllowAsNonLast); + Assert.False(_x86Filter.AllowAsLast); + Assert.True(_x86Filter.AllowAsNonLast); } [Fact] public void ChangesStreamSize() { - Assert.False(armFilter.ChangesDataSize); - Assert.False(armtFilter.ChangesDataSize); - Assert.False(ia64Filter.ChangesDataSize); - Assert.False(ppcFilter.ChangesDataSize); - Assert.False(sparcFilter.ChangesDataSize); - Assert.False(x86Filter.ChangesDataSize); + Assert.False(_armFilter.ChangesDataSize); + Assert.False(_armtFilter.ChangesDataSize); + Assert.False(_ia64Filter.ChangesDataSize); + Assert.False(_ppcFilter.ChangesDataSize); + Assert.False(_sparcFilter.ChangesDataSize); + Assert.False(_x86Filter.ChangesDataSize); } [Theory] @@ -67,22 +67,22 @@ public void ChangesStreamSize() public void OnlyAcceptsOneByte(byte[] bytes) { InvalidDataException ex; - ex = Assert.Throws(() => armFilter.Init(bytes)); + ex = Assert.Throws(() => _armFilter.Init(bytes)); Assert.Equal("ARM properties unexpected length", ex.Message); - ex = Assert.Throws(() => armtFilter.Init(bytes)); + ex = Assert.Throws(() => _armtFilter.Init(bytes)); Assert.Equal("ARM Thumb properties unexpected length", ex.Message); - ex = Assert.Throws(() => ia64Filter.Init(bytes)); + ex = Assert.Throws(() => _ia64Filter.Init(bytes)); Assert.Equal("IA64 properties unexpected length", ex.Message); - ex = Assert.Throws(() => ppcFilter.Init(bytes)); + ex = Assert.Throws(() => _ppcFilter.Init(bytes)); Assert.Equal("PPC properties unexpected length", ex.Message); - ex = Assert.Throws(() => sparcFilter.Init(bytes)); + ex = Assert.Throws(() => _sparcFilter.Init(bytes)); Assert.Equal("SPARC properties unexpected length", ex.Message); - ex = Assert.Throws(() => x86Filter.Init(bytes)); + ex = Assert.Throws(() => _x86Filter.Init(bytes)); Assert.Equal("X86 properties unexpected length", ex.Message); } } diff --git a/tests/SharpCompress.Test/Xz/Filters/Lzma2Tests.cs b/tests/SharpCompress.Test/Xz/Filters/Lzma2Tests.cs index ff5dd467..e77bc2f8 100644 --- a/tests/SharpCompress.Test/Xz/Filters/Lzma2Tests.cs +++ b/tests/SharpCompress.Test/Xz/Filters/Lzma2Tests.cs @@ -5,21 +5,21 @@ namespace SharpCompress.Test.Xz.Filters; -public class Lzma2Tests : XZTestsBase +public class Lzma2Tests : XzTestsBase { - private readonly Lzma2Filter filter; + private readonly Lzma2Filter _filter; - public Lzma2Tests() => filter = new Lzma2Filter(); + public Lzma2Tests() => _filter = new Lzma2Filter(); [Fact] public void IsOnlyAllowedLast() { - Assert.True(filter.AllowAsLast); - Assert.False(filter.AllowAsNonLast); + Assert.True(_filter.AllowAsLast); + Assert.False(_filter.AllowAsNonLast); } [Fact] - public void ChangesStreamSize() => Assert.True(filter.ChangesDataSize); + public void ChangesStreamSize() => Assert.True(_filter.ChangesDataSize); [Theory] [InlineData(0, (uint)4 * 1024)] @@ -31,18 +31,18 @@ public void IsOnlyAllowedLast() [InlineData(40, (uint)(1024 * 1024 * 1024 - 1) * 4 + 3)] public void CalculatesDictionarySize(byte inByte, uint dicSize) { - filter.Init(new[] { inByte }); - Assert.Equal(filter.DictionarySize, dicSize); + _filter.Init([inByte]); + Assert.Equal(_filter.DictionarySize, dicSize); } [Fact] public void CalculatesDictionarySizeError() { uint temp; - filter.Init(new byte[] { 41 }); + _filter.Init([41]); var ex = Assert.Throws(() => { - temp = filter.DictionarySize; + temp = _filter.DictionarySize; }); Assert.Equal("Dictionary size greater than UInt32.Max", ex.Message); } @@ -52,14 +52,14 @@ public void CalculatesDictionarySizeError() [InlineData(new byte[] { 0, 0 })] public void OnlyAcceptsOneByte(byte[] bytes) { - var ex = Assert.Throws(() => filter.Init(bytes)); + var ex = Assert.Throws(() => _filter.Init(bytes)); Assert.Equal("LZMA properties unexpected length", ex.Message); } [Fact] public void ReservedBytesThrow() { - var ex = Assert.Throws(() => filter.Init(new byte[] { 0xC0 })); + var ex = Assert.Throws(() => _filter.Init([0xC0])); Assert.Equal("Reserved bits used in LZMA properties", ex.Message); } } diff --git a/tests/SharpCompress.Test/Xz/XZBlockTests.cs b/tests/SharpCompress.Test/Xz/XZBlockTests.cs index 87e68d93..78873590 100644 --- a/tests/SharpCompress.Test/Xz/XZBlockTests.cs +++ b/tests/SharpCompress.Test/Xz/XZBlockTests.cs @@ -5,7 +5,7 @@ namespace SharpCompress.Test.Xz; -public class XZBlockTests : XZTestsBase +public class XzBlockTests : XzTestsBase { protected override void Rewind(Stream stream) => stream.Position = 12; @@ -28,10 +28,10 @@ public void OnFindIndexBlockThrow() { var bytes = new byte[] { 0 }; using Stream indexBlockStream = new MemoryStream(bytes); - var XZBlock = new XZBlock(indexBlockStream, CheckType.CRC64, 8); + var xzBlock = new XZBlock(indexBlockStream, CheckType.CRC64, 8); Assert.Throws(() => { - ReadBytes(XZBlock, 1); + ReadBytes(xzBlock, 1); }); } @@ -42,10 +42,10 @@ public void CrcIncorrectThrows() bytes[20]++; using Stream badCrcStream = new MemoryStream(bytes); Rewind(badCrcStream); - var XZBlock = new XZBlock(badCrcStream, CheckType.CRC64, 8); + var xzBlock = new XZBlock(badCrcStream, CheckType.CRC64, 8); var ex = Assert.Throws(() => { - ReadBytes(XZBlock, 1); + ReadBytes(xzBlock, 1); }); Assert.Equal("Block header corrupt", ex.Message); } @@ -53,24 +53,24 @@ public void CrcIncorrectThrows() [Fact] public void CanReadM() { - var XZBlock = new XZBlock(CompressedStream, CheckType.CRC64, 8); - Assert.Equal(Encoding.ASCII.GetBytes("M"), ReadBytes(XZBlock, 1)); + var xzBlock = new XZBlock(CompressedStream, CheckType.CRC64, 8); + Assert.Equal(Encoding.ASCII.GetBytes("M"), ReadBytes(xzBlock, 1)); } [Fact] public void CanReadMary() { - var XZBlock = new XZBlock(CompressedStream, CheckType.CRC64, 8); - Assert.Equal(Encoding.ASCII.GetBytes("M"), ReadBytes(XZBlock, 1)); - Assert.Equal(Encoding.ASCII.GetBytes("a"), ReadBytes(XZBlock, 1)); - Assert.Equal(Encoding.ASCII.GetBytes("ry"), ReadBytes(XZBlock, 2)); + var xzBlock = new XZBlock(CompressedStream, CheckType.CRC64, 8); + Assert.Equal(Encoding.ASCII.GetBytes("M"), ReadBytes(xzBlock, 1)); + Assert.Equal(Encoding.ASCII.GetBytes("a"), ReadBytes(xzBlock, 1)); + Assert.Equal(Encoding.ASCII.GetBytes("ry"), ReadBytes(xzBlock, 2)); } [Fact] public void CanReadPoemWithStreamReader() { - var XZBlock = new XZBlock(CompressedStream, CheckType.CRC64, 8); - var sr = new StreamReader(XZBlock); + var xzBlock = new XZBlock(CompressedStream, CheckType.CRC64, 8); + var sr = new StreamReader(xzBlock); Assert.Equal(sr.ReadToEnd(), Original); } @@ -78,8 +78,8 @@ public void CanReadPoemWithStreamReader() public void NoopWhenNoPadding() { // CompressedStream's only block has no padding. - var XZBlock = new XZBlock(CompressedStream, CheckType.CRC64, 8); - var sr = new StreamReader(XZBlock); + var xzBlock = new XZBlock(CompressedStream, CheckType.CRC64, 8); + var sr = new StreamReader(xzBlock); sr.ReadToEnd(); Assert.Equal(0L, CompressedStream.Position % 4L); } @@ -88,8 +88,8 @@ public void NoopWhenNoPadding() public void SkipsPaddingWhenPresent() { // CompressedIndexedStream's first block has 1-byte padding. - var XZBlock = new XZBlock(CompressedIndexedStream, CheckType.CRC64, 8); - var sr = new StreamReader(XZBlock); + var xzBlock = new XZBlock(CompressedIndexedStream, CheckType.CRC64, 8); + var sr = new StreamReader(xzBlock); sr.ReadToEnd(); Assert.Equal(0L, CompressedIndexedStream.Position % 4L); } diff --git a/tests/SharpCompress.Test/Xz/XZHeaderTests.cs b/tests/SharpCompress.Test/Xz/XZHeaderTests.cs index e187b47a..8815b7a9 100644 --- a/tests/SharpCompress.Test/Xz/XZHeaderTests.cs +++ b/tests/SharpCompress.Test/Xz/XZHeaderTests.cs @@ -4,23 +4,21 @@ namespace SharpCompress.Test.Xz; -public class XZHeaderTests : XZTestsBase +public class XzHeaderTests : XzTestsBase { [Fact] public void ChecksMagicNumber() { var bytes = (byte[])Compressed.Clone(); bytes[3]++; - using (Stream badMagicNumberStream = new MemoryStream(bytes)) + using Stream badMagicNumberStream = new MemoryStream(bytes); + var br = new BinaryReader(badMagicNumberStream); + var header = new XZHeader(br); + var ex = Assert.Throws(() => { - BinaryReader br = new BinaryReader(badMagicNumberStream); - var header = new XZHeader(br); - var ex = Assert.Throws(() => - { - header.Process(); - }); - Assert.Equal("Invalid XZ Stream", ex.Message); - } + header.Process(); + }); + Assert.Equal("Invalid XZ Stream", ex.Message); } [Fact] @@ -28,42 +26,38 @@ public void CorruptHeaderThrows() { var bytes = (byte[])Compressed.Clone(); bytes[8]++; - using (Stream badCrcStream = new MemoryStream(bytes)) + using Stream badCrcStream = new MemoryStream(bytes); + var br = new BinaryReader(badCrcStream); + var header = new XZHeader(br); + var ex = Assert.Throws(() => { - BinaryReader br = new BinaryReader(badCrcStream); - var header = new XZHeader(br); - var ex = Assert.Throws(() => - { - header.Process(); - }); - Assert.Equal("Stream header corrupt", ex.Message); - } + header.Process(); + }); + Assert.Equal("Stream header corrupt", ex.Message); } [Fact] public void BadVersionIfCrcOkButStreamFlagUnknown() { var bytes = (byte[])Compressed.Clone(); - byte[] streamFlags = { 0x00, 0xF4 }; - byte[] crc = Crc32.Compute(streamFlags).ToLittleEndianBytes(); + byte[] streamFlags = [0x00, 0xF4]; + var crc = Crc32.Compute(streamFlags).ToLittleEndianBytes(); streamFlags.CopyTo(bytes, 6); crc.CopyTo(bytes, 8); - using (Stream badFlagStream = new MemoryStream(bytes)) + using Stream badFlagStream = new MemoryStream(bytes); + var br = new BinaryReader(badFlagStream); + var header = new XZHeader(br); + var ex = Assert.Throws(() => { - BinaryReader br = new BinaryReader(badFlagStream); - var header = new XZHeader(br); - var ex = Assert.Throws(() => - { - header.Process(); - }); - Assert.Equal("Unknown XZ Stream Version", ex.Message); - } + header.Process(); + }); + Assert.Equal("Unknown XZ Stream Version", ex.Message); } [Fact] public void ProcessesBlockCheckType() { - BinaryReader br = new BinaryReader(CompressedStream); + var br = new BinaryReader(CompressedStream); var header = new XZHeader(br); header.Process(); Assert.Equal(CheckType.CRC64, header.BlockCheckType); @@ -72,7 +66,7 @@ public void ProcessesBlockCheckType() [Fact] public void CanCalculateBlockCheckSize() { - BinaryReader br = new BinaryReader(CompressedStream); + var br = new BinaryReader(CompressedStream); var header = new XZHeader(br); header.Process(); Assert.Equal(8, header.BlockCheckSize); diff --git a/tests/SharpCompress.Test/Xz/XZIndexTests.cs b/tests/SharpCompress.Test/Xz/XZIndexTests.cs index ccbf81b7..b00b9d1a 100644 --- a/tests/SharpCompress.Test/Xz/XZIndexTests.cs +++ b/tests/SharpCompress.Test/Xz/XZIndexTests.cs @@ -4,7 +4,7 @@ namespace SharpCompress.Test.Xz; -public class XZIndexTests : XZTestsBase +public class XzIndexTests : XzTestsBase { protected override void RewindEmpty(Stream stream) => stream.Position = 12; @@ -15,29 +15,25 @@ public class XZIndexTests : XZTestsBase [Fact] public void RecordsStreamStartOnInit() { - using (Stream badStream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 })) - { - BinaryReader br = new BinaryReader(badStream); - var index = new XZIndex(br, false); - Assert.Equal(0, index.StreamStartPosition); - } + using Stream badStream = new MemoryStream([1, 2, 3, 4, 5]); + var br = new BinaryReader(badStream); + var index = new XZIndex(br, false); + Assert.Equal(0, index.StreamStartPosition); } [Fact] public void ThrowsIfHasNoIndexMarker() { - using (Stream badStream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 })) - { - BinaryReader br = new BinaryReader(badStream); - var index = new XZIndex(br, false); - Assert.Throws(() => index.Process()); - } + using Stream badStream = new MemoryStream([1, 2, 3, 4, 5]); + var br = new BinaryReader(badStream); + var index = new XZIndex(br, false); + Assert.Throws(() => index.Process()); } [Fact] public void ReadsNoRecord() { - BinaryReader br = new BinaryReader(CompressedEmptyStream); + var br = new BinaryReader(CompressedEmptyStream); var index = new XZIndex(br, false); index.Process(); Assert.Equal((ulong)0, index.NumberOfRecords); @@ -46,7 +42,7 @@ public void ReadsNoRecord() [Fact] public void ReadsOneRecord() { - BinaryReader br = new BinaryReader(CompressedStream); + var br = new BinaryReader(CompressedStream); var index = new XZIndex(br, false); index.Process(); Assert.Equal((ulong)1, index.NumberOfRecords); @@ -55,7 +51,7 @@ public void ReadsOneRecord() [Fact] public void ReadsMultipleRecords() { - BinaryReader br = new BinaryReader(CompressedIndexedStream); + var br = new BinaryReader(CompressedIndexedStream); var index = new XZIndex(br, false); index.Process(); Assert.Equal((ulong)2, index.NumberOfRecords); @@ -64,7 +60,7 @@ public void ReadsMultipleRecords() [Fact] public void ReadsFirstRecord() { - BinaryReader br = new BinaryReader(CompressedStream); + var br = new BinaryReader(CompressedStream); var index = new XZIndex(br, false); index.Process(); Assert.Equal((ulong)OriginalBytes.Length, index.Records[0].UncompressedSize); @@ -74,31 +70,12 @@ public void ReadsFirstRecord() public void SkipsPadding() { // Index with 3-byte padding. - using ( - Stream badStream = new MemoryStream( - new byte[] - { - 0x00, - 0x01, - 0x10, - 0x80, - 0x01, - 0x00, - 0x00, - 0x00, - 0xB1, - 0x01, - 0xD9, - 0xC9, - 0xFF - } - ) - ) - { - BinaryReader br = new BinaryReader(badStream); - var index = new XZIndex(br, false); - index.Process(); - Assert.Equal(0L, badStream.Position % 4L); - } + using Stream badStream = new MemoryStream( + [0x00, 0x01, 0x10, 0x80, 0x01, 0x00, 0x00, 0x00, 0xB1, 0x01, 0xD9, 0xC9, 0xFF] + ); + var br = new BinaryReader(badStream); + var index = new XZIndex(br, false); + index.Process(); + Assert.Equal(0L, badStream.Position % 4L); } } diff --git a/tests/SharpCompress.Test/Xz/XZStreamTests.cs b/tests/SharpCompress.Test/Xz/XZStreamTests.cs index 1b5a9343..02c5020c 100644 --- a/tests/SharpCompress.Test/Xz/XZStreamTests.cs +++ b/tests/SharpCompress.Test/Xz/XZStreamTests.cs @@ -4,38 +4,32 @@ namespace SharpCompress.Test.Xz; -public class XZStreamTests : XZTestsBase +public class XzStreamTests : XzTestsBase { [Fact] public void CanReadEmptyStream() { - XZStream xz = new XZStream(CompressedEmptyStream); - using (var sr = new StreamReader(xz)) - { - string uncompressed = sr.ReadToEnd(); - Assert.Equal(OriginalEmpty, uncompressed); - } + var xz = new XZStream(CompressedEmptyStream); + using var sr = new StreamReader(xz); + var uncompressed = sr.ReadToEnd(); + Assert.Equal(OriginalEmpty, uncompressed); } [Fact] public void CanReadStream() { - XZStream xz = new XZStream(CompressedStream); - using (var sr = new StreamReader(xz)) - { - string uncompressed = sr.ReadToEnd(); - Assert.Equal(Original, uncompressed); - } + var xz = new XZStream(CompressedStream); + using var sr = new StreamReader(xz); + var uncompressed = sr.ReadToEnd(); + Assert.Equal(Original, uncompressed); } [Fact] public void CanReadIndexedStream() { - XZStream xz = new XZStream(CompressedIndexedStream); - using (var sr = new StreamReader(xz)) - { - string uncompressed = sr.ReadToEnd(); - Assert.Equal(OriginalIndexed, uncompressed); - } + var xz = new XZStream(CompressedIndexedStream); + using var sr = new StreamReader(xz); + var uncompressed = sr.ReadToEnd(); + Assert.Equal(OriginalIndexed, uncompressed); } } diff --git a/tests/SharpCompress.Test/Xz/XZTestsBase.cs b/tests/SharpCompress.Test/Xz/XZTestsBase.cs index 5a1b5cbb..a679934e 100644 --- a/tests/SharpCompress.Test/Xz/XZTestsBase.cs +++ b/tests/SharpCompress.Test/Xz/XZTestsBase.cs @@ -4,9 +4,9 @@ namespace SharpCompress.Test.Xz; -public abstract class XZTestsBase : IDisposable +public abstract class XzTestsBase : IDisposable { - public XZTestsBase() + public XzTestsBase() { RewindEmpty(CompressedEmptyStream); Rewind(CompressedStream); @@ -29,8 +29,7 @@ public void Dispose() protected Stream CompressedEmptyStream { get; } = new MemoryStream(CompressedEmpty); protected static byte[] CompressedEmpty { get; } = - new byte[] - { + [ 0xfd, 0x37, 0x7a, @@ -63,7 +62,7 @@ public void Dispose() 0x01, 0x59, 0x5a - }; + ]; protected static byte[] OriginalEmptyBytes => Encoding.ASCII.GetBytes(OriginalEmpty); @@ -72,8 +71,7 @@ public void Dispose() protected Stream CompressedStream { get; } = new MemoryStream(Compressed); protected static byte[] Compressed { get; } = - new byte[] - { + [ 0xfd, 0x37, 0x7a, @@ -454,7 +452,7 @@ public void Dispose() 0x04, 0x59, 0x5a - }; + ]; protected static byte[] OriginalBytes => Encoding.ASCII.GetBytes(Original); protected static string Original { get; } = @@ -481,8 +479,7 @@ public void Dispose() protected Stream CompressedIndexedStream { get; } = new MemoryStream(CompressedIndexed); protected static byte[] CompressedIndexed { get; } = - new byte[] - { + [ 0xfd, 0x37, 0x7a, @@ -1123,7 +1120,7 @@ public void Dispose() 0x01, 0x59, 0x5a - }; + ]; protected static byte[] OriginalIndexedBytes => Encoding.ASCII.GetBytes(OriginalIndexed); diff --git a/tests/SharpCompress.Test/Zip/Zip64Tests.cs b/tests/SharpCompress.Test/Zip/Zip64Tests.cs index 739867f7..a89b1128 100644 --- a/tests/SharpCompress.Test/Zip/Zip64Tests.cs +++ b/tests/SharpCompress.Test/Zip/Zip64Tests.cs @@ -3,6 +3,8 @@ using System.Linq; using SharpCompress.Archives; using SharpCompress.Common; +using SharpCompress.Common.Zip; +using SharpCompress.Compressors.Deflate; using SharpCompress.Readers; using SharpCompress.Readers.Zip; using SharpCompress.Test.Mocks; @@ -23,27 +25,27 @@ public Zip64Tests() [Trait("format", "zip64")] public void Zip64_Single_Large_File() => // One single file, requires zip64 - RunSingleTest(1, FOUR_GB_LIMIT, set_zip64: true, forward_only: false); + RunSingleTest(1, FOUR_GB_LIMIT, setZip64: true, forwardOnly: false); [Trait("format", "zip64")] public void Zip64_Two_Large_Files() => // One single file, requires zip64 - RunSingleTest(2, FOUR_GB_LIMIT, set_zip64: true, forward_only: false); + RunSingleTest(2, FOUR_GB_LIMIT, setZip64: true, forwardOnly: false); [Trait("format", "zip64")] public void Zip64_Two_Small_files() => // Multiple files, does not require zip64 - RunSingleTest(2, FOUR_GB_LIMIT / 2, set_zip64: false, forward_only: false); + RunSingleTest(2, FOUR_GB_LIMIT / 2, setZip64: false, forwardOnly: false); [Trait("format", "zip64")] public void Zip64_Two_Small_files_stream() => // Multiple files, does not require zip64, and works with streams - RunSingleTest(2, FOUR_GB_LIMIT / 2, set_zip64: false, forward_only: true); + RunSingleTest(2, FOUR_GB_LIMIT / 2, setZip64: false, forwardOnly: true); [Trait("format", "zip64")] public void Zip64_Two_Small_Files_Zip64() => // Multiple files, use zip64 even though it is not required - RunSingleTest(2, FOUR_GB_LIMIT / 2, set_zip64: true, forward_only: false); + RunSingleTest(2, FOUR_GB_LIMIT / 2, setZip64: true, forwardOnly: false); [Trait("format", "zip64")] public void Zip64_Single_Large_File_Fail() @@ -51,7 +53,7 @@ public void Zip64_Single_Large_File_Fail() try { // One single file, should fail - RunSingleTest(1, FOUR_GB_LIMIT, set_zip64: false, forward_only: false); + RunSingleTest(1, FOUR_GB_LIMIT, setZip64: false, forwardOnly: false); throw new InvalidOperationException("Test did not fail?"); } catch (NotSupportedException) { } @@ -63,7 +65,7 @@ public void Zip64_Single_Large_File_Zip64_Streaming_Fail() try { // One single file, should fail (fast) with zip64 - RunSingleTest(1, FOUR_GB_LIMIT, set_zip64: true, forward_only: true); + RunSingleTest(1, FOUR_GB_LIMIT, setZip64: true, forwardOnly: true); throw new InvalidOperationException("Test did not fail?"); } catch (NotSupportedException) { } @@ -75,7 +77,7 @@ public void Zip64_Single_Large_File_Streaming_Fail() try { // One single file, should fail once the write discovers the problem - RunSingleTest(1, FOUR_GB_LIMIT, set_zip64: false, forward_only: true); + RunSingleTest(1, FOUR_GB_LIMIT, setZip64: false, forwardOnly: true); throw new InvalidOperationException("Test did not fail?"); } catch (NotSupportedException) { } @@ -84,9 +86,9 @@ public void Zip64_Single_Large_File_Streaming_Fail() public void RunSingleTest( long files, long filesize, - bool set_zip64, - bool forward_only, - long write_chunk_size = 1024 * 1024, + bool setZip64, + bool forwardOnly, + long writeChunkSize = 1024 * 1024, string filename = "zip64-test.zip" ) { @@ -99,7 +101,7 @@ public void Zip64_Single_Large_File_Streaming_Fail() if (!File.Exists(filename)) { - CreateZipArchive(filename, files, filesize, write_chunk_size, set_zip64, forward_only); + CreateZipArchive(filename, files, filesize, writeChunkSize, setZip64, forwardOnly); } var resForward = ReadForwardOnly(filename); @@ -138,23 +140,20 @@ public void Zip64_Single_Large_File_Streaming_Fail() long files, long filesize, long chunksize, - bool set_zip64, - bool forward_only + bool setZip64, + bool forwardOnly ) { var data = new byte[chunksize]; // Use deflate for speed - var opts = new ZipWriterOptions(CompressionType.Deflate) { UseZip64 = set_zip64 }; + var opts = new ZipWriterOptions(CompressionType.Deflate) { UseZip64 = setZip64 }; // Use no compression to ensure we hit the limits (actually inflates a bit, but seems better than using method==Store) - var eo = new ZipWriterEntryOptions() - { - DeflateCompressionLevel = Compressors.Deflate.CompressionLevel.None - }; + var eo = new ZipWriterEntryOptions { DeflateCompressionLevel = CompressionLevel.None }; using var zip = File.OpenWrite(filename); - using var st = forward_only ? (Stream)new ForwardOnlyStream(zip) : zip; + using var st = forwardOnly ? (Stream)new ForwardOnlyStream(zip) : zip; using var zipWriter = (ZipWriter)WriterFactory.Open(st, ArchiveType.Zip, opts); for (var i = 0; i < files; i++) { @@ -173,9 +172,9 @@ bool forward_only { long count = 0; long size = 0; - Common.Zip.ZipEntry? prev = null; + ZipEntry? prev = null; using (var fs = File.OpenRead(filename)) - using (var rd = ZipReader.Open(fs, new ReaderOptions() { LookForHeader = false })) + using (var rd = ZipReader.Open(fs, new ReaderOptions { LookForHeader = false })) { while (rd.MoveToNextEntry()) { diff --git a/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs b/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs index 94012e74..1948b26a 100644 --- a/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs +++ b/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs @@ -186,9 +186,9 @@ public void Zip_Shrink_ArchiveStreamRead() [Fact] public void Zip_Random_Write_Remove() { - string scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Zip.deflate.mod.zip"); - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); - string modified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.mod.zip"); + var scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Zip.deflate.mod.zip"); + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); + var modified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.mod.zip"); using (var archive = ZipArchive.Open(unmodified)) { @@ -208,10 +208,10 @@ public void Zip_Random_Write_Remove() [Fact] public void Zip_Random_Write_Add() { - string jpg = Path.Combine(ORIGINAL_FILES_PATH, "jpg", "test.jpg"); - string scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Zip.deflate.mod.zip"); - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.mod.zip"); - string modified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.mod2.zip"); + var jpg = Path.Combine(ORIGINAL_FILES_PATH, "jpg", "test.jpg"); + var scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Zip.deflate.mod.zip"); + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.mod.zip"); + var modified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.mod2.zip"); using (var archive = ZipArchive.Open(unmodified)) { @@ -228,12 +228,12 @@ public void Zip_Random_Write_Add() [Fact] public void Zip_Save_Twice() { - string scratchPath1 = Path.Combine(SCRATCH_FILES_PATH, "a.zip"); - string scratchPath2 = Path.Combine(SCRATCH_FILES_PATH, "b.zip"); + var scratchPath1 = Path.Combine(SCRATCH_FILES_PATH, "a.zip"); + var scratchPath2 = Path.Combine(SCRATCH_FILES_PATH, "b.zip"); using (var arc = ZipArchive.Create()) { - string str = "test.txt"; + var str = "test.txt"; var source = new MemoryStream(Encoding.UTF8.GetBytes(str)); arc.AddEntry("test.txt", source, true, source.Length); arc.SaveTo(scratchPath1, CompressionType.Deflate); @@ -246,42 +246,36 @@ public void Zip_Save_Twice() [Fact] public void Zip_Removal_Poly() { - string scratchPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); + var scratchPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); - using (ZipArchive vfs = (ZipArchive)ArchiveFactory.Open(scratchPath)) - { - var e = vfs.Entries.First(v => + using var vfs = (ZipArchive)ArchiveFactory.Open(scratchPath); + var e = vfs.Entries.First(v => v.Key.EndsWith("jpg", StringComparison.OrdinalIgnoreCase)); + vfs.RemoveEntry(e); + Assert.Null( + vfs.Entries.FirstOrDefault(v => v.Key.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) - ); - vfs.RemoveEntry(e); - Assert.Null( - vfs.Entries.FirstOrDefault(v => - v.Key.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) - ) - ); - Assert.Null( - ((IArchive)vfs).Entries.FirstOrDefault(v => - v.Key.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) - ) - ); - } + ) + ); + Assert.Null( + ((IArchive)vfs).Entries.FirstOrDefault(v => + v.Key.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) + ) + ); } [Fact] public void Zip_Create_NoDups() { - using (var arc = ZipArchive.Create()) - { - arc.AddEntry("1.txt", new MemoryStream()); - Assert.Throws(() => arc.AddEntry("\\1.txt", new MemoryStream())); - } + using var arc = ZipArchive.Create(); + arc.AddEntry("1.txt", new MemoryStream()); + Assert.Throws(() => arc.AddEntry("\\1.txt", new MemoryStream())); } [Fact] public void Zip_Create_Same_Stream() { - string scratchPath1 = Path.Combine(SCRATCH_FILES_PATH, "a.zip"); - string scratchPath2 = Path.Combine(SCRATCH_FILES_PATH, "b.zip"); + var scratchPath1 = Path.Combine(SCRATCH_FILES_PATH, "a.zip"); + var scratchPath2 = Path.Combine(SCRATCH_FILES_PATH, "b.zip"); using (var arc = ZipArchive.Create()) { @@ -326,8 +320,8 @@ public void Zip_Create_New() } File.Copy(file, newFileName); } - string scratchPath = Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.noEmptyDirs.zip"); - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); + var scratchPath = Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.noEmptyDirs.zip"); + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); using (var archive = ZipArchive.Create()) { @@ -393,7 +387,7 @@ public void Zip_Create_New_Add_Remove() } File.Copy(file, newFileName); } - string scratchPath = Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.noEmptyDirs.zip"); + var scratchPath = Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.noEmptyDirs.zip"); using (var archive = ZipArchive.Create()) { @@ -418,7 +412,7 @@ public void Zip_Deflate_WinzipAES_Read() using ( var reader = ZipArchive.Open( Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.WinzipAES.zip"), - new ReaderOptions() { Password = "test" } + new ReaderOptions { Password = "test" } ) ) { @@ -426,7 +420,7 @@ public void Zip_Deflate_WinzipAES_Read() { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -436,40 +430,32 @@ public void Zip_Deflate_WinzipAES_Read() [Fact] public void Zip_Deflate_WinzipAES_MultiOpenEntryStream() { - using ( - var reader = ZipArchive.Open( - Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.WinzipAES2.zip"), - new ReaderOptions() { Password = "test" } - ) - ) + using var reader = ZipArchive.Open( + Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.WinzipAES2.zip"), + new ReaderOptions { Password = "test" } + ); + foreach (var entry in reader.Entries.Where(x => !x.IsDirectory)) { - foreach (var entry in reader.Entries.Where(x => !x.IsDirectory)) - { - var stream = entry.OpenEntryStream(); - Assert.NotNull(stream); - var ex = Record.Exception(() => stream = entry.OpenEntryStream()); - Assert.Null(ex); - } + var stream = entry.OpenEntryStream(); + Assert.NotNull(stream); + var ex = Record.Exception(() => stream = entry.OpenEntryStream()); + Assert.Null(ex); } } [Fact] public void Zip_Read_Volume_Comment() { - using ( - var reader = ZipArchive.Open( - Path.Combine(TEST_ARCHIVES_PATH, "Zip.zip64.zip"), - new ReaderOptions() { Password = "test" } - ) - ) - { - var isComplete = reader.IsComplete; - Assert.Equal(1, reader.Volumes.Count); + using var reader = ZipArchive.Open( + Path.Combine(TEST_ARCHIVES_PATH, "Zip.zip64.zip"), + new ReaderOptions { Password = "test" } + ); + var isComplete = reader.IsComplete; + Assert.Equal(1, reader.Volumes.Count); - string expectedComment = - "Encoding:utf-8 || Compression:Deflate levelDefault || Encrypt:None || ZIP64:Always\r\nCreated at 2017-Jan-23 14:10:43 || DotNetZip Tool v1.9.1.8\r\nTest zip64 archive"; - Assert.Equal(expectedComment, reader.Volumes.First().Comment); - } + var expectedComment = + "Encoding:utf-8 || Compression:Deflate levelDefault || Encrypt:None || ZIP64:Always\r\nCreated at 2017-Jan-23 14:10:43 || DotNetZip Tool v1.9.1.8\r\nTest zip64 archive"; + Assert.Equal(expectedComment, reader.Volumes.First().Comment); } [Fact] @@ -478,7 +464,7 @@ public void Zip_BZip2_Pkware_Read() using ( var reader = ZipArchive.Open( Path.Combine(TEST_ARCHIVES_PATH, "Zip.bzip2.pkware.zip"), - new ReaderOptions() { Password = "test" } + new ReaderOptions { Password = "test" } ) ) { @@ -486,7 +472,7 @@ public void Zip_BZip2_Pkware_Read() { entry.WriteToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -496,10 +482,10 @@ public void Zip_BZip2_Pkware_Read() [Fact] public void Zip_Random_Entry_Access() { - string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); + var unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); - ZipArchive a = ZipArchive.Open(unmodified); - int count = 0; + var a = ZipArchive.Open(unmodified); + var count = 0; foreach (var e in a.Entries) { count++; @@ -510,7 +496,7 @@ public void Zip_Random_Entry_Access() a.Dispose(); a = ZipArchive.Open(unmodified); - int count2 = 0; + var count2 = 0; foreach (var e in a.Entries) { @@ -526,7 +512,7 @@ public void Zip_Random_Entry_Access() } } - int count3 = 0; + var count3 = 0; foreach (var e in a.Entries) { count3++; @@ -538,29 +524,21 @@ public void Zip_Random_Entry_Access() [Fact] public void Zip_Deflate_PKWear_Multipy_Entry_Access() { - string zipFile = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.pkware.zip"); + var zipFile = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.pkware.zip"); - using (FileStream fileStream = File.Open(zipFile, FileMode.Open)) + using var fileStream = File.Open(zipFile, FileMode.Open); + using var archive = ArchiveFactory.Open( + fileStream, + new ReaderOptions { Password = "12345678" } + ); + var entries = archive.Entries.Where(entry => !entry.IsDirectory); + foreach (var entry in entries) { - using ( - IArchive archive = ArchiveFactory.Open( - fileStream, - new ReaderOptions { Password = "12345678" } - ) - ) + for (var i = 0; i < 100; i++) { - var entries = archive.Entries.Where(entry => !entry.IsDirectory); - foreach (IArchiveEntry entry in entries) - { - for (var i = 0; i < 100; i++) - { - using (var memoryStream = new MemoryStream()) - using (Stream entryStream = entry.OpenEntryStream()) - { - entryStream.CopyTo(memoryStream); - } - } - } + using var memoryStream = new MemoryStream(); + using var entryStream = entry.OpenEntryStream(); + entryStream.CopyTo(memoryStream); } } } @@ -571,19 +549,17 @@ public void Zip_Evil_Throws_Exception() //windows only because of the paths Skip.IfNot(Environment.OSVersion.Platform == PlatformID.Win32NT); - string zipFile = Path.Combine(TEST_ARCHIVES_PATH, "Zip.Evil.zip"); + var zipFile = Path.Combine(TEST_ARCHIVES_PATH, "Zip.Evil.zip"); Assert.ThrowsAny(() => { - using (var archive = ZipArchive.Open(zipFile)) + using var archive = ZipArchive.Open(zipFile); + foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { - foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) - { - entry.WriteToDirectory( - SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } - ); - } + entry.WriteToDirectory( + SCRATCH_FILES_PATH, + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } + ); } }); } @@ -598,9 +574,7 @@ public void TestSharpCompressWithEmptyStream() { MemoryStream stream = new NonSeekableMemoryStream(); - using ( - IWriter zipWriter = WriterFactory.Open(stream, ArchiveType.Zip, CompressionType.Deflate) - ) + using (var zipWriter = WriterFactory.Open(stream, ArchiveType.Zip, CompressionType.Deflate)) { zipWriter.Write("foo.txt", new MemoryStream(Array.Empty())); zipWriter.Write("foo2.txt", new MemoryStream(new byte[10])); @@ -613,16 +587,14 @@ public void TestSharpCompressWithEmptyStream() { foreach (var entry in zipArchive.Entries) { - using (var entryStream = entry.OpenEntryStream()) + using var entryStream = entry.OpenEntryStream(); + var tempStream = new MemoryStream(); + const int bufSize = 0x1000; + var buf = new byte[bufSize]; + var bytesRead = 0; + while ((bytesRead = entryStream.Read(buf, 0, bufSize)) > 0) { - MemoryStream tempStream = new MemoryStream(); - const int bufSize = 0x1000; - byte[] buf = new byte[bufSize]; - int bytesRead = 0; - while ((bytesRead = entryStream.Read(buf, 0, bufSize)) > 0) - { - tempStream.Write(buf, 0, bytesRead); - } + tempStream.Write(buf, 0, bytesRead); } } } @@ -631,119 +603,105 @@ public void TestSharpCompressWithEmptyStream() [Fact] public void Zip_BadLocalExtra_Read() { - string zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.badlocalextra.zip"); + var zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.badlocalextra.zip"); - using (ZipArchive za = ZipArchive.Open(zipPath)) + using var za = ZipArchive.Open(zipPath); + var ex = Record.Exception(() => { - var ex = Record.Exception(() => - { - var firstEntry = za.Entries.First(x => x.Key == "first.txt"); - var buffer = new byte[4096]; + var firstEntry = za.Entries.First(x => x.Key == "first.txt"); + var buffer = new byte[4096]; - using (var memoryStream = new MemoryStream()) - using (var firstStream = firstEntry.OpenEntryStream()) - { - firstStream.CopyTo(memoryStream); - Assert.Equal(199, memoryStream.Length); - } - }); + using var memoryStream = new MemoryStream(); + using var firstStream = firstEntry.OpenEntryStream(); + firstStream.CopyTo(memoryStream); + Assert.Equal(199, memoryStream.Length); + }); - Assert.Null(ex); - } + Assert.Null(ex); } [Fact] public void Zip_NoCompression_DataDescriptors_Read() { - string zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.none.datadescriptors.zip"); + var zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.none.datadescriptors.zip"); - using (ZipArchive za = ZipArchive.Open(zipPath)) - { - var firstEntry = za.Entries.First(x => x.Key == "first.txt"); - var buffer = new byte[4096]; + using var za = ZipArchive.Open(zipPath); + var firstEntry = za.Entries.First(x => x.Key == "first.txt"); + var buffer = new byte[4096]; - using (var memoryStream = new MemoryStream()) - using (var firstStream = firstEntry.OpenEntryStream()) - { - firstStream.CopyTo(memoryStream); - Assert.Equal(199, memoryStream.Length); - } + using (var memoryStream = new MemoryStream()) + using (var firstStream = firstEntry.OpenEntryStream()) + { + firstStream.CopyTo(memoryStream); + Assert.Equal(199, memoryStream.Length); + } - var len1 = 0; - var buffer1 = new byte[firstEntry.Size + 256]; + var len1 = 0; + var buffer1 = new byte[firstEntry.Size + 256]; - using (var firstStream = firstEntry.OpenEntryStream()) - { - len1 = firstStream.Read(buffer1, 0, buffer.Length); - } + using (var firstStream = firstEntry.OpenEntryStream()) + { + len1 = firstStream.Read(buffer1, 0, buffer.Length); + } - Assert.Equal(199, len1); + Assert.Equal(199, len1); #if !NETFRAMEWORK && !NETSTANDARD2_0 - var len2 = 0; - var buffer2 = new byte[firstEntry.Size + 256]; + var len2 = 0; + var buffer2 = new byte[firstEntry.Size + 256]; - using (var firstStream = firstEntry.OpenEntryStream()) - { - len2 = firstStream.Read(buffer2.AsSpan()); - } - Assert.Equal(len1, len2); - Assert.Equal(buffer1, buffer2); -#endif + using (var firstStream = firstEntry.OpenEntryStream()) + { + len2 = firstStream.Read(buffer2.AsSpan()); } + Assert.Equal(len1, len2); + Assert.Equal(buffer1, buffer2); +#endif } [Fact] public void Zip_LongComment_Read() { - string zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.LongComment.zip"); + var zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.LongComment.zip"); - using (ZipArchive za = ZipArchive.Open(zipPath)) - { - var count = za.Entries.Count; - Assert.Equal(1, count); - } + using var za = ZipArchive.Open(zipPath); + var count = za.Entries.Count; + Assert.Equal(1, count); } [Fact] public void Zip_Zip64_CompressedSizeExtraOnly_Read() { - string zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.zip64.compressedonly.zip"); + var zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.zip64.compressedonly.zip"); - using (ZipArchive za = ZipArchive.Open(zipPath)) - { - var firstEntry = za.Entries.First(x => x.Key == "test/test.txt"); + using var za = ZipArchive.Open(zipPath); + var firstEntry = za.Entries.First(x => x.Key == "test/test.txt"); - using (var memoryStream = new MemoryStream()) - using (var firstStream = firstEntry.OpenEntryStream()) - { - firstStream.CopyTo(memoryStream); - Assert.Equal(15, memoryStream.Length); - } - } + using var memoryStream = new MemoryStream(); + using var firstStream = firstEntry.OpenEntryStream(); + firstStream.CopyTo(memoryStream); + Assert.Equal(15, memoryStream.Length); } [Fact] public void Zip_Uncompressed_Read_All() { - string zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.uncompressed.zip"); - using (var stream = File.Open(zipPath, FileMode.Open, FileAccess.Read)) + var zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.uncompressed.zip"); + using var stream = File.Open(zipPath, FileMode.Open, FileAccess.Read); + var archive = ArchiveFactory.Open(stream); + var reader = archive.ExtractAllEntries(); + var entries = 0; + while (reader.MoveToNextEntry()) { - IArchive archive = ArchiveFactory.Open(stream); - IReader reader = archive.ExtractAllEntries(); - int entries = 0; - while (reader.MoveToNextEntry()) + using (var entryStream = reader.OpenEntryStream()) + using (var target = new MemoryStream()) { - using (var entryStream = reader.OpenEntryStream()) - using (var target = new MemoryStream()) - { - entryStream.CopyTo(target); - } - - entries++; + entryStream.CopyTo(target); } - Assert.Equal(4, entries); + + entries++; } + Assert.Equal(4, entries); } [Fact] @@ -758,19 +716,17 @@ public void Zip_Uncompressed_Skip_All() "DEADBEEF" }; var zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.uncompressed.zip"); - using (var stream = File.Open(zipPath, FileMode.Open, FileAccess.Read)) + using var stream = File.Open(zipPath, FileMode.Open, FileAccess.Read); + var archive = ArchiveFactory.Open(stream); + var reader = archive.ExtractAllEntries(); + var x = 0; + while (reader.MoveToNextEntry()) { - IArchive archive = ArchiveFactory.Open(stream); - IReader reader = archive.ExtractAllEntries(); - int x = 0; - while (reader.MoveToNextEntry()) - { - Assert.Equal(keys[x], reader.Entry.Key); - x++; - } - - Assert.Equal(4, x); + Assert.Equal(keys[x], reader.Entry.Key); + x++; } + + Assert.Equal(4, x); } [Fact] @@ -779,7 +735,7 @@ public void Zip_Forced_Ignores_UnicodePathExtra() var zipPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.UnicodePathExtra.zip"); using (var stream = File.Open(zipPath, FileMode.Open, FileAccess.Read)) { - IArchive archive = ArchiveFactory.Open( + var archive = ArchiveFactory.Open( stream, new ReaderOptions { @@ -789,13 +745,13 @@ public void Zip_Forced_Ignores_UnicodePathExtra() } } ); - IReader reader = archive.ExtractAllEntries(); + var reader = archive.ExtractAllEntries(); reader.MoveToNextEntry(); Assert.Equal("궖귛궖귙귪궖귗귪궖귙_wav.frq", reader.Entry.Key); } using (var stream = File.Open(zipPath, FileMode.Open, FileAccess.Read)) { - IArchive archive = ArchiveFactory.Open( + var archive = ArchiveFactory.Open( stream, new ReaderOptions { @@ -805,7 +761,7 @@ public void Zip_Forced_Ignores_UnicodePathExtra() } } ); - IReader reader = archive.ExtractAllEntries(); + var reader = archive.ExtractAllEntries(); reader.MoveToNextEntry(); Assert.Equal("きょきゅんきゃんきゅ_wav.frq", reader.Entry.Key); } diff --git a/tests/SharpCompress.Test/Zip/ZipReaderTests.cs b/tests/SharpCompress.Test/Zip/ZipReaderTests.cs index e5254c19..3296bcb0 100644 --- a/tests/SharpCompress.Test/Zip/ZipReaderTests.cs +++ b/tests/SharpCompress.Test/Zip/ZipReaderTests.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using SharpCompress.Archives; using SharpCompress.Common; using SharpCompress.IO; using SharpCompress.Readers; @@ -70,7 +71,7 @@ public void Zip_Deflate_Streamed_Skip() { reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -108,7 +109,7 @@ public void Zip_BZip2_PkwareEncryption_Read() using ( Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Zip.bzip2.pkware.zip")) ) - using (var reader = ZipReader.Open(stream, new ReaderOptions() { Password = "test" })) + using (var reader = ZipReader.Open(stream, new ReaderOptions { Password = "test" })) { while (reader.MoveToNextEntry()) { @@ -117,7 +118,7 @@ public void Zip_BZip2_PkwareEncryption_Read() Assert.Equal(CompressionType.BZip2, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -139,7 +140,7 @@ public void Zip_Reader_Disposal_Test() { reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -160,7 +161,7 @@ public void Zip_Reader_Disposal_Test2() { reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -176,7 +177,7 @@ public void Zip_Reader_Disposal_Test2() Path.Combine(TEST_ARCHIVES_PATH, "Zip.lzma.WinzipAES.zip") ) ) - using (var reader = ZipReader.Open(stream, new ReaderOptions() { Password = "test" })) + using (var reader = ZipReader.Open(stream, new ReaderOptions { Password = "test" })) { while (reader.MoveToNextEntry()) { @@ -185,7 +186,7 @@ public void Zip_Reader_Disposal_Test2() Assert.Equal(CompressionType.Unknown, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -201,7 +202,7 @@ public void Zip_Deflate_WinzipAES_Read() Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.WinzipAES.zip") ) ) - using (var reader = ZipReader.Open(stream, new ReaderOptions() { Password = "test" })) + using (var reader = ZipReader.Open(stream, new ReaderOptions { Password = "test" })) { while (reader.MoveToNextEntry()) { @@ -210,7 +211,7 @@ public void Zip_Deflate_WinzipAES_Read() Assert.Equal(CompressionType.Unknown, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); } } @@ -223,7 +224,7 @@ public void Zip_Deflate_ZipCrypto_Read() { var count = 0; using (Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "zipcrypto.zip"))) - using (var reader = ZipReader.Open(stream, new ReaderOptions() { Password = "test" })) + using (var reader = ZipReader.Open(stream, new ReaderOptions { Password = "test" })) { while (reader.MoveToNextEntry()) { @@ -232,7 +233,7 @@ public void Zip_Deflate_ZipCrypto_Read() Assert.Equal(CompressionType.None, reader.Entry.CompressionType); reader.WriteEntryToDirectory( SCRATCH_FILES_PATH, - new ExtractionOptions() { ExtractFullPath = true, Overwrite = true } + new ExtractionOptions { ExtractFullPath = true, Overwrite = true } ); count++; } @@ -364,7 +365,7 @@ public void Zip_Uncompressed_64bit() { var zipPath = Path.Combine(TEST_ARCHIVES_PATH, "64bitstream.zip.7z"); using var stream = File.Open(zipPath, FileMode.Open, FileAccess.Read); - var archive = Archives.ArchiveFactory.Open(stream); + var archive = ArchiveFactory.Open(stream); var reader = archive.ExtractAllEntries(); reader.MoveToNextEntry(); var zipReader = ZipReader.Open(reader.OpenEntryStream());