diff --git a/src/client/spark_core/Collections/Extensions/ListExtensions.cs b/src/client/spark_core/Collections/Extensions/ListExtensions.cs index 194085d20..705165806 100644 --- a/src/client/spark_core/Collections/Extensions/ListExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/ListExtensions.cs @@ -1,4 +1,5 @@ using bts.utils; +using mbts.utils; using System; using System.Collections; using System.Collections.Generic; @@ -110,6 +111,12 @@ namespace bts.collections { public static IList WrapType(this IList list) => new TypeWrapper(list); + public static IList WrapReverse(this IList list) => + new ReverseWrapper(list); + + public static IReadOnlyList WrapReverseRO(this IList list) => + new ReverseWrapper(list); + public static IList WrapSubRange(this IList list, int start) => new SubRangeWrapper(list, start, list.Count - start); @@ -220,6 +227,53 @@ namespace bts.collections { IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } + class ReverseWrapper : IList, IReadOnlyList { + readonly IList _source; + + public ReverseWrapper(IList source) => + _source = source ?? throw new ArgumentNullException(nameof(source)); + + public T this[int index] { + get => _source[_check_reverse(index)]; + set => _source[_check_reverse(index)] = value; + } + + public int Count => _source.Count; + + public bool IsReadOnly => _source.IsReadOnly; + + public void Add(T item) => _source.Insert(0, item); + public void Clear() => _source.Clear(); + public bool Contains(T item) => _source.Contains(item); + public void CopyTo(T[] array, int arrayIndex) { + for (int i = 0; i < Count; i++) + array[arrayIndex + i] = _source[_reverse(i)]; + } + public IEnumerator GetEnumerator() { + for (int i = Count - 1; i >= 0; i--) + yield return _source[i]; + } + public int IndexOf(T item) { + /// Though it isn't stated in the IList contract, it is standard practice for 'IndexOf' to return -1 if the item isn't found. + /// Therefor, if 'i' is negative, return it directly (without reversing it). + int i = _source.IndexOf(item); + return i < 0 ? i : _reverse(i); + } + public void Insert(int index, T item) => _source.Insert(_check_reverse(index), item); + public bool Remove(T item) => _source.Remove(item); + public void RemoveAt(int index) => _source.RemoveAt(_check_reverse(index)); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + // Validates the index before reversing it, so any inevitable 'IndexOutOfRange' exception isn't incidentally reversed too. + int _check_reverse(int index) => + index < 0 ? throw ExceptionBuilder.IndexOutOfRange.lt_zero() : + index >= Count ? throw ExceptionBuilder.IndexOutOfRange.gte_length() : + _reverse(index); + + int _reverse(int index) => + Count - index - 1; + } + class SubRangeWrapper : IList, IReadOnlyList { readonly IList _source; readonly int _start;