added 'ReverseWrapper()' to ListExtensions

This commit is contained in:
John Colvin committed 2019-08-14 00:24:34 -05:00
1 parent df6b065e43
commit 32b9c0db10
1 file changed
+54
@@ -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<T> WrapType<T>(this IList list) =>
new TypeWrapper<T>(list);
public static IList<T> WrapReverse<T>(this IList<T> list) =>
new ReverseWrapper<T>(list);
public static IReadOnlyList<T> WrapReverseRO<T>(this IList<T> list) =>
new ReverseWrapper<T>(list);
public static IList<T> WrapSubRange<T>(this IList<T> list, int start) =>
new SubRangeWrapper<T>(list, start, list.Count - start);
@@ -220,6 +227,53 @@ namespace bts.collections {
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
class ReverseWrapper<T> : IList<T>, IReadOnlyList<T> {
readonly IList<T> _source;
public ReverseWrapper(IList<T> 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<T> 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<T> : IList<T>, IReadOnlyList<T> {
readonly IList<T> _source;
readonly int _start;