-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXxHash128HashProvider.cs
More file actions
95 lines (84 loc) · 2.44 KB
/
Copy pathXxHash128HashProvider.cs
File metadata and controls
95 lines (84 loc) · 2.44 KB
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
90
91
92
93
94
95
// Copyright (c) 2023-2026 ktsu-dev contributors
namespace ktsu.Essentials.HashProviders.XxHash128;
using ktsu.Essentials;
using System;
using System.IO;
using SysXxHash128 = System.IO.Hashing.XxHash128;
/// <summary>
/// A hash provider that uses xxHash128 for hashing data.
/// </summary>
public class XxHash128HashProvider : IHashProvider
{
/// <summary>
/// The length of the xxHash128 hash in bytes (16 bytes / 128 bits).
/// </summary>
public int HashLengthBytes => 16;
/// <summary>
/// Tries to hash the specified data into the provided hash buffer using xxHash128.
/// </summary>
/// <param name="data">The data to hash.</param>
/// <param name="destination">The hash buffer to write the result to.</param>
/// <param name="bytesWritten">The number of bytes written to <paramref name="destination"/>.</param>
/// <returns>True if the hash operation was successful, false otherwise.</returns>
public bool TryHash(ReadOnlySpan<byte> data, Span<byte> destination, out int bytesWritten)
{
bytesWritten = 0;
if (destination.Length < HashLengthBytes)
{
return false;
}
try
{
return SysXxHash128.TryHash(data, destination, out bytesWritten)
&& bytesWritten == HashLengthBytes;
}
catch (ArgumentException)
{
return false;
}
}
/// <summary>
/// Tries to hash the specified data from a stream into the provided hash buffer using xxHash128.
/// </summary>
/// <param name="data">The stream containing data to hash.</param>
/// <param name="destination">The hash buffer to write the result to.</param>
/// <param name="bytesWritten">The number of bytes written to <paramref name="destination"/>.</param>
/// <returns>True if the hash operation was successful, false otherwise.</returns>
public bool TryHash(Stream data, Span<byte> destination, out int bytesWritten)
{
bytesWritten = 0;
if (destination.Length < HashLengthBytes)
{
return false;
}
if (data is null)
{
return false;
}
try
{
SysXxHash128 hasher = new();
hasher.Append(data);
return hasher.TryGetHashAndReset(destination, out bytesWritten)
&& bytesWritten == HashLengthBytes;
}
catch (ArgumentException)
{
return false;
}
catch (IOException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
catch (NotSupportedException)
{
return false;
}
}
/// <inheritdoc/>
public IIncrementalHash CreateIncremental() => new NonCryptoIncrementalHash(new SysXxHash128(), HashLengthBytes);
}