-
Notifications
You must be signed in to change notification settings - Fork 139
/
HashAlgorithmTable.cs
59 lines (55 loc) · 2.32 KB
/
HashAlgorithmTable.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
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Libplanet.Blocks
{
public static class HashAlgorithmTable
{
/// <summary>
/// Creates a <see cref="HashAlgorithmGetter"/> delegate from a <paramref name="table"/>.
/// </summary>
/// <param name="table">A table with block index offsets and their corresponding
/// <see cref="HashAlgorithmType"/>. For example, <c>0: SHA1, 10: SHA256, 100: SHA512</c>
/// means <c>i => i >= 100 ? HashAlgorithmType.Of<SHA512>() : i >= 10 ?
/// HashAlgorithmType.Of<SHA256>() : HashAlgorithmType.Of<SHA1>()</c>.
/// (Note that 0 means <em>otherwise</em>.) It must contain at least one entry with
/// index 0, because it is the last fallback.</param>
/// <returns>A corresponding <see cref="HashAlgorithmGetter"/>.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="table"/> has no
/// the last fallback entry with index 0, or there are entries with duplicate indices.
/// </exception>
public static HashAlgorithmGetter ToHashAlgorithmGetter(
this IEnumerable<KeyValuePair<long, HashAlgorithmType>> table
)
{
KeyValuePair<long, HashAlgorithmType>[] indices =
table.OrderByDescending(kv => kv.Key).ToArray();
if (!indices.Any() || indices[indices.Length - 1].Key > 0)
{
throw new ArgumentException(
$"The {nameof(table)} must contain at least one entry with index 0.",
nameof(table)
);
}
else if (indices.Select(kv => kv.Key).ToImmutableHashSet().Count < indices.Length)
{
throw new ArgumentException(
$"Entries with duplicate indices are disallowed.",
nameof(table)
);
}
return index =>
{
foreach (KeyValuePair<long, HashAlgorithmType> pair in indices)
{
if (index >= pair.Key)
{
return pair.Value;
}
}
return indices[0].Value;
};
}
}
}