Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ReadOnlySet<T> #103306

Merged
merged 3 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/libraries/System.Collections/ref/System.Collections.cs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,38 @@ void System.Collections.IEnumerator.Reset() { }
}
}
}
namespace System.Collections.ObjectModel
{
public partial class ReadOnlySet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlySet<T>, System.Collections.Generic.ISet<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public ReadOnlySet(System.Collections.Generic.ISet<T> @set) { }
public int Count { get { throw null; } }
public static System.Collections.ObjectModel.ReadOnlySet<T> Empty { get { throw null; } }
protected System.Collections.Generic.ISet<T> Set { get { throw null; } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public bool Contains(T item) { throw null; }
public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; }
public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { throw null; }
void System.Collections.Generic.ICollection<T>.Add(T item) { }
void System.Collections.Generic.ICollection<T>.Clear() { }
void System.Collections.Generic.ICollection<T>.CopyTo(T[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<T>.Remove(T item) { throw null; }
bool System.Collections.Generic.ISet<T>.Add(T item) { throw null; }
void System.Collections.Generic.ISet<T>.ExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
void System.Collections.Generic.ISet<T>.IntersectWith(System.Collections.Generic.IEnumerable<T> other) { }
void System.Collections.Generic.ISet<T>.SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
void System.Collections.Generic.ISet<T>.UnionWith(System.Collections.Generic.IEnumerable<T> other) { }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
}
#endif // !BUILDING_CORELIB_REFERENCE
namespace System.Collections.Generic
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
Link="Common\System\Collections\Generic\ICollectionDebugView.cs" />
<Compile Include="$(CoreLibSharedDir)System\Collections\Generic\IDictionaryDebugView.cs"
Link="Common\System\Collections\Generic\IDictionaryDebugView.cs" />
<Compile Include="$(CoreLibSharedDir)System\Collections\ObjectModel\CollectionHelpers.cs"
Link="Common\System\Collections\ObjectModel\CollectionHelpers.cs" />
<Compile Include="System\Collections\Generic\LinkedList.cs" />
<Compile Include="System\Collections\Generic\PriorityQueue.cs" />
<Compile Include="System\Collections\Generic\PriorityQueueDebugView.cs" />
<Compile Include="System\Collections\Generic\ReadOnlySet.cs" />
<Compile Include="System\Collections\Generic\SortedDictionary.cs" />
<Compile Include="System\Collections\Generic\SortedList.cs" />
<Compile Include="System\Collections\Generic\SortedSet.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// 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.Generic;
using System.Diagnostics;

namespace System.Collections.ObjectModel
{
/// <summary>Represents a read-only, generic set of values.</summary>
/// <typeparam name="T">The type of values in the set.</typeparam>
[DebuggerDisplay("Count = {Count}")]
public class ReadOnlySet<T> : IReadOnlySet<T>, ISet<T>, ICollection
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
{
/// <summary>The wrapped set.</summary>
private readonly ISet<T> _set;

/// <summary>Initializes a new instance of the <see cref="ReadOnlySet{T}"/> class that is a wrapper around the specified set.</summary>
/// <param name="set">The set to wrap.</param>
public ReadOnlySet(ISet<T> set)
{
ArgumentNullException.ThrowIfNull(set);
_set = set;
}

/// <summary>Gets an empty <see cref="ReadOnlySet{T}"/>.</summary>
public static ReadOnlySet<T> Empty { get; } = new ReadOnlySet<T>(new HashSet<T>());
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved

/// <summary>Gets the set that is wrapped by this <see cref="ReadOnlySet{T}"/> object.</summary>
protected ISet<T> Set => _set;

/// <inheritdoc/>
public int Count => _set.Count;

/// <inheritdoc/>
public IEnumerator<T> GetEnumerator() =>
_set.Count == 0 ? ((IEnumerable<T>)Array.Empty<T>()).GetEnumerator() :
_set.GetEnumerator();

/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

/// <inheritdoc/>
public bool Contains(T item) => _set.Contains(item);

/// <inheritdoc/>
public bool IsProperSubsetOf(IEnumerable<T> other) => _set.IsProperSubsetOf(other);

/// <inheritdoc/>
public bool IsProperSupersetOf(IEnumerable<T> other) => _set.IsProperSupersetOf(other);

/// <inheritdoc/>
public bool IsSubsetOf(IEnumerable<T> other) => _set.IsSubsetOf(other);

/// <inheritdoc/>
public bool IsSupersetOf(IEnumerable<T> other) => _set.IsSupersetOf(other);

/// <inheritdoc/>
public bool Overlaps(IEnumerable<T> other) => _set.Overlaps(other);

/// <inheritdoc/>
public bool SetEquals(IEnumerable<T> other) => _set.SetEquals(other);

/// <inheritdoc/>
void ICollection<T>.CopyTo(T[] array, int arrayIndex) => _set.CopyTo(array, arrayIndex);

/// <inheritdoc/>
void ICollection.CopyTo(Array array, int index) => CollectionHelpers.CopyTo(_set, array, index);

/// <inheritdoc/>
bool ICollection<T>.IsReadOnly => true;

/// <inheritdoc/>
bool ICollection.IsSynchronized => false;
stephentoub marked this conversation as resolved.
Show resolved Hide resolved

/// <inheritdoc/>
object ICollection.SyncRoot => _set is ICollection c ? c.SyncRoot : this;

/// <inheritdoc/>
bool ISet<T>.Add(T item) => throw new NotSupportedException();

/// <inheritdoc/>
void ISet<T>.ExceptWith(IEnumerable<T> other) => throw new NotSupportedException();

/// <inheritdoc/>
void ISet<T>.IntersectWith(IEnumerable<T> other) => throw new NotSupportedException();

/// <inheritdoc/>
void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) => throw new NotSupportedException();

/// <inheritdoc/>
void ISet<T>.UnionWith(IEnumerable<T> other) => throw new NotSupportedException();

/// <inheritdoc/>
void ICollection<T>.Add(T item) => throw new NotSupportedException();

/// <inheritdoc/>
void ICollection<T>.Clear() => throw new NotSupportedException();

/// <inheritdoc/>
bool ICollection<T>.Remove(T item) => throw new NotSupportedException();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// 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.Generic;
using Xunit;

namespace System.Collections.ObjectModel.Tests
{
public class ReadOnlySetTests
{
[Fact]
public void Ctor_NullSet_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("set", () => new ReadOnlySet<int>(null));
}

[Fact]
public void Ctor_SetProperty_Roundtrips()
{
var set = new HashSet<int>();
Assert.Same(set, new DerivedReadOnlySet<int>(set).Set);
}

[Fact]
public void Empty_EmptyAndIdempotent()
{
Assert.Same(ReadOnlySet<int>.Empty, ReadOnlySet<int>.Empty);
Assert.Empty(ReadOnlySet<int>.Empty);
Assert.Same(ReadOnlySet<int>.Empty.GetEnumerator(), ReadOnlySet<int>.Empty.GetEnumerator());
}

[Fact]
public void MembersDelegateToWrappedSet()
{
var set = new ReadOnlySet<int>(new HashSet<int>() { 1, 2, 3 });

Assert.True(set.Contains(2));
Assert.False(set.Contains(4));

Assert.Equal(3, set.Count);

Assert.True(set.IsProperSubsetOf([1, 2, 3, 4]));
Assert.False(set.IsProperSubsetOf([1, 2, 5]));

Assert.True(set.IsProperSupersetOf([1, 2]));
Assert.False(set.IsProperSupersetOf([1, 4]));

Assert.True(set.IsSubsetOf([1, 2, 3, 4]));
Assert.False(set.IsSubsetOf([1, 2, 5]));

Assert.True(set.IsSupersetOf([1, 2]));
Assert.False(set.IsSupersetOf([1, 4]));

Assert.True(set.Overlaps([-1, 0, 1]));
Assert.False(set.Overlaps([-1, 0]));

Assert.True(set.SetEquals([1, 2, 3]));
Assert.False(set.SetEquals([1, 2, 4]));

int[] result = new int[3];
((ICollection<int>)set).CopyTo(result, 0);
Assert.Equal(result, new int[] { 1, 2, 3 });

Array.Clear(result);
((ICollection)set).CopyTo(result, 0);
Assert.Equal(result, new int[] { 1, 2, 3 });

Assert.NotNull(set.GetEnumerator());
}

[Fact]
public void ChangesToUnderlyingSetReflected()
{
var set = new HashSet<int> { 1, 2, 3 };
var readOnlySet = new ReadOnlySet<int>(set);

set.Add(4);
Assert.Equal(4, readOnlySet.Count);
Assert.True(readOnlySet.Contains(4));

set.Remove(2);
Assert.Equal(3, readOnlySet.Count);
Assert.False(readOnlySet.Contains(2));
}

[Fact]
public void IsReadOnly_True()
{
var set = new ReadOnlySet<int>(new HashSet<int> { 1, 2, 3 });
Assert.True(((ICollection<int>)set).IsReadOnly);
}

[Fact]
public void MutationThrows_CollectionUnmodified()
{
var set = new HashSet<int> { 1, 2, 3 };
var readOnlySet = new ReadOnlySet<int>(set);

Assert.Throws<NotSupportedException>(() => ((ICollection<int>)readOnlySet).Add(4));
Assert.Throws<NotSupportedException>(() => ((ICollection<int>)readOnlySet).Remove(1));
Assert.Throws<NotSupportedException>(() => ((ICollection<int>)readOnlySet).Clear());

Assert.Throws<NotSupportedException>(() => ((ISet<int>)readOnlySet).Add(4));
Assert.Throws<NotSupportedException>(() => ((ISet<int>)readOnlySet).ExceptWith([1, 2, 3]));
Assert.Throws<NotSupportedException>(() => ((ISet<int>)readOnlySet).IntersectWith([1, 2, 3]));
Assert.Throws<NotSupportedException>(() => ((ISet<int>)readOnlySet).SymmetricExceptWith([1, 2, 3]));
Assert.Throws<NotSupportedException>(() => ((ISet<int>)readOnlySet).UnionWith([1, 2, 3]));

Assert.Equal(3, set.Count);
}

[Fact]
public void ICollection_Synchronization()
{
var set = new ReadOnlySet<int>(new HashSet<int> { 1, 2, 3 });

Assert.False(((ICollection)set).IsSynchronized);
Assert.Same(set, ((ICollection)set).SyncRoot);
}

private class DerivedReadOnlySet<T> : ReadOnlySet<T>
{
public DerivedReadOnlySet(HashSet<T> set) : base(set) { }

public new ISet<T> Set => base.Set;
}
}
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
}
Loading
Loading