#nullable enable namespace Spark.DataStream { using System; using System.Collections; using System.Collections.Generic; public static class GenericCollectionWrapper { public static GenericCollectionWrapper Create( ICollection source, Func? cast = null) => new(source, cast); } public class GenericCollectionWrapper : ICollection { readonly ICollection source; readonly ICollection? genericSource; readonly IList? listSource; readonly Func cast; public GenericCollectionWrapper(ICollection source, Func? cast = null) { this.source = source; this.cast = cast ?? ConvertUtils.try_convert; genericSource = source as ICollection; listSource = source as IList; } public int Count => source.Count; public bool IsReadOnly => genericSource?.IsReadOnly ?? false; public void Add(T item) { if (genericSource is not null) { genericSource.Add(item); return; } if (listSource is not null) { listSource?.Add(item); return; } throw new InvalidOperationException(); } public void Clear() { if (genericSource is not null) { genericSource?.Clear(); return; } listSource?.Clear(); } public bool Contains(T item) { if (genericSource is not null) { return genericSource.Contains(item); } var cmp = EqualityComparer.Default; foreach (var obj in source) { if (cmp.Equals(cast(obj), item)) { return true; } } return false; } public void CopyTo(T[] array, int arrayIndex) { if (genericSource is not null) { genericSource.CopyTo(array, arrayIndex); return; } foreach (var obj in source) { array[arrayIndex++] = cast(obj); } } public IEnumerator GetEnumerator() { if (genericSource is not null) { return genericSource.GetEnumerator(); } return castImpl(); IEnumerator castImpl() { foreach (var obj in source) { yield return cast(obj); } } } public bool Remove(T item) { if (genericSource is not null) { return genericSource.Remove(item); } if (listSource is not null) { int origCount = Count; listSource.Remove(cast(item)); return Count == origCount - 1; } throw new InvalidOperationException(); } IEnumerator IEnumerable.GetEnumerator() => source.GetEnumerator(); } }