replace SynchronizedViewList backed uses AlternateIndexList

This commit is contained in:
neuecc 2024-09-02 19:31:29 +09:00
parent 08b328c16f
commit c0c9cd48d7
6 changed files with 602 additions and 625 deletions

View File

@ -0,0 +1,222 @@
#pragma warning disable CS0436
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
namespace ObservableCollections;
public class AlternateIndexList<T> : IEnumerable<T>
{
List<IndexedValue> list; // alternate index is ordered
public AlternateIndexList()
{
this.list = new();
}
public AlternateIndexList(IEnumerable<(int OrderedAlternateIndex, T Value)> values)
{
this.list = values.Select(x => new IndexedValue(x.OrderedAlternateIndex, x.Value)).ToList();
}
void UpdateAlternateIndex(int startIndex, int incr)
{
var span = CollectionsMarshal.AsSpan(list);
for (int i = startIndex; i < span.Length; i++)
{
span[i].AlternateIndex += incr;
}
}
public T this[int index]
{
get => list[index].Value;
}
public int Count => list.Count;
public void Insert(int alternateIndex, T value)
{
var index = list.BinarySearch(alternateIndex);
if (index < 0)
{
index = ~index;
}
list.Insert(index, new(alternateIndex, value));
UpdateAlternateIndex(index + 1, 1);
}
public void InsertRange(int startingAlternateIndex, IEnumerable<T> values)
{
var index = list.BinarySearch(startingAlternateIndex);
if (index < 0)
{
index = ~index;
}
using var iter = new InsertIterator(startingAlternateIndex, values);
list.InsertRange(index, iter);
UpdateAlternateIndex(index + iter.ConsumedCount, iter.ConsumedCount);
}
public void Remove(T value)
{
var index = list.FindIndex(x => EqualityComparer<T>.Default.Equals(x.Value, value));
if (index != -1)
{
list.RemoveAt(index);
UpdateAlternateIndex(index, -1);
}
}
public void RemoveAt(int alternateIndex)
{
var index = list.BinarySearch(alternateIndex);
if (index != -1)
{
list.RemoveAt(index);
UpdateAlternateIndex(index, -1);
}
}
public void RemoveRange(int alternateIndex, int count)
{
var index = list.BinarySearch(alternateIndex);
if (index < 0)
{
index = ~index;
}
list.RemoveRange(index, count);
UpdateAlternateIndex(index, -count);
}
public bool TryGetAtAlternateIndex(int alternateIndex, [MaybeNullWhen(true)] out T value)
{
var index = list.BinarySearch(alternateIndex);
if (index < 0)
{
value = default!;
return false;
}
value = list[index].Value!;
return true;
}
public bool TrySetAtAlternateIndex(int alternateIndex, T value)
{
var index = list.BinarySearch(alternateIndex);
if (index < 0)
{
return false;
}
CollectionsMarshal.AsSpan(list)[index].Value = value;
return true;
}
public bool TryReplaceByValue(T searchValue, T replaceValue)
{
var index = list.FindIndex(x => EqualityComparer<T>.Default.Equals(x.Value, searchValue));
if (index != -1)
{
CollectionsMarshal.AsSpan(list)[index].Value = replaceValue;
return true;
}
return false;
}
public void Clear()
{
list.Clear();
}
public void Clear(IEnumerable<(int OrderedAlternateIndex, T Value)> values)
{
list.Clear();
list.AddRange(values.Select(x => new IndexedValue(x.OrderedAlternateIndex, x.Value)));
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in list)
{
yield return item.Value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerable<(int AlternateIndex, T Value)> GetIndexedValues()
{
foreach (var item in list)
{
yield return (item.AlternateIndex, item.Value);
}
}
class InsertIterator(int startingIndex, IEnumerable<T> values) : IEnumerable<IndexedValue>, IEnumerator<IndexedValue>
{
IEnumerator<T> iter = values.GetEnumerator();
IndexedValue current;
public int ConsumedCount { get; private set; }
public IndexedValue Current => current;
object IEnumerator.Current => Current;
public void Dispose() => iter.Reset();
public bool MoveNext()
{
if (iter.MoveNext())
{
ConsumedCount++;
current = new(startingIndex++, iter.Current);
return true;
}
return false;
}
public void Reset() => iter.Reset();
public IEnumerator<IndexedValue> GetEnumerator() => this;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
struct IndexedValue : IComparable<IndexedValue>
{
public int AlternateIndex; // mutable
public T Value; // mutable
public IndexedValue(int alternateIndex, T value)
{
this.AlternateIndex = alternateIndex;
this.Value = value;
}
public static implicit operator IndexedValue(int alternateIndex) // for query
{
return new IndexedValue(alternateIndex, default!);
}
public int CompareTo(IndexedValue other)
{
return AlternateIndex.CompareTo(other.AlternateIndex);
}
public override string ToString()
{
return (AlternateIndex, Value).ToString();
}
}
}

View File

@ -1,211 +0,0 @@
#pragma warning disable CS0436
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
namespace ObservableCollections.Internal
{
public class AlternateIndexList<T> : IEnumerable<T>
{
List<IndexedValue> list; // alternate index is ordered
public AlternateIndexList()
{
this.list = new();
}
public AlternateIndexList(IEnumerable<(int OrderedAlternateIndex, T Value)> values)
{
this.list = values.Select(x => new IndexedValue(x.OrderedAlternateIndex, x.Value)).ToList();
}
void UpdateAlternateIndex(int startIndex, int incr)
{
var span = CollectionsMarshal.AsSpan(list);
for (int i = startIndex; i < span.Length; i++)
{
span[i].AlternateIndex += incr;
}
}
public T this[int index]
{
get => list[index].Value;
}
public int Count => list.Count;
public void Insert(int alternateIndex, T value)
{
var index = list.BinarySearch(alternateIndex);
if (index < 0)
{
index = ~index;
}
list.Insert(index, new(alternateIndex, value));
UpdateAlternateIndex(index + 1, 1);
}
public void InsertRange(int startingAlternateIndex, IEnumerable<T> values)
{
var index = list.BinarySearch(startingAlternateIndex);
if (index < 0)
{
index = ~index;
}
using var iter = new InsertIterator(startingAlternateIndex, values);
list.InsertRange(index, iter);
UpdateAlternateIndex(index + iter.ConsumedCount, iter.ConsumedCount);
}
public void Remove(T value)
{
var index = list.FindIndex(x => EqualityComparer<T>.Default.Equals(x.Value, value));
if (index != -1)
{
list.RemoveAt(index);
UpdateAlternateIndex(index, -1);
}
}
public void RemoveAt(int alternateIndex)
{
var index = list.BinarySearch(alternateIndex);
if (index != -1)
{
list.RemoveAt(index);
UpdateAlternateIndex(index, -1);
}
}
public void RemoveRange(int alternateIndex, int count)
{
var index = list.BinarySearch(alternateIndex);
if (index < 0)
{
index = ~index;
}
list.RemoveRange(index, count);
UpdateAlternateIndex(index, -count);
}
public bool TryGetAtAlternateIndex(int alternateIndex, [MaybeNullWhen(true)] out T value)
{
var index = list.BinarySearch(alternateIndex);
if (index < 0)
{
value = default!;
return false;
}
value = list[index].Value!;
return true;
}
public bool TrySetAtAlternateIndex(int alternateIndex, T value)
{
var index = list.BinarySearch(alternateIndex);
if (index < 0)
{
return false;
}
CollectionsMarshal.AsSpan(list)[index].Value = value;
return true;
}
public void Clear()
{
list.Clear();
}
// Can't implement add, reverse and sort because alternate index is unknown
// void Add();
// void AddRange();
// void Reverse();
// void Sort();
public IEnumerator<T> GetEnumerator()
{
foreach (var item in list)
{
yield return item.Value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerable<(int AlternateIndex, T Value)> GetIndexedValues()
{
foreach (var item in list)
{
yield return (item.AlternateIndex, item.Value);
}
}
class InsertIterator(int startingIndex, IEnumerable<T> values) : IEnumerable<IndexedValue>, IEnumerator<IndexedValue>
{
IEnumerator<T> iter = values.GetEnumerator();
IndexedValue current;
public int ConsumedCount { get; private set; }
public IndexedValue Current => current;
object IEnumerator.Current => Current;
public void Dispose() => iter.Reset();
public bool MoveNext()
{
if (iter.MoveNext())
{
ConsumedCount++;
current = new(startingIndex++, iter.Current);
return true;
}
return false;
}
public void Reset() => iter.Reset();
public IEnumerator<IndexedValue> GetEnumerator() => this;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
struct IndexedValue : IComparable<IndexedValue>
{
public int AlternateIndex; // mutable
public T Value; // mutable
public IndexedValue(int alternateIndex, T value)
{
this.AlternateIndex = alternateIndex;
this.Value = value;
}
public static implicit operator IndexedValue(int alternateIndex) // for query
{
return new IndexedValue(alternateIndex, default!);
}
public int CompareTo(IndexedValue other)
{
return AlternateIndex.CompareTo(other.AlternateIndex);
}
public override string ToString()
{
return (AlternateIndex, Value).ToString();
}
}
}
}

View File

@ -1,30 +0,0 @@
using System;
using System.Collections.Generic;
namespace ObservableCollections.Internal
{
internal class RemoveAllMatcher<T>
{
readonly HashSet<T> hashSet;
public RemoveAllMatcher(ReadOnlySpan<T> source)
{
#if !NETSTANDARD2_0
var set = new HashSet<T>(capacity: source.Length);
#else
var set = new HashSet<T>();
#endif
foreach (var item in source)
{
set.Add(item);
}
this.hashSet = set;
}
public bool Predicate(T value)
{
return hashSet.Contains(value);
}
}
}

View File

@ -100,11 +100,16 @@ namespace ObservableCollections
{ {
lock (SyncRoot) lock (SyncRoot)
{ {
var index = list.Count; var index = list.Count; // starting index
#if NET8_0_OR_GREATER
list.AddRange(items);
#else
foreach (var item in items) foreach (var item in items)
{ {
list.Add(item); list.Add(item);
} }
#endif
CollectionChanged?.Invoke(NotifyCollectionChangedEventArgs<T>.Add(items, index)); CollectionChanged?.Invoke(NotifyCollectionChangedEventArgs<T>.Add(items, index));
} }
@ -204,11 +209,16 @@ namespace ObservableCollections
{ {
lock (SyncRoot) lock (SyncRoot)
{ {
#if NET8_0_OR_GREATER
list.InsertRange(index, items);
CollectionChanged?.Invoke(NotifyCollectionChangedEventArgs<T>.Add(items, index));
#else
using (var xs = new CloneCollection<T>(items)) using (var xs = new CloneCollection<T>(items))
{ {
list.InsertRange(index, xs.AsEnumerable()); list.InsertRange(index, xs.AsEnumerable());
CollectionChanged?.Invoke(NotifyCollectionChangedEventArgs<T>.Add(xs.Span, index)); CollectionChanged?.Invoke(NotifyCollectionChangedEventArgs<T>.Add(xs.Span, index));
} }
#endif
} }
} }
@ -304,7 +314,6 @@ namespace ObservableCollections
} }
} }
public void Reverse(int index, int count) public void Reverse(int index, int count)
{ {
lock (SyncRoot) lock (SyncRoot)

View File

@ -7,13 +7,12 @@ using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace ObservableCollections namespace ObservableCollections;
{
internal class SynchronizedViewList<T, TView> : ISynchronizedViewList<TView> internal class SynchronizedViewList<T, TView> : ISynchronizedViewList<TView>
{ {
readonly ISynchronizedView<T, TView> parent; readonly ISynchronizedView<T, TView> parent;
protected readonly List<TView> listView; protected readonly AlternateIndexList<TView> listView;
protected readonly object gate = new object(); protected readonly object gate = new object();
public SynchronizedViewList(ISynchronizedView<T, TView> parent) public SynchronizedViewList(ISynchronizedView<T, TView> parent)
@ -21,41 +20,52 @@ namespace ObservableCollections
this.parent = parent; this.parent = parent;
lock (parent.SyncRoot) lock (parent.SyncRoot)
{ {
listView = parent.ToList(); listView = new AlternateIndexList<TView>(IterateFilteredIndexedViewsOfParent());
parent.ViewChanged += Parent_ViewChanged; parent.ViewChanged += Parent_ViewChanged;
} }
} }
IEnumerable<(int, TView)> IterateFilteredIndexedViewsOfParent()
{
var filter = parent.Filter;
var index = 0;
if (filter.IsNullFilter())
{
foreach (var item in parent.Unfiltered) // use Unfiltered
{
yield return (index, item.View);
index++;
}
}
else
{
foreach (var item in parent.Unfiltered) // use Unfiltered
{
if (filter.IsMatch(item.Value))
{
yield return (index, item.View);
}
index++;
}
}
}
private void Parent_ViewChanged(in SynchronizedViewChangedEventArgs<T, TView> e) private void Parent_ViewChanged(in SynchronizedViewChangedEventArgs<T, TView> e)
{ {
// event is called inside parent lock
lock (gate) lock (gate)
{ {
switch (e.Action) switch (e.Action)
{ {
case NotifyCollectionChangedAction.Add: // Add or Insert case NotifyCollectionChangedAction.Add: // Add or Insert
if (e.IsSingleItem) if (e.IsSingleItem)
{
if (e.NewStartingIndex == -1)
{
listView.Add(e.NewItem.View);
}
else
{ {
listView.Insert(e.NewStartingIndex, e.NewItem.View); listView.Insert(e.NewStartingIndex, e.NewItem.View);
} }
}
else else
{ {
if (e.NewStartingIndex == -1) using var array = new CloneCollection<TView>(e.NewViews);
{ listView.InsertRange(e.NewStartingIndex, array.AsEnumerable());
listView.AddRange(e.NewViews);
}
else
{
// fnew SortedList<int, int>().sort
listView.InsertRange(e.NewStartingIndex, e.NewViews);
}
} }
break; break;
case NotifyCollectionChangedAction.Remove: // Remove case NotifyCollectionChangedAction.Remove: // Remove
@ -74,26 +84,25 @@ namespace ObservableCollections
{ {
if (e.OldStartingIndex == -1) if (e.OldStartingIndex == -1)
{ {
var matcher = new RemoveAllMatcher<TView>(e.OldViews); foreach (var view in e.OldViews) // index is unknown, can't do batching
listView.RemoveAll(matcher.Predicate); {
listView.Remove(view);
}
} }
else else
{ {
listView.RemoveRange(e.OldStartingIndex, e.OldViews.Length); listView.RemoveRange(e.OldStartingIndex, e.OldViews.Length);
} }
} }
break; break;
case NotifyCollectionChangedAction.Replace: // Indexer case NotifyCollectionChangedAction.Replace: // Indexer
if (e.NewStartingIndex == -1) if (e.NewStartingIndex == -1)
{ {
var index = listView.IndexOf(e.OldItem.View); listView.TryReplaceByValue(e.OldItem.View, e.NewItem.View);
listView[index] = e.NewItem.View;
} }
else else
{ {
listView[e.NewStartingIndex] = e.NewItem.View; listView.TrySetAtAlternateIndex(e.NewStartingIndex, e.NewItem.View);
} }
break; break;
@ -109,41 +118,7 @@ namespace ObservableCollections
} }
break; break;
case NotifyCollectionChangedAction.Reset: // Clear or drastic changes case NotifyCollectionChangedAction.Reset: // Clear or drastic changes
if (e.SortOperation.IsNull) listView.Clear(IterateFilteredIndexedViewsOfParent()); // clear and fill refresh
{
listView.Clear();
foreach (var item in parent) // refresh
{
listView.Add(item);
}
}
else if (e.SortOperation.IsReverse)
{
listView.Reverse();
}
else
{
#if NET6_0_OR_GREATER
#pragma warning disable CS0436
if (parent is ObservableList<T>.View<TView> observableListView)
{
var comparer = new ObservableList<T>.View<TView>.IgnoreViewComparer(e.SortOperation.Comparer ?? Comparer<T>.Default);
var viewSpan = CollectionsMarshal.AsSpan(listView).Slice(e.SortOperation.Index, e.SortOperation.Count);
var sourceSpan = CollectionsMarshal.AsSpan(observableListView.list).Slice(e.SortOperation.Index, e.SortOperation.Count);
sourceSpan.Sort(viewSpan, comparer); // span.Sort is NET6 or greater
}
else
#pragma warning restore CS0436
#endif
{
// can not get source Span, do Clear and Refresh
listView.Clear();
foreach (var item in parent)
{
listView.Add(item);
}
}
}
break; break;
default: default:
break; break;
@ -199,13 +174,13 @@ namespace ObservableCollections
{ {
parent.ViewChanged -= Parent_ViewChanged; parent.ViewChanged -= Parent_ViewChanged;
} }
} }
internal class NotifyCollectionChangedSynchronizedView<T, TView> : internal class NotifyCollectionChangedSynchronizedView<T, TView> :
SynchronizedViewList<T, TView>, SynchronizedViewList<T, TView>,
INotifyCollectionChangedSynchronizedView<TView>, INotifyCollectionChangedSynchronizedView<TView>,
IList<TView>, IList IList<TView>, IList
{ {
static readonly PropertyChangedEventArgs CountPropertyChangedEventArgs = new("Count"); static readonly PropertyChangedEventArgs CountPropertyChangedEventArgs = new("Count");
static readonly Action<NotifyCollectionChangedEventArgs> raiseChangedEventInvoke = RaiseChangedEvent; static readonly Action<NotifyCollectionChangedEventArgs> raiseChangedEventInvoke = RaiseChangedEvent;
@ -444,5 +419,4 @@ namespace ObservableCollections
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
}
} }

View File

@ -97,4 +97,17 @@ public class AlternateIndexListTest
list.TryGetAtAlternateIndex(4, out var baz).Should().BeTrue(); list.TryGetAtAlternateIndex(4, out var baz).Should().BeTrue();
baz.Should().Be("new-baz"); baz.Should().Be("new-baz");
} }
[Fact]
public void TryReplaceByValue()
{
var list = new AlternateIndexList<string>();
list.Insert(0, "foo");
list.Insert(2, "bar");
list.Insert(4, "baz");
list.TryReplaceByValue("bar", "new-bar");
list.GetIndexedValues().Should().Equal((0, "foo"), (2, "new-bar"), (4, "baz"));
}
} }