Hash->HashMap, add Basket.Queue
[org.ibex.util.git] / src / org / ibex / util / Cache.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.util;
6
7 /** A HashMap with a fixed size; drops extraneous elements. Uses an
8  *  LRU strategy, either ordering elements based on insertion order
9  *  or access order.
10  *
11  *  @author crawshaw@ibex.org
12  */
13 public class Cache extends Basket.Hash {
14     public Cache(int maxSize, boolean accessOrder) {
15         super(maxSize * 2, 0.75F);
16     }
17     /*
18     private static final long serialVersionUID = 23498092L;
19
20     private final int maxSize;
21     private final boolean accessOrder;
22
23     private int[] prev;
24     private int[] next;
25     private int first = -1, last = -1;
26
27     public Cache(int maxSize, boolean accessOrder) {
28         super(maxSize * 2, 0.75F);
29
30         prev = new int[entries.length];
31         next = new int[entries.length];
32         for (int i=0; i < maxSize; i++) { prev[i] = next[i] = -1; }
33
34         this.maxSize = maxSize;
35         this.accessOrder = accessOrder;
36     }
37
38     public Object get(Object k) {
39         int i = indexOf(k);
40         if (i < 0) return null;
41         if (accessOrder) { // move to front of linked list
42             entryRemoved(i);
43             prev[i] = -1;
44             if (first >= 0) prev[first] = i;
45             next[i] = first;
46             first = i;
47         }
48         return entries[i + 1];
49     }
50
51     protected void entryAdded(int i) {
52         if (last >= 0) next[last] = i;
53         prev[i] = last >= 0 ? last : -1;
54         next[i] = -1;
55         int ourlast = accessOrder ? last : first;
56         last = i;
57         if (first < 0) first = last;
58         if (ourlast >= 0 && size > maxSize) remove(ourlast);
59     }
60
61     protected void entryRemoved(int i) {
62         if (prev[i] >= 0) next[prev[i]] = next[i];
63         if (next[i] >= 0) prev[next[i]] = prev[i];
64         if (last == i) last = prev[i] >= 0 ? prev[i] : -1;
65         if (first == i) first = next[i] >= 0 ? next[i] : -1;
66     }
67
68     protected void entryUpdated(int i) {
69         if (!accessOrder) { entryRemoved(i); entryAdded(i); }
70     }
71     */
72 }