| | 1 | | namespace NLightning.Domain.Crypto.ValueObjects; |
| | 2 | |
|
| | 3 | | using Constants; |
| | 4 | | using Utils.Extensions; |
| | 5 | |
|
| | 6 | | public readonly struct Hash : IEquatable<Hash> |
| | 7 | | { |
| | 8 | | private readonly byte[] _value; |
| 36 | 9 | | public static Hash Empty => new(new byte[CryptoConstants.Sha256HashLen]); |
| | 10 | |
|
| | 11 | | public Hash(byte[] value) |
| | 12 | | { |
| 952 | 13 | | if (value.Length < CryptoConstants.Sha256HashLen) |
| 0 | 14 | | throw new ArgumentOutOfRangeException(nameof(value), value.Length, |
| 0 | 15 | | $"Hash must have {CryptoConstants.Sha256HashLen} bytes."); |
| | 16 | |
|
| 952 | 17 | | _value = value; |
| 952 | 18 | | } |
| | 19 | |
|
| 916 | 20 | | public static implicit operator Hash(byte[] bytes) => new(bytes); |
| 0 | 21 | | public static implicit operator byte[](Hash hash) => hash._value; |
| | 22 | |
|
| 132 | 23 | | public static implicit operator ReadOnlyMemory<byte>(Hash hash) => hash._value; |
| | 24 | |
|
| 0 | 25 | | public override string ToString() => Convert.ToHexString(_value).ToLowerInvariant(); |
| | 26 | |
|
| | 27 | | public bool Equals(Hash other) |
| | 28 | | { |
| | 29 | | // Handle null cases first |
| | 30 | | // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract |
| 0 | 31 | | if (_value is null && other._value is null) |
| 0 | 32 | | return true; |
| | 33 | |
|
| | 34 | | // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract |
| 0 | 35 | | if (_value is null || other._value is null) |
| 0 | 36 | | return false; |
| | 37 | |
|
| 0 | 38 | | return _value.SequenceEqual(other._value); |
| | 39 | | } |
| | 40 | |
|
| | 41 | | public override bool Equals(object? obj) |
| | 42 | | { |
| 0 | 43 | | if (obj is null) |
| 0 | 44 | | return false; |
| | 45 | |
|
| 0 | 46 | | return obj is Hash other && Equals(other); |
| | 47 | | } |
| | 48 | |
|
| | 49 | | public override int GetHashCode() |
| | 50 | | { |
| 0 | 51 | | return _value.GetByteArrayHashCode(); |
| | 52 | | } |
| | 53 | | } |