ni_nitdoc: added fast copy past utility to signatures.
[nit.git] / src / more_collections.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Highly specific, but useful, collections-related classes.
16 module more_collections
17
18 # Simple way to store an HashMap[K, Array[V]]
19 class MultiHashMap[K: Object, V]
20 super HashMap[K, Array[V]]
21
22 # Add `v' to the array associated with `k'.
23 # If there is no array associated, then create it.
24 fun add_one(k: K, v: V)
25 do
26 if self.has_key(k) then
27 self[k].add(v)
28 else
29 self[k] = [v]
30 end
31 end
32
33 init do end
34 end
35
36 # Simple way to store an HashMap[K1, HashMap[K2, V]]
37 class HashMap2[K1: Object, K2: Object, V]
38 private var level1: HashMap[K1, HashMap[K2, V]] = new HashMap[K1, HashMap[K2, V]]
39
40 # Return the value associated to the keys `k1` and `k2`.
41 # Return `null` if no such a value.
42 fun [](k1: K1, k2: K2): nullable V
43 do
44 var level1 = self.level1
45 if not level1.has_key(k1) then return null
46 var level2 = level1[k1]
47 if not level2.has_key(k2) then return null
48 return level2[k2]
49 end
50
51 # Set `v` the value associated to the keys `k1` and `k2`.
52 fun []=(k1: K1, k2: K2, v: V)
53 do
54 var level1 = self.level1
55 var level2: HashMap[K2, V]
56 if not level1.has_key(k1) then
57 level2 = new HashMap[K2, V]
58 level1[k1] = level2
59 else
60 level2 = level1[k1]
61 end
62 level2[k2] = v
63 end
64 end
65
66 # Simple way to store an HashMap[K1, HashMap[K2, HashMap[K3, V]]]
67 class HashMap3[K1: Object, K2: Object, K3: Object, V]
68 private var level1: HashMap[K1, HashMap2[K2, K3, V]] = new HashMap[K1, HashMap2[K2, K3, V]]
69
70 # Return the value associated to the keys `k1`, `k2`, and `k3`.
71 # Return `null` if no such a value.
72 fun [](k1: K1, k2: K2, k3: K3): nullable V
73 do
74 var level1 = self.level1
75 if not level1.has_key(k1) then return null
76 var level2 = level1[k1]
77 return level2[k2, k3]
78 end
79
80 # Set `v` the value associated to the keys `k1`, `k2`, and `k3`.
81 fun []=(k1: K1, k2: K2, k3: K3, v: V)
82 do
83 var level1 = self.level1
84 var level2: HashMap2[K2, K3, V]
85 if not level1.has_key(k1) then
86 level2 = new HashMap2[K2, K3, V]
87 level1[k1] = level2
88 else
89 level2 = level1[k1]
90 end
91 level2[k2, k3] = v
92 end
93 end