diff --git a/src/client/spark_core/Collections/Extensions/ListExtensions.cs b/src/client/spark_core/Collections/Extensions/ListExtensions.cs index 4ed226ed0..1ea655323 100644 --- a/src/client/spark_core/Collections/Extensions/ListExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/ListExtensions.cs @@ -158,6 +158,9 @@ namespace bts.collections { public static IReadOnlyList WrapSelectorRO(this IList list, Func convert) => new SelectorWrapper(list, convert, null); + public static IReadOnlyList WrapReadOnlySelector(this IReadOnlyList list, Func convert) => + new ReadOnlySelectorWrapper(list, convert); + private static Random rng = new Random(); public static void Shuffle(this IList list) { @@ -374,6 +377,56 @@ namespace bts.collections { } } + class ReadOnlySelectorWrapper : IReadOnlyList, IList { + readonly IReadOnlyList _source; + readonly Func _convert; + + public ReadOnlySelectorWrapper(IReadOnlyList source, Func convert) { + _source = source; + _convert = convert; + } + + public TOut this[int index] { + get => _convert(_source[index]); + set => throw new NotSupportedException(); + } + + public int Count => _source.Count; + + public bool IsReadOnly => true; + + public void Add(TOut item) => throw new NotSupportedException(); + public void Clear() => throw new NotSupportedException(); + + public bool Contains(TOut item) => + IndexOf(item) >= 0; + + public void CopyTo(TOut[] array, int arrayIndex) { + int stop = _source.Count; + for (int i = 0; i < stop; i++) + array[i + arrayIndex] = _convert(_source[i]); + } + + public IEnumerator GetEnumerator() { + for (int i = 0; i < _source.Count; i++) + yield return _convert(_source[i]); + } + IEnumerator IEnumerable.GetEnumerator() => + GetEnumerator(); + + public int IndexOf(TOut item) { + for (int i = 0; i < _source.Count; i++) { + if (EqualityComparer.Default.Equals(_convert(_source[i]), item)) + return i; + } + return -1; + } + + public void Insert(int index, TOut item) => throw new NotSupportedException(); + public bool Remove(TOut item) => throw new NotImplementedException(); + public void RemoveAt(int index) => throw new NotImplementedException(); + } + class SelectorWrapper : IList, IList, IReadOnlyList { readonly Func _convert; readonly Func _convert_back;