01: /*
02: * @(#)LRUcache.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.Context;
12: import pnuts.lang.PnutsFunction;
13: import org.pnuts.util.LRUCacheMap;
14: import org.pnuts.util.LRUCache;
15: import java.util.*;
16:
17: /**
18: * function LRUCache(size {, func(key)})
19: */
20: public class LRUcache extends PnutsFunction {
21:
22: public LRUcache() {
23: super ("LRUcache");
24: }
25:
26: public boolean defined(int nargs) {
27: return nargs == 1 || nargs == 2 || nargs == 3;
28: }
29:
30: public Object exec(Object[] args, final Context context) {
31: int nargs = args.length;
32: if (nargs == 1) {
33: int max = ((Integer) args[0]).intValue();
34: return new FixedSizedCache(max, null, null, context);
35: } else if (nargs == 2) {
36: int max = ((Integer) args[0]).intValue();
37: return new FixedSizedCache(max, (PnutsFunction) args[1],
38: null, context);
39: } else if (nargs == 3) {
40: int max = ((Integer) args[0]).intValue();
41: return new FixedSizedCache(max, (PnutsFunction) args[1],
42: (PnutsFunction) args[2], context);
43: } else {
44: undefined(args, context);
45: return null;
46: }
47: }
48:
49: static class FixedSizedCache extends LRUCacheMap {
50: PnutsFunction cf, df;
51: Context context;
52:
53: FixedSizedCache(int max, PnutsFunction cf, PnutsFunction df,
54: Context c) {
55: super (max);
56: this .cf = cf;
57: this .df = df;
58: this .context = c;
59: }
60:
61: protected Object construct(Object key) {
62: return cf.call(new Object[] { key }, context);
63: }
64:
65: public void expired(Object old) {
66: if (df != null) {
67: df.call(new Object[] { old }, context);
68: }
69: }
70: }
71:
72: public String toString() {
73: return "function LRUcache(size { , function(key) {, function (old)}})";
74: }
75: }
|