Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created August 2, 2021 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/9899e63d3b348a1ad195f88c4b744f29 to your computer and use it in GitHub Desktop.
Save atifaziz/9899e63d3b348a1ad195f88c4b744f29 to your computer and use it in GitHub Desktop.
An empty set implementation
#region Copyright (c) 2021 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
sealed partial class EmptySet<T> : ISet<T>
{
public static readonly EmptySet<T> Instance = new EmptySet<T>();
EmptySet() { }
public int Count => 0;
public bool IsReadOnly => true;
public bool Contains(T item) => false;
void ICollection<T>.CopyTo(T[] array, int arrayIndex) { /* nothing to copy */ }
public IEnumerator<T> GetEnumerator() { yield break; }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public bool IsProperSubsetOf(IEnumerable<T> other) => true;
public bool IsProperSupersetOf(IEnumerable<T> other) => false;
public bool IsSubsetOf(IEnumerable<T> other) => true;
public bool IsSupersetOf(IEnumerable<T> other) => false;
public bool Overlaps(IEnumerable<T> other) => false;
public bool SetEquals(IEnumerable<T> other)
{
switch (other)
{
case null: throw new ArgumentNullException(nameof(other));
case ICollection<T> collection: return collection.Count == 0;
case IReadOnlyCollection<T> collection: return collection.Count == 0;
case { } sequence:
{
using var e = sequence.GetEnumerator();
return !e.MoveNext();
}
}
}
void ICollection<T>.Add(T item) => throw new NotSupportedException();
bool ICollection<T>.Remove(T item) => throw new NotSupportedException();
void ISet<T>.ExceptWith(IEnumerable<T> other) => throw new NotSupportedException();
void ISet<T>.IntersectWith(IEnumerable<T> other) => throw new NotSupportedException();
void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) => throw new NotSupportedException();
void ISet<T>.UnionWith(IEnumerable<T> other) => throw new NotSupportedException();
bool ISet<T>.Add(T item) => throw new NotSupportedException();
void ICollection<T>.Clear() => throw new NotSupportedException();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment