4 using System.Collections;
5 using System.Collections.Generic;
6 using System.Collections.Specialized;
7 using System.Runtime.InteropServices;
8 using SiliconStudio.Core.Serialization.Serializers;
10 namespace SiliconStudio.Core.Collections
17 public abstract class KeyedSortedList<TKey, T> : IList<T>
29 comparer = Comparer<TKey>.Default;
31 this.comparer = comparer;
39 protected abstract TKey GetKeyForItem(T item);
48 items.Insert(index, item);
57 items.RemoveAt(index);
61 public void Add(T item)
63 var key = GetKeyForItem(item);
65 var index = BinarySearch(key);
67 throw new InvalidOperationException(
"An item with the same key has already been added.");
69 InsertItem(~index, item);
74 return BinarySearch(key) >= 0;
79 var index = BinarySearch(key);
89 public T
this[
int index]
91 get {
return items[index]; }
92 set { items[index] = value; }
95 public T
this[TKey key]
99 int index = BinarySearch(key);
101 throw new KeyNotFoundException();
106 int index = BinarySearch(key);
108 items[index] = value;
110 items.Insert(~index, value);
123 return items.Contains(item);
129 throw new NotImplementedException();
135 throw new NotImplementedException();
141 get {
return items.Count; }
145 public bool IsReadOnly
147 get {
return false; }
153 return items.IndexOf(item);
157 void IList<T>.Insert(
int index, T item)
159 throw new NotImplementedException();
165 items.RemoveAt(index);
171 return new Enumerator(items);
175 IEnumerator IEnumerable.GetEnumerator()
177 return new Enumerator(items);
182 return new Enumerator(items);
187 var values = items.Items;
189 int end = items.Count - 1;
193 int middle = start + ((end - start) >> 1);
194 var itemKey = GetKeyForItem(values[middle]);
196 var compareResult = comparer.Compare(itemKey, searchKey);
198 if (compareResult == 0)
202 if (compareResult < 0)
214 #region Nested type: Enumerator
216 [StructLayout(LayoutKind.Sequential)]
217 public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
227 current =
default(T);
236 if (index < list.
Count)
238 current = list.Items[index];
242 return MoveNextRare();
245 private bool MoveNextRare()
247 index = list.Count + 1;
248 current =
default(T);
254 get {
return current; }
257 object IEnumerator.Current
259 get {
return Current; }
262 void IEnumerator.Reset()
265 current =
default(T);
int BinarySearch(TKey searchKey)
Enumerator GetEnumerator()
virtual void RemoveItem(int index)
Called every time an item should be removed at a given index.
virtual void InsertItem(int index, T item)
Called every time an item should be added at a given index.
KeyedSortedList(IComparer< TKey > comparer)