ln.types/odb/PersistentList.cs

166 lines
4.3 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
namespace ln.types.odb
{
public class PersistentList<T> : IList<T> where T: IPersistent
{
private Dictionary<Guid, T> persistentInstances = new Dictionary<Guid, T>();
private List<Guid> index = new List<Guid>();
public ODB ODB { get; }
public PersistentList(ODB odb)
{
ODB = odb;
}
public T this[int n]
{
get {
Guid persistentID = index[n];
if (!persistentInstances.ContainsKey(persistentID))
persistentInstances[persistentID] = (T)ODB.LoadPersistent(persistentID);
return persistentInstances[persistentID];
}
set {
if (value == null)
index[n] = Guid.Empty;
Guid persistenceID = value.GetPersistenceID();
persistentInstances[persistenceID] = value;
index[n] = persistenceID;
}
}
public int Count => index.Count;
public bool IsReadOnly => false;
public void Add(T item)
{
if (item == null)
{
index.Add(Guid.Empty);
}
else
{
Guid persistenceID = item.GetPersistenceID();
persistentInstances[persistenceID] = item;
index.Add(persistenceID);
}
}
public void Clear()
{
persistentInstances.Clear();
index.Clear();
}
public bool Contains(T item)
{
Guid persistenceID = item.GetPersistenceID();
if (index.Contains(persistenceID))
return true;
foreach (T mine in this)
{
if (mine.Equals(item))
return true;
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
foreach (T item in this)
{
array[arrayIndex] = this[arrayIndex];
arrayIndex++;
}
}
public IEnumerator<T> GetEnumerator()
{
return new PersistentListEnumerator(this);
}
public int IndexOf(T item)
{
Guid persistenceID = item == null ? Guid.Empty : item.GetPersistenceID();
int i = index.IndexOf(persistenceID);
if (i < 0)
{
for (int n=0;n<Count;n++)
{
if (this[n].Equals(item))
return n;
}
}
return -1;
}
public void Insert(int _index, T item)
{
Guid persistenceID = item == null ? Guid.Empty : item.GetPersistenceID();
index.Insert(_index, persistenceID);
persistentInstances[persistenceID] = item;
}
public bool Remove(T item)
{
int ind = IndexOf(item);
if (ind >= 0)
RemoveAt(ind);
return ind >= 0;
}
public void RemoveAt(int _index)
{
Guid persistenceID = index[_index];
if (persistentInstances.ContainsKey(persistenceID))
persistentInstances.Remove(persistenceID);
index.RemoveAt(_index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new PersistentListEnumerator(this);
}
class PersistentListEnumerator : IEnumerator<T>
{
int currentIndex = -1;
PersistentList<T> persistentList;
public PersistentListEnumerator(PersistentList<T> persistentList)
{
this.persistentList = persistentList;
}
public T Current => persistentList[currentIndex];
object IEnumerator.Current => persistentList[currentIndex];
public void Dispose()
{
persistentList = null;
}
public bool MoveNext()
{
currentIndex++;
return (currentIndex < persistentList.Count);
}
public void Reset()
{
currentIndex = -1;
}
}
}
}