wabbajack/Wabbajack.Common/Hash.cs

230 lines
7.2 KiB
C#
Raw Normal View History

using System;
2020-03-22 15:50:53 +00:00
using System.Collections.Generic;
using System.Data.HashFunction.xxHash;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
2020-04-26 13:37:57 +00:00
using Newtonsoft.Json;
2020-03-22 15:50:53 +00:00
using File = Alphaleonis.Win32.Filesystem.File;
using Path = Alphaleonis.Win32.Filesystem.Path;
namespace Wabbajack.Common
{
/// <summary>
/// Struct representing a xxHash64 value. It's a struct with a ulong in it, but wrapped so we don't confuse
/// it with other longs in the system.
/// </summary>
2020-04-26 13:37:57 +00:00
[JsonConverter(typeof(Utils.HashJsonConverter))]
2020-03-22 15:50:53 +00:00
public struct Hash
{
private readonly ulong _code;
public Hash(ulong code = 0)
{
_code = code;
}
2020-03-27 03:10:23 +00:00
public bool IsValid => _code != 0;
2020-03-22 15:50:53 +00:00
public override string ToString()
{
return BitConverter.GetBytes(_code).ToBase64();
}
public override bool Equals(object? obj)
{
if (obj is Hash h)
return h._code == _code;
return false;
}
public override int GetHashCode()
{
return (int)(_code >> 32) ^ (int)_code;
}
public static bool operator ==(Hash a, Hash b)
{
return a._code == b._code;
}
public static bool operator !=(Hash a, Hash b)
{
return !(a == b);
}
public static explicit operator ulong(Hash a)
{
return a._code;
}
public static explicit operator long(Hash a)
{
return BitConverter.ToInt64(BitConverter.GetBytes(a._code));
}
public string ToHex()
{
return BitConverter.GetBytes(_code).ToHex();
}
public string ToBase64()
{
return BitConverter.GetBytes(_code).ToBase64();
}
public static Hash FromBase64(string hash)
{
return new Hash(BitConverter.ToUInt64(hash.FromBase64()));
}
public static Hash Empty = new Hash();
public static Hash FromLong(in long argHash)
{
return new Hash(BitConverter.ToUInt64(BitConverter.GetBytes(argHash)));
}
2020-03-26 12:28:03 +00:00
public static Hash FromULong(in ulong argHash)
{
return new Hash(argHash);
}
2020-03-22 15:50:53 +00:00
public static Hash FromHex(string xxHashAsHex)
{
return new Hash(BitConverter.ToUInt64(xxHashAsHex.FromHex()));
}
}
public static partial class Utils
{
public static Hash ReadHash(this BinaryReader br)
{
return new Hash(br.ReadUInt64());
}
public static void Write(this BinaryWriter bw, Hash hash)
{
bw.Write((ulong)hash);
}
public static string StringSha256Hex(this string s)
{
var sha = new SHA256Managed();
using (var o = new CryptoStream(Stream.Null, sha, CryptoStreamMode.Write))
{
using var i = new MemoryStream(Encoding.UTF8.GetBytes(s));
i.CopyTo(o);
}
return sha.Hash.ToHex();
}
2020-03-23 12:57:18 +00:00
public static Hash FileHash(this AbsolutePath file, bool nullOnIoError = false)
2020-03-22 15:50:53 +00:00
{
try
{
2020-03-23 12:57:18 +00:00
using var fs = file.OpenRead();
2020-03-22 15:50:53 +00:00
var config = new xxHashConfig {HashSizeInBits = 64};
2020-03-23 12:57:18 +00:00
using var f = new StatusFileStream(fs, $"Hashing {(string)file.FileName}");
2020-03-22 15:50:53 +00:00
return new Hash(BitConverter.ToUInt64(xxHashFactory.Instance.Create(config).ComputeHash(f).Hash));
}
catch (IOException)
{
if (nullOnIoError) return Hash.Empty;
throw;
}
}
2020-04-09 12:46:33 +00:00
public static Hash xxHash(this byte[] data)
{
var hash = new xxHashConfig();
hash.HashSizeInBits = 64;
hash.Seed = 0x42;
using var fs = new MemoryStream(data);
var config = new xxHashConfig {HashSizeInBits = 64};
using var f = new StatusFileStream(fs, $"Hashing memory stream");
var value = xxHashFactory.Instance.Create(config).ComputeHash(f);
return Hash.FromULong(BitConverter.ToUInt64(value.Hash));
}
public static Hash xxHash(this Stream stream)
{
var hash = new xxHashConfig();
hash.HashSizeInBits = 64;
hash.Seed = 0x42;
var config = new xxHashConfig {HashSizeInBits = 64};
using var f = new StatusFileStream(stream, $"Hashing memory stream");
var value = xxHashFactory.Instance.Create(config).ComputeHash(f);
return Hash.FromULong(BitConverter.ToUInt64(value.Hash));
}
2020-03-23 12:57:18 +00:00
public static Hash FileHashCached(this AbsolutePath file, bool nullOnIoError = false)
2020-03-22 15:50:53 +00:00
{
if (TryGetHashCache(file, out var foundHash)) return foundHash;
var hash = file.FileHash(nullOnIoError);
if (hash != Hash.Empty)
WriteHashCache(file, hash);
return hash;
}
2020-03-23 12:57:18 +00:00
public static bool TryGetHashCache(AbsolutePath file, out Hash hash)
2020-03-22 15:50:53 +00:00
{
2020-03-25 12:47:25 +00:00
var hashFile = file.WithExtension(Consts.HashFileExtension);
2020-03-22 15:50:53 +00:00
hash = Hash.Empty;
2020-03-25 12:47:25 +00:00
if (!hashFile.IsFile) return false;
2020-03-22 15:50:53 +00:00
2020-03-25 12:47:25 +00:00
if (hashFile.Size != 20) return false;
2020-03-22 15:50:53 +00:00
2020-03-25 12:47:25 +00:00
using var fs = hashFile.OpenRead();
2020-03-22 15:50:53 +00:00
using var br = new BinaryReader(fs);
var version = br.ReadUInt32();
if (version != HashCacheVersion) return false;
var lastModified = br.ReadUInt64();
2020-03-23 12:57:18 +00:00
if (lastModified != file.LastModifiedUtc.AsUnixTime()) return false;
2020-03-22 15:50:53 +00:00
hash = new Hash(br.ReadUInt64());
return true;
}
private const uint HashCacheVersion = 0x01;
2020-03-23 12:57:18 +00:00
private static void WriteHashCache(AbsolutePath file, Hash hash)
2020-03-22 15:50:53 +00:00
{
2020-03-25 12:47:25 +00:00
using var fs = file.WithExtension(Consts.HashFileExtension).Create();
2020-03-22 15:50:53 +00:00
using var bw = new BinaryWriter(fs);
bw.Write(HashCacheVersion);
2020-03-23 12:57:18 +00:00
var lastModified = file.LastModifiedUtc.AsUnixTime();
2020-03-22 15:50:53 +00:00
bw.Write(lastModified);
bw.Write((ulong)hash);
}
2020-03-23 12:57:18 +00:00
public static async Task<Hash> FileHashCachedAsync(this AbsolutePath file, bool nullOnIOError = false)
2020-03-22 15:50:53 +00:00
{
if (TryGetHashCache(file, out var foundHash)) return foundHash;
var hash = await file.FileHashAsync(nullOnIOError);
if (hash != Hash.Empty)
WriteHashCache(file, hash);
return hash;
}
2020-03-23 12:57:18 +00:00
public static async Task<Hash> FileHashAsync(this AbsolutePath file, bool nullOnIOError = false)
2020-03-22 15:50:53 +00:00
{
try
{
2020-03-23 12:57:18 +00:00
await using var fs = file.OpenRead();
2020-03-22 15:50:53 +00:00
var config = new xxHashConfig {HashSizeInBits = 64};
var value = await xxHashFactory.Instance.Create(config).ComputeHashAsync(fs);
return new Hash(BitConverter.ToUInt64(value.Hash));
}
catch (IOException)
{
if (nullOnIOError) return Hash.Empty;
throw;
}
}
}
}