-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReadonlyBytes.cs
78 lines (68 loc) · 1.96 KB
/
ReadonlyBytes.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace hashes
{
public class ReadonlyBytes : IEnumerable<byte>
{
private readonly byte[] _array;
internal readonly int Length;
private readonly int _hashCode;
public ReadonlyBytes(params byte[] item)
{
_array = item ?? throw new ArgumentNullException();
_hashCode = CalculateHashCode();
Length = item.Length;
}
public byte this[int index]
{
get
{
if (index < 0 || index >= Length) throw new IndexOutOfRangeException();
return _array[index];
}
}
public IEnumerator<byte> GetEnumerator()
{
for (var i = 0; i < Length; i++)
yield return _array[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public override string ToString()
{
if (_array.Length == 0)
return "[]";
var builder = new StringBuilder();
builder.Append("[");
for (var i = 0; i < _array.Length; i++)
{
builder.Append(_array[i]);
builder.Append(i == _array.Length - 1 ? "]" : ", ");
}
return builder.ToString();
}
public override bool Equals(object obj)
{
if (obj?.GetType() != this.GetType()) return false;
return obj.GetHashCode() == _hashCode;
}
public sealed override int GetHashCode()
{
return _hashCode;
}
private int CalculateHashCode()
{
unchecked
{
var hash = 1677711;
foreach (var item in _array)
hash = hash * 2166131 + item.GetHashCode();
return hash;
}
}
}
}