-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
ImmutableEquatableArray.cs
86 lines (68 loc) · 2.84 KB
/
ImmutableEquatableArray.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Numerics.Hashing;
namespace System.Text.Json.SourceGeneration
{
/// <summary>
/// Provides an immutable list implementation which implements sequence equality.
/// </summary>
public sealed class ImmutableEquatableArray<T> : IEquatable<ImmutableEquatableArray<T>>, IReadOnlyList<T>
where T : IEquatable<T>
{
public static ImmutableEquatableArray<T> Empty { get; } = new ImmutableEquatableArray<T>(Array.Empty<T>());
private readonly T[] _values;
public T this[int index] => _values[index];
public int Count => _values.Length;
public ImmutableEquatableArray(IEnumerable<T> values)
=> _values = values.ToArray();
public bool Equals(ImmutableEquatableArray<T>? other)
=> other != null && ((ReadOnlySpan<T>)_values).SequenceEqual(other._values);
public override bool Equals(object? obj)
=> obj is ImmutableEquatableArray<T> other && Equals(other);
public override int GetHashCode()
{
int hash = 0;
foreach (T value in _values)
{
hash = HashHelpers.Combine(hash, value is null ? 0 : value.GetHashCode());
}
return hash;
}
public Enumerator GetEnumerator() => new Enumerator(_values);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => ((IEnumerable<T>)_values).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _values.GetEnumerator();
public struct Enumerator
{
private readonly T[] _values;
private int _index;
internal Enumerator(T[] values)
{
_values = values;
_index = -1;
}
public bool MoveNext()
{
int newIndex = _index + 1;
if ((uint)newIndex < (uint)_values.Length)
{
_index = newIndex;
return true;
}
return false;
}
public readonly T Current => _values[_index];
}
}
public static class ImmutableEquatableArray
{
public static ImmutableEquatableArray<T> Empty<T>() where T : IEquatable<T>
=> ImmutableEquatableArray<T>.Empty;
public static ImmutableEquatableArray<T> ToImmutableEquatableArray<T>(this IEnumerable<T> values) where T : IEquatable<T>
=> new(values);
public static ImmutableEquatableArray<T> Create<T>(params T[] values) where T : IEquatable<T>
=> values is { Length: > 0 } ? new(values) : ImmutableEquatableArray<T>.Empty;
}
}