/
Nonce.cs
89 lines (80 loc) · 3.14 KB
/
Nonce.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
namespace Libplanet
{
/// <summary>
/// An arbitrary <see cref="byte"/>s that determines a
/// <see cref="Hashcash.Stamp"/>.
/// </summary>
[Equals]
public struct Nonce
{
private ImmutableArray<byte> _byteArray;
/// <summary>
/// Converts a <see cref="byte"/> array into a <see cref="Nonce"/>
/// value.
/// <para>This constructor is an inverse function of
/// <see cref="ToByteArray()"/> method.</para>
/// </summary>
/// <param name="nonce">A <see cref="byte"/> array to convert to
/// a <see cref="Nonce"/> object. It must not be <c>null</c>.</param>
/// <exception cref="ArgumentNullException">Thrown when the given
/// <paramref name="nonce"/> is a <c>null</c>.</exception>
/// <seealso cref="ToByteArray()"/>
public Nonce(byte[] nonce)
: this(nonce?.ToImmutableArray() ?? throw new ArgumentNullException(nameof(nonce)))
{
}
/// <summary>
/// Converts an immutable <see cref="byte"/> array into a <see cref="Nonce"/> instance.
/// <para>This constructor is inverse of <see cref="ByteArray"/> property.</para>
/// </summary>
/// <param name="nonce">An immutable <see cref="byte"/> array to convert to
/// a <see cref="Nonce"/> instance.</param>
/// <seealso cref="ByteArray"/>
public Nonce(ImmutableArray<byte> nonce) =>
_byteArray = nonce;
/// <summary>
/// A bare immutable <see cref="byte"/> array of the nonce.
/// </summary>
/// <remarks>It is immutable. For a mutable array, use
/// <see cref="ToByteArray()"/> method instead.</remarks>
/// <seealso cref="ToByteArray()"/>
public ImmutableArray<byte> ByteArray
{
get
{
if (_byteArray.IsDefault)
{
_byteArray = ImmutableArray<byte>.Empty;
}
return _byteArray;
}
}
public static bool operator ==(Nonce left, Nonce right) => Operator.Weave(left, right);
public static bool operator !=(Nonce left, Nonce right) => Operator.Weave(left, right);
/// <summary>
/// Gets a bare mutable <see cref="byte"/> array of the nonce.
/// </summary>
/// <returns>A new mutable <see cref="byte"/> array of the nonce.
/// Since a returned array is created every time the method is called,
/// any mutations on that array does not affect to
/// the <see cref="Nonce"/> object.
/// </returns>
/// <seealso cref="ByteArray"/>
[Pure]
public byte[] ToByteArray() => ByteArray.ToArray();
/// <summary>
/// Gets a hexadecimal representation of a <see cref="Nonce"/>.
/// </summary>
/// <returns>A hexadecimal representation of a <see cref="Nonce"/>.
/// </returns>
[Pure]
public override string ToString()
{
return ByteUtil.Hex(ToByteArray());
}
}
}