diff options
Diffstat (limited to 'source/lru.d')
-rw-r--r-- | source/lru.d | 63 |
1 files changed, 21 insertions, 42 deletions
diff --git a/source/lru.d b/source/lru.d index 6d802df..2e8da73 100644 --- a/source/lru.d +++ b/source/lru.d @@ -1,22 +1,18 @@ import std.array : appender; -private struct Node(T) -{ +private struct Node(T) { Node!T* prev; Node!T* next; T data; } -private struct List(T) -{ +private struct List(T) { Node!T* head; Node!T* tail; size_t length; - invariant () - { - if (length > 0) - { + invariant () { + if (length > 0) { assert(head !is null); assert(tail !is null); } @@ -37,8 +33,7 @@ private struct List(T) } }*/ - void remove(Node!T* n) - { + void remove(Node!T* n) { if (n.next) n.next.prev = n.prev; if (n.prev) @@ -50,8 +45,7 @@ private struct List(T) length--; } - void push(Node!T* n) - { + void push(Node!T* n) { n.prev = null; n.next = head; head = n; @@ -63,12 +57,10 @@ private struct List(T) } Node!T* pop() - in - { + in { assert(tail); } - do - { + do { Node!T* node = tail; remove(node); return node; @@ -76,8 +68,7 @@ private struct List(T) } -unittest -{ +unittest { List!int l; Node!int first; l.push(&first); @@ -95,60 +86,49 @@ unittest l.pop(); } -class LRUCache(From, To) -{ +class LRUCache(From, To) { private size_t _cap; - private struct Record - { + private struct Record { To val; From key; } private Node!Record*[From] map; private List!Record queue; - this(size_t cap) - { + this(size_t cap) { _cap = cap; } - private void checksz() - { - if (queue.length > _cap) - { + private void checksz() { + if (queue.length > _cap) { auto node = queue.pop(); map.remove(node.data.key); } } - bool opBinaryRight(string op : "in")(From key) - { + bool opBinaryRight(string op : "in")(From key) { return cast(bool)(key in map); } To opIndex(From f) - in - { + in { assert(f in map); } - do - { + do { auto p = map[f]; queue.remove(p); queue.push(p); return p.data.val; } - void opIndexAssign(To t, From f) - { + void opIndexAssign(To t, From f) { auto p = f in map; Node!Record* node; bool alloc = p is null; - if (!alloc) - { + if (!alloc) { queue.remove(*p); node = *p; - } - else + } else node = new Node!Record(); node.data.val = t; node.data.key = f; @@ -159,8 +139,7 @@ class LRUCache(From, To) } } -unittest -{ +unittest { auto cache = new LRUCache!(int, int)(2); cache[0] = 1; cache[4] = 2; |