34 lines
1.5 KiB
C#
34 lines
1.5 KiB
C#
using Newtonsoft.Json;
|
|
using System.Diagnostics;
|
|
|
|
namespace MinecraftDiscordBot.Models;
|
|
|
|
[JsonConverter(typeof(Md5JsonConverter))]
|
|
[DebuggerDisplay($"{{{nameof(ToString)}(),nq}}")]
|
|
public class Md5Hash : IEquatable<Md5Hash?> {
|
|
private readonly byte[] _hash;
|
|
public Md5Hash(string hash) : this(Convert.FromHexString(hash)) { }
|
|
public Md5Hash(byte[] hash) {
|
|
if (hash is not { Length: 16 }) throw new ArgumentException("Invalid digest size!", nameof(hash));
|
|
_hash = hash;
|
|
}
|
|
public override bool Equals(object? obj) => Equals(obj as Md5Hash);
|
|
public bool Equals(Md5Hash? other) => other != null && _hash.SequenceEqual(other._hash);
|
|
public override int GetHashCode() {
|
|
var hashCode = new HashCode();
|
|
hashCode.AddBytes(_hash);
|
|
return hashCode.ToHashCode();
|
|
}
|
|
public override string ToString() => Convert.ToHexString(_hash);
|
|
|
|
public class Md5JsonConverter : JsonConverter<Md5Hash> {
|
|
public override Md5Hash? ReadJson(JsonReader reader, Type objectType, Md5Hash? existingValue, bool hasExistingValue, JsonSerializer serializer)
|
|
=> reader.Value is string { Length: 32 } value
|
|
? new(value)
|
|
: throw new JsonException($"Could not parse MD5 hash with token '{reader.Value}'");
|
|
public override void WriteJson(JsonWriter writer, Md5Hash? value, JsonSerializer serializer) {
|
|
if (value is null) writer.WriteNull();
|
|
else writer.WriteValue(value.ToString());
|
|
}
|
|
}
|
|
} |