| | 1 | | namespace NLightning.Domain.ValueObjects; |
| | 2 | |
|
| | 3 | | using Interfaces; |
| | 4 | |
|
| | 5 | | /// <summary> |
| | 6 | | /// Represents a chain hash. |
| | 7 | | /// </summary> |
| | 8 | | /// <remarks> |
| | 9 | | /// A chain hash is a 32-byte hash used to identify a chain. |
| | 10 | | /// </remarks> |
| | 11 | | public readonly struct ChainHash : IValueObject, IEquatable<ChainHash> |
| | 12 | | { |
| | 13 | | /// <summary> |
| | 14 | | /// The length of a chain hash. |
| | 15 | | /// </summary> |
| | 16 | | public const int LENGTH = 32; |
| | 17 | |
|
| | 18 | | private readonly byte[] _value; |
| | 19 | |
|
| | 20 | | /// <summary> |
| | 21 | | /// Initializes a new instance of the <see cref="ChainHash"/> struct. |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="value">The value of the chain hash.</param> |
| | 24 | | /// <exception cref="ArgumentOutOfRangeException">Thrown when the value is not 32 bytes.</exception> |
| | 25 | | public ChainHash(ReadOnlySpan<byte> value) |
| | 26 | | { |
| 84 | 27 | | if (value.Length != 32) |
| | 28 | | { |
| 4 | 29 | | throw new ArgumentOutOfRangeException(nameof(value), "ChainHash must be 32 bytes"); |
| | 30 | | } |
| | 31 | |
|
| 80 | 32 | | _value = value.ToArray(); |
| 80 | 33 | | } |
| | 34 | |
|
| | 35 | | /// <summary> |
| | 36 | | /// Compares two chain hashes for equality. |
| | 37 | | /// </summary> |
| | 38 | | /// <param name="other">The chain hash to compare to.</param> |
| | 39 | | /// <returns>True if the chain hashes are equal, otherwise false.</returns> |
| | 40 | | public bool Equals(ChainHash other) |
| | 41 | | { |
| 64 | 42 | | return _value.SequenceEqual(other._value); |
| | 43 | | } |
| | 44 | |
|
| | 45 | | public override bool Equals(object? obj) |
| | 46 | | { |
| 0 | 47 | | if (obj is ChainHash other) |
| | 48 | | { |
| 0 | 49 | | return Equals(other); |
| | 50 | | } |
| | 51 | |
|
| 0 | 52 | | return false; |
| | 53 | | } |
| | 54 | |
|
| | 55 | | public override int GetHashCode() |
| | 56 | | { |
| 0 | 57 | | return BitConverter.ToInt32(_value, 0); |
| | 58 | | } |
| | 59 | |
|
| 72 | 60 | | public static implicit operator byte[](ChainHash c) => c._value; |
| 12 | 61 | | public static implicit operator ReadOnlyMemory<byte>(ChainHash c) => c._value; |
| 8 | 62 | | public static implicit operator ChainHash(byte[] value) => new(value); |
| | 63 | |
|
| | 64 | | public static bool operator ==(ChainHash left, ChainHash right) |
| | 65 | | { |
| 16 | 66 | | return left.Equals(right); |
| | 67 | | } |
| | 68 | |
|
| | 69 | | public static bool operator !=(ChainHash left, ChainHash right) |
| | 70 | | { |
| 8 | 71 | | return !(left == right); |
| | 72 | | } |
| | 73 | | } |