101 lines
2.8 KiB
C#
101 lines
2.8 KiB
C#
#nullable enable
|
|
namespace Spark.DataStream {
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
|
|
public static class GenericCollectionWrapper {
|
|
public static GenericCollectionWrapper<T> Create<T>(
|
|
ICollection source, Func<object?, T>? cast = null) =>
|
|
new(source, cast);
|
|
}
|
|
|
|
public class GenericCollectionWrapper<T> : ICollection<T> {
|
|
readonly ICollection source;
|
|
readonly ICollection<T>? genericSource;
|
|
readonly IList? listSource;
|
|
readonly Func<object?, T> cast;
|
|
|
|
public GenericCollectionWrapper(ICollection source, Func<object?, T>? cast = null) {
|
|
this.source = source;
|
|
this.cast = cast ?? ConvertUtils.try_convert<T>;
|
|
genericSource = source as ICollection<T>;
|
|
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<T>.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<T> GetEnumerator() {
|
|
if (genericSource is not null) {
|
|
return genericSource.GetEnumerator();
|
|
}
|
|
return castImpl();
|
|
IEnumerator<T> 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();
|
|
}
|
|
}
|