1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 module hunt.shiro.cache.MapCache;
20 
21 import hunt.shiro.cache.Cache;
22 
23 // import java.util.Collection;
24 // import java.util.Collections;
25 // import java.util.Map;
26 // import java.util.Set;
27 
28 import hunt.Exceptions;
29 import hunt.util.StringBuilder;
30 
31 import std.array;
32 
33 /**
34  * A <code>MapCache</code> is a {@link Cache Cache} implementation that uses a backing {@link Map} instance to store
35  * and retrieve cached data.
36  *
37  * @since 1.0
38  */
39 class MapCache(K, V) : Cache!(K, V) {
40 
41     /**
42      * Backing instance.
43      */
44     private V[K] map;
45 
46     /**
47      * The name of this cache.
48      */
49     private string name;
50 
51     this(string name) {
52         if (name.empty) {
53             throw new IllegalArgumentException("Cache name cannot be null.");
54         }
55         // if (backingMap is null) {
56         //     throw new IllegalArgumentException("Backing map cannot be null.");
57         // }
58         this.name = name;
59         // this.map = backingMap;
60     }
61 
62     V get(K key) {
63         return map[key];
64     }
65 
66     V get(K key, V defaultValue) {
67         return map.get(key, defaultValue);
68     }
69 
70     bool contain(K key) {
71         auto itemPtr = key in map;
72         return itemPtr !is null;
73     }
74 
75     V put(K key, V value) {
76         return map[key] = value;
77     }
78 
79     V remove(K key) {
80         V v = map[key];
81         map.remove(key);
82         return v;
83     }
84 
85     void clear() {
86         map.clear();
87     }
88 
89     int size() {
90         return cast(int)map.length;
91     }
92 
93     K[] keys() {
94         return map.keys;
95     }
96 
97     V[] values() {
98         return map.values;
99     }
100 
101     override string toString() {
102         return new StringBuilder("MapCache '")
103                 .append(name).append("' (")
104                 .append(map.length)
105                 .append(" entries)")
106                 .toString();
107     }
108 }