wabbajack/Wabbajack.DTOs/Texture/PHash.cs

72 lines
1.6 KiB
C#
Raw Normal View History

2021-06-16 05:16:25 +00:00
using System.Data;
using System.IO;
2021-09-27 12:42:46 +00:00
using Wabbajack.Hashing.xxHash64;
2021-06-16 05:16:25 +00:00
2021-09-27 12:42:46 +00:00
namespace Wabbajack.DTOs.Texture
2021-06-16 05:16:25 +00:00
{
public struct PHash
{
2021-09-27 12:42:46 +00:00
public const int SIZE = 40;
2021-06-16 21:07:16 +00:00
private readonly int _hash;
2021-06-16 05:16:25 +00:00
2021-06-17 23:09:03 +00:00
public byte[] Data { get; }
2021-09-27 12:42:46 +00:00
public PHash(byte[] data)
2021-06-16 05:16:25 +00:00
{
2021-06-17 23:09:03 +00:00
Data = data;
if (Data.Length != SIZE)
2021-06-16 05:16:25 +00:00
throw new DataException();
2021-09-27 12:42:46 +00:00
2021-06-16 21:07:16 +00:00
long h = 0;
2021-06-17 23:09:03 +00:00
h |= Data[0];
2021-06-16 21:07:16 +00:00
h <<= 8;
2021-06-17 23:09:03 +00:00
h |= Data[1];
2021-06-16 21:07:16 +00:00
h <<= 8;
2021-06-17 23:09:03 +00:00
h |= Data[2];
2021-06-16 21:07:16 +00:00
h <<= 8;
2021-06-17 23:09:03 +00:00
h |= Data[3];
2021-06-16 21:07:16 +00:00
h <<= 8;
_hash = (int)h;
2021-06-16 05:16:25 +00:00
}
public static PHash FromBase64(string base64)
{
var data = base64.FromBase64();
if (data.Length != SIZE)
throw new DataException();
return new PHash(data);
}
2021-09-27 12:42:46 +00:00
2021-06-16 05:16:25 +00:00
public static PHash Read(BinaryReader br)
{
2021-09-27 12:42:46 +00:00
return new PHash(br.ReadBytes(SIZE));
2021-06-16 05:16:25 +00:00
}
public void Write(BinaryWriter br)
{
2021-06-16 21:07:16 +00:00
if (_hash == 0)
br.Write(new byte[SIZE]);
2021-09-27 12:42:46 +00:00
else
2021-06-17 23:09:03 +00:00
br.Write(Data);
2021-06-16 05:16:25 +00:00
}
public override string ToString()
{
2021-06-17 23:09:03 +00:00
return Data.ToBase64();
2021-06-16 05:16:25 +00:00
}
public override int GetHashCode()
{
long h = 0;
2021-06-17 23:09:03 +00:00
h |= Data[0];
2021-06-16 05:16:25 +00:00
h <<= 8;
2021-06-17 23:09:03 +00:00
h |= Data[1];
2021-06-16 05:16:25 +00:00
h <<= 8;
2021-06-17 23:09:03 +00:00
h |= Data[2];
2021-06-16 05:16:25 +00:00
h <<= 8;
2021-06-17 23:09:03 +00:00
h |= Data[3];
2021-06-16 05:16:25 +00:00
h <<= 8;
return (int)h;
}
2021-06-17 23:09:03 +00:00
}
2021-09-27 12:42:46 +00:00
}