forked from microsoft/MixedRealityToolkit-Unity
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReadOnlyHashSet.cs
88 lines (73 loc) · 2.42 KB
/
ReadOnlyHashSet.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// A wrapper for <see cref="HashSet{T}"/> that doesn't allow modification of the set. This is
/// useful for handing out references to a set that is going to be modified internally, without
/// giving external consumers the opportunity to accidentally modify the set.
/// </summary>
public class ReadOnlyHashSet<TElement> :
ICollection<TElement>,
IEnumerable<TElement>,
IEnumerable
{
private readonly HashSet<TElement> underlyingSet;
public ReadOnlyHashSet(HashSet<TElement> underlyingSet)
{
Debug.Assert(underlyingSet != null, "underlyingSet cannot be null.");
this.underlyingSet = underlyingSet;
}
public int Count
{
get { return underlyingSet.Count; }
}
bool ICollection<TElement>.IsReadOnly
{
get { return true; }
}
void ICollection<TElement>.Add(TElement item)
{
throw NewWriteDeniedException();
}
void ICollection<TElement>.Clear()
{
throw NewWriteDeniedException();
}
public bool Contains(TElement item)
{
return underlyingSet.Contains(item);
}
public void CopyTo(TElement[] array, int arrayIndex)
{
underlyingSet.CopyTo(array, arrayIndex);
}
public IEnumerator<TElement> GetEnumerator()
{
return underlyingSet.GetEnumerator();
}
bool ICollection<TElement>.Remove(TElement item)
{
throw NewWriteDeniedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return underlyingSet.GetEnumerator();
}
private NotSupportedException NewWriteDeniedException()
{
return new NotSupportedException("ReadOnlyHashSet<TElement> is not directly writable.");
}
}
public static class ReadOnlyHashSetRelatedExtensions
{
public static ReadOnlyHashSet<TElement> AsReadOnly<TElement>(this HashSet<TElement> set)
{
return new ReadOnlyHashSet<TElement>(set);
}
}
}