using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Discord { internal static class CollectionExtensions { //public static IReadOnlyCollection ToReadOnlyCollection(this IReadOnlyCollection source) // => new CollectionWrapper(source, () => source.Count); public static IReadOnlyCollection ToReadOnlyCollection(this ICollection source) => new CollectionWrapper(source, () => source.Count); //public static IReadOnlyCollection ToReadOnlyCollection(this IReadOnlyDictionary source) // => new CollectionWrapper(source.Select(x => x.Value), () => source.Count); public static IReadOnlyCollection ToReadOnlyCollection(this IDictionary source) => new CollectionWrapper(source.Select(x => x.Value), () => source.Count); public static IReadOnlyCollection ToReadOnlyCollection(this IEnumerable query, IReadOnlyCollection source) => new CollectionWrapper(query, () => source.Count); public static IReadOnlyCollection ToReadOnlyCollection(this IEnumerable query, Func countFunc) => new CollectionWrapper(query, countFunc); } [DebuggerDisplay(@"{DebuggerDisplay,nq}")] internal struct CollectionWrapper : IReadOnlyCollection { private readonly IEnumerable _query; private readonly Func _countFunc; //It's okay that this count is affected by race conditions - we're wrapping a concurrent collection and that's to be expected public int Count => _countFunc(); public CollectionWrapper(IEnumerable query, Func countFunc) { _query = query; _countFunc = countFunc; } private string DebuggerDisplay => $"Count = {Count}"; public IEnumerator GetEnumerator() => _query.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _query.GetEnumerator(); } }