using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace DataStructures.MoveToFrontListSpace
{
///
/// Moves most recently accessed element to the root
///
///
[Serializable]
public class MoveToFrontList : IEnumerable, ICollection
{
private List list;
private readonly object syncRoot = new object();
bool ICollection.Remove(T item)
{
var removedItem = ((ICollection) list).Remove(item);
return removedItem;
}
public int Count
{
get { return list.Count; }
}
public bool IsReadOnly { get; private set; }
public int Capacity
{
get { return list.Capacity; }
}
public object SyncRoot
{
get { return syncRoot; }
}
public bool IsSynchronized
{
get { return false; }
}
public MoveToFrontList()
{
list = new List();
}
public MoveToFrontList(int capacity)
{
Contract.Requires(capacity > 0);
list = new List(capacity);
}
///
/// Retrieves specific node and updates that node position
///
///
/// null if element isn't in the list
public T Get(T element)
{
Contract.Requires(element != null);
var node = list.FirstOrDefault(e => e.Equals(element));
if (node == null)
{
return default(T);
}
list.Remove(node);
list.Insert(0, node);
return node;
}
///
///
///
///
public void Add(T element)
{
Contract.Requires(element != null);
list.Add(element);
}
public void Clear()
{
list = new List();
}
public bool Contains(T item)
{
return list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
Contract.Requires(array != null, "array");
Contract.Requires(arrayIndex >= 0, "index");
Contract.Requires(arrayIndex <= Count);
var i = arrayIndex;
foreach (var element in list)
{
array.SetValue(element, i++);
}
}
///
/// Removes element from list, throws exception
///
///
public void Remove(T element)
{
Contract.Requires(element != null);
list.Remove(element);
}
public void CopyTo(Array array, int index)
{
Contract.Requires(array != null, "array");
Contract.Requires(index >= 0, "index");
Contract.Requires(index <= Count);
int i = index;
foreach (var element in list)
{
array.SetValue(element, i++);
}
}
public IEnumerator GetEnumerator()
{
return list.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public static class MoveToFrontListExtension
{
public static T[] CopyToArray(this MoveToFrontList self)
{
var returnedArray = new T[self.Count];
var count = 0;
foreach (var element in self)
{
returnedArray[count++] = element;
}
return returnedArray;
}
}
}