Skip to content

Commit

Permalink
Target .NET 8
Browse files Browse the repository at this point in the history
  • Loading branch information
xPaw committed Feb 14, 2024
1 parent 964c70e commit e8a863c
Show file tree
Hide file tree
Showing 11 changed files with 60 additions and 45 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/ValvePak/ValvePak.Benchmark/

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

Expand Down
13 changes: 13 additions & 0 deletions ValvePak/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,16 @@ indent_size = 4
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.cs]
# CA5351: Do Not Use Broken Cryptographic Algorithms - vpks use MD5
dotnet_diagnostic.CA5351.severity = none

# CA1819: Properties should not return arrays
dotnet_diagnostic.CA1819.severity = none

# CA1721: Property names should not match get methods
dotnet_diagnostic.CA1721.severity = none

# CA1002: Do not expose generic lists
dotnet_diagnostic.CA1002.severity = none
4 changes: 2 additions & 2 deletions ValvePak/ValvePak.Test/ValvePak.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="NUnit" Version="4.0.1" />
<PackageReference Include="NUnit.Analyzers" Version="3.10.0">
<PackageReference Include="NUnit.Analyzers" Version="4.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
3 changes: 1 addition & 2 deletions ValvePak/ValvePak.Test/WriteTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public void AddAndRemoveFiles()
package.AddFile("test2.txt", []);
package.AddFile("test3.txt", []);
package.AddFile("test4.txt", []);
#pragma warning disable NUnit2045 // Use Assert.Multiple

Assert.That(package.Entries.ContainsKey("txt"), Is.True);
Assert.That(package.Entries["txt"], Has.Count.EqualTo(4));
Assert.That(package.RemoveFile(package.FindEntry("test2.txt")), Is.True);
Expand All @@ -107,7 +107,6 @@ public void AddAndRemoveFiles()
Assert.That(package.RemoveFile(package.FindEntry("test3.txt")), Is.True);
Assert.That(package.RemoveFile(package.FindEntry("test1.txt")), Is.True);
Assert.That(package.Entries, Is.Empty);
#pragma warning restore NUnit2045
}

[Test]
Expand Down
2 changes: 1 addition & 1 deletion ValvePak/ValvePak/CaseInsensitivePackageEntryComparer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace SteamDatabase.ValvePak
{
class CaseInsensitivePackageEntryComparer(StringComparison comparison) : IComparer<PackageEntry>
sealed class CaseInsensitivePackageEntryComparer(StringComparison comparison) : IComparer<PackageEntry>
{
public StringComparison Comparison { get; } = comparison;

Expand Down
31 changes: 15 additions & 16 deletions ValvePak/ValvePak/Package.Read.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ public void Read(string filename)
/// <param name="input">The input <see cref="Stream"/> to read from.</param>
public void Read(Stream input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
ArgumentNullException.ThrowIfNull(input);

if (FileName == null)
{
Expand Down Expand Up @@ -96,11 +93,7 @@ public void Read(Stream input)
/// <param name="validateCrc">If true, CRC32 will be calculated and verified for read data.</param>
public void ReadEntry(PackageEntry entry, out byte[] output, bool validateCrc = true)
{
// TODO: Add overload to read into existing byte array (ArrayPool)
if (entry == null)
{
throw new ArgumentNullException(nameof(entry));
}
ArgumentNullException.ThrowIfNull(entry);

output = new byte[entry.TotalLength];

Expand All @@ -115,7 +108,10 @@ public void ReadEntry(PackageEntry entry, out byte[] output, bool validateCrc =
/// <param name="validateCrc">If true, CRC32 will be calculated and verified for read data.</param>
public void ReadEntry(PackageEntry entry, byte[] output, bool validateCrc = true)
{
var totalLength = (int)entry.TotalLength;
ArgumentNullException.ThrowIfNull(entry);
ArgumentNullException.ThrowIfNull(output);

var totalLength = (int)entry.TotalLength;

if (output.Length < totalLength)
{
Expand All @@ -129,11 +125,12 @@ public void ReadEntry(PackageEntry entry, byte[] output, bool validateCrc = true

if (entry.Length > 0)
{
Stream fs = null;
#pragma warning disable CA2000 // Dispose objects before losing scope
var fs = GetFileStream(entry.ArchiveIndex);
#pragma warning restore CA2000 // Stream is base reader stream when reading from non-split vpk, it should not be disposed

try
{
fs = GetFileStream(entry.ArchiveIndex);
fs.Seek(entry.Offset, SeekOrigin.Current);

int length = (int)entry.Length;
Expand All @@ -147,9 +144,9 @@ public void ReadEntry(PackageEntry entry, byte[] output, bool validateCrc = true
}
finally
{
if (entry.ArchiveIndex != 0x7FFF)
if (entry.ArchiveIndex != 0x7FFF)
{
fs?.Close();
fs.Dispose();
}
}
}
Expand Down Expand Up @@ -356,8 +353,10 @@ private Stream GetFileStream(ushort archiveIndex)
/// <param name="entry">Package entry.</param>
/// <returns>Stream for a given package entry contents.</returns>
public Stream GetMemoryMappedStreamIfPossible(PackageEntry entry)
{
if (entry.Length <= 4096 || entry.SmallData.Length > 0)
{
ArgumentNullException.ThrowIfNull(entry);

if (entry.Length <= 4096 || entry.SmallData.Length > 0)
{
ReadEntry(entry, out var output, false);
return new MemoryStream(output);
Expand Down
9 changes: 7 additions & 2 deletions ValvePak/ValvePak/Package.Save.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public partial class Package
/// <returns>Returns true if entry was removed, false otherwise.</returns>
public bool RemoveFile(PackageEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);

if (!Entries.TryGetValue(entry.TypeName, out var typeEntries))
{
return false;
Expand All @@ -40,6 +42,8 @@ public bool RemoveFile(PackageEntry entry)
/// <returns>The added entry.</returns>
public PackageEntry AddFile(string filePath, byte[] fileData)
{
ArgumentNullException.ThrowIfNull(filePath);

filePath = filePath.Replace(WindowsDirectorySeparator, DirectorySeparatorChar);

var lastSeparator = filePath.LastIndexOf(DirectorySeparatorChar);
Expand Down Expand Up @@ -116,6 +120,8 @@ public void Write(Stream stream)
throw new InvalidOperationException("This package was opened from a _dir.vpk, writing back is currently unsupported.");
}

ArgumentNullException.ThrowIfNull(stream);

if (!stream.CanSeek || !stream.CanRead)
{
throw new InvalidOperationException("Stream must be seekable and readable.");
Expand Down Expand Up @@ -240,7 +246,6 @@ public void Write(Stream stream)
// TODO: It is possible to transform these hashes while writing the file to remove seeking and stream reading
using var fileTreeMD5 = MD5.Create();
using var fullFileMD5 = MD5.Create();
using var hashesMD5 = MD5.Create();

stream.Read(buffer, 0, headerSize);
fullFileMD5.TransformBlock(buffer, 0, headerSize, null, 0);
Expand Down Expand Up @@ -276,7 +281,7 @@ public void Write(Stream stream)
fullFileMD5.TransformBlock(fileTreeMD5.Hash, 0, fileTreeMD5.Hash.Length, null, 0);

// File hashes hash
var fileHashesMD5 = hashesMD5.ComputeHash([]); // We did not write any file hashes
var fileHashesMD5 = MD5.HashData([]); // We did not write any file hashes
writer.Write(fileHashesMD5);

// Full file hash
Expand Down
26 changes: 13 additions & 13 deletions ValvePak/ValvePak/Package.Verify.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ namespace SteamDatabase.ValvePak
/// </summary>
public partial class Package : IDisposable
{
class SubStream : Stream
{
sealed class SubStream : Stream, IDisposable
{
#pragma warning disable CA2213 // Disposable fields should be disposed
private readonly Stream baseStream;
#pragma warning restore CA2213
private readonly long length;
private long position;
public SubStream(Stream baseStream, long offset, long length)
Expand Down Expand Up @@ -71,25 +73,24 @@ public void VerifyHashes()
throw new InvalidDataException("Only version 2 is supported.");
}

using var md5 = MD5.Create();
var subStream = new SubStream(Reader.BaseStream, HeaderSize, (int)TreeSize);
var hash = md5.ComputeHash(subStream);
using var subStream = new SubStream(Reader.BaseStream, HeaderSize, (int)TreeSize);
var hash = MD5.HashData(subStream);

if (!hash.SequenceEqual(TreeChecksum))
{
throw new InvalidDataException($"File tree checksum mismatch ({BitConverter.ToString(hash)} != expected {BitConverter.ToString(TreeChecksum)})");
}

subStream = new SubStream(Reader.BaseStream, FileSizeBeforeArchiveMD5Entries, (int)ArchiveMD5SectionSize);
hash = md5.ComputeHash(subStream);
using var subStream2 = new SubStream(Reader.BaseStream, FileSizeBeforeArchiveMD5Entries, (int)ArchiveMD5SectionSize);
hash = MD5.HashData(subStream2);

if (!hash.SequenceEqual(ArchiveMD5EntriesChecksum))
{
throw new InvalidDataException($"Archive MD5 entries checksum mismatch ({BitConverter.ToString(hash)} != expected {BitConverter.ToString(ArchiveMD5EntriesChecksum)})");
}

subStream = new SubStream(Reader.BaseStream, 0, FileSizeBeforeWholeFileHash);
hash = md5.ComputeHash(subStream);
using var subStream3 = new SubStream(Reader.BaseStream, 0, FileSizeBeforeWholeFileHash);
hash = MD5.HashData(subStream3);

if (!hash.SequenceEqual(WholeFileChecksum))
{
Expand All @@ -103,7 +104,6 @@ public void VerifyHashes()
/// <param name="progressReporter">If provided, will report a string with the current verification progress.</param>
public void VerifyChunkHashes(IProgress<string> progressReporter = null)
{
using var md5 = MD5.Create();
Stream stream = null;
var lastArchiveIndex = uint.MaxValue;

Expand Down Expand Up @@ -141,8 +141,8 @@ public void VerifyChunkHashes(IProgress<string> progressReporter = null)
stream.Seek(offset, SeekOrigin.Begin);
}

var subStream = new SubStream(stream, stream.Position + entry.Offset, entry.Length);
var hash = md5.ComputeHash(subStream);
using var subStream = new SubStream(stream, stream.Position + entry.Offset, entry.Length);
var hash = MD5.HashData(subStream);

if (!hash.SequenceEqual(entry.Checksum))
{
Expand Down Expand Up @@ -198,7 +198,7 @@ public bool IsSignatureValid()
using var rsa = RSA.Create();
rsa.ImportSubjectPublicKeyInfo(PublicKey, out _);

var subStream = new SubStream(Reader.BaseStream, 0, FileSizeBeforeSignature);
using var subStream = new SubStream(Reader.BaseStream, 0, FileSizeBeforeSignature);

return rsa.VerifyData(subStream, Signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
Expand Down
10 changes: 2 additions & 8 deletions ValvePak/ValvePak/Package.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,7 @@ protected virtual void Dispose(bool disposing)
/// <param name="fileName">Filename.</param>
public void SetFileName(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException(nameof(fileName));
}
ArgumentNullException.ThrowIfNull(fileName);

if (fileName.EndsWith(".vpk", StringComparison.OrdinalIgnoreCase))
{
Expand All @@ -170,10 +167,7 @@ public void SetFileName(string fileName)
/// <param name="filePath">Full path to the file to find.</param>
public PackageEntry FindEntry(string filePathStr)
{
if (filePathStr == null)
{
throw new ArgumentNullException(nameof(filePathStr));
}
ArgumentNullException.ThrowIfNull(filePathStr);

// Normalize path separators when reading the file list
var filePath = filePathStr.Replace(WindowsDirectorySeparator, DirectorySeparatorChar).AsSpan();
Expand Down
3 changes: 3 additions & 0 deletions ValvePak/ValvePak/PackageEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ public class PackageEntry
/// <summary>
/// Gets or sets file name of this entry.
/// </summary>
/// <remarks>
/// This does not contain <see cref="TypeName"/>.
/// </remarks>
public string FileName { get; set; }

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion ValvePak/ValvePak/ValvePak.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Product>Valve Pak Library</Product>
<Description>Fully fledged library to work with Valve's Pak (VPK) archives</Description>
Expand Down

0 comments on commit e8a863c

Please sign in to comment.