Added tests for LRUCache.
Moved core test code to reflect changes in core code. Removed unused using directives.
This commit is contained in:
@@ -1,77 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GameServiceWarden.Core.Module
|
||||
{
|
||||
public class LRUCache<K, V>
|
||||
{
|
||||
private class Node
|
||||
{
|
||||
public K key;
|
||||
public V value;
|
||||
public Node front;
|
||||
public Node back;
|
||||
}
|
||||
|
||||
public int Size {get { return size; } }
|
||||
public int Length {get { return valueDictionary.Count; } }
|
||||
private readonly int size;
|
||||
private Node top;
|
||||
private Node bottom;
|
||||
private Dictionary<K, Node> valueDictionary;
|
||||
private Action<V> cleanupAction;
|
||||
|
||||
public LRUCache(int size = 100, Action<V> cleanup = null)
|
||||
{
|
||||
this.size = size;
|
||||
valueDictionary = new Dictionary<K, Node>(size);
|
||||
this.cleanupAction = cleanup;
|
||||
}
|
||||
|
||||
private void MoveToTop(K key) {
|
||||
Node node = valueDictionary[key];
|
||||
if (node != null && top != node) {
|
||||
node.front.back = node.back;
|
||||
node.back = top;
|
||||
node.front = null;
|
||||
top = node;
|
||||
}
|
||||
}
|
||||
|
||||
private Node AddToTop(K key, V value) {
|
||||
Node node = new Node();
|
||||
node.front = null;
|
||||
node.back = top;
|
||||
node.value = value;
|
||||
node.key = key;
|
||||
top = node;
|
||||
if (bottom == null) {
|
||||
bottom = node;
|
||||
} else if (valueDictionary.Count == Size) {
|
||||
valueDictionary.Remove(bottom.key);
|
||||
cleanupAction(bottom.value);
|
||||
bottom = bottom.front;
|
||||
}
|
||||
valueDictionary[key] = node;
|
||||
return node;
|
||||
}
|
||||
|
||||
public V Use(K key, Func<V> generate) {
|
||||
if (generate == null) throw new ArgumentNullException("generate");
|
||||
Node value = null;
|
||||
if (valueDictionary.ContainsKey(key)) {
|
||||
value = valueDictionary[key];
|
||||
MoveToTop(key);
|
||||
} else {
|
||||
value = AddToTop(key, generate());
|
||||
}
|
||||
return value.value;
|
||||
}
|
||||
|
||||
public void Clear() {
|
||||
top = null;
|
||||
bottom = null;
|
||||
valueDictionary.Clear();
|
||||
}
|
||||
}
|
||||
}
|
@@ -2,14 +2,10 @@ using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Linq;
|
||||
using GameServiceWarden.API.Games;
|
||||
using GameServiceWarden.Core.Persistence;
|
||||
using GameServiceWarden.API.Module;
|
||||
using System.Text;
|
||||
using GameServiceWarden.Core.Collection;
|
||||
|
||||
namespace GameServiceWarden.Core.Module
|
||||
{
|
||||
|
Reference in New Issue
Block a user