1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Highly specific, but useful, collections-related classes.
16 module more_collections
is serialize
21 # Simple way to store an `HashMap[K, Array[V]]`
23 # Unlike standard HashMap, MultiHashMap provides a new
24 # empty array on the first access on a unknown key.
26 # var m = new MultiHashMap[String, Char]
27 # assert not m.has_key("four")
32 # assert m.has_key("four")
33 # assert m["four"] == ['i', 'i', 'i', 'i']
34 # assert m["zzz"] == new Array[Char]
35 class MultiHashMap[K
, V
]
36 super HashMap[K
, Array[V
]]
38 # Add `v` to the array associated with `k`.
40 # If there is no array associated, then create it.
42 # For the inverse operation, see `remove_one`.
45 # var m = new MultiHashMap[String, Char]
46 # m.add_one("four", 'i')
47 # m.add_one("four", 'i')
48 # m.add_one("four", 'i')
49 # m.add_one("four", 'i')
50 # assert m.has_key("four")
51 # assert m["four"] == ['i', 'i', 'i', 'i']
53 fun add_one
(k
: K
, v
: V
)
55 var x
= self.get_or_null
(k
)
63 redef fun provide_default_value
(key
) do
64 var res
= new Array[V
]
69 # Remove an occurrence of `v` from the array associated with `k`.
71 # If the associated array does not contain `v`, do nothing. If the
72 # associated array only contain one element and this element is `v`, remove
75 # In a nutshell, does the inverse operation of `add_one`.
78 # var m = new MultiHashMap[String, Char]
79 # m["four"] = ['4', 'i', 'i', 'i', 'i']
80 # m.remove_one("four", 'i')
81 # assert m["four"] == ['4', 'i', 'i', 'i']
83 # m = new MultiHashMap[String, Char]
84 # m.add_one("one", '1')
85 # m.remove_one("one", '?')
86 # assert m["one"] == ['1']
87 # m.remove_one("one", '1')
88 # assert not m.has_key("one")
89 # assert m["one"] == new Array[Char]
91 # m = new MultiHashMap[String, Char]
92 # m.add_one("one", '1')
93 # m.remove_one("two", '2')
94 # assert not m.has_key("two")
95 # assert m["one"] == ['1']
96 # assert m["two"] == new Array[Char]
98 fun remove_one
(k
: K
, v
: V
)
100 var x
= get_or_null
(k
)
103 if x
.is_empty
then keys
.remove
(k
)
107 # Search the values in `pe.greaters` from the most smaller elements that have a value.
109 # Elements without values are ignored.
111 # Basically, values defined in nearest greater elements of `pe` are inherited.
114 # var pos = new POSet[String]
115 # pos.add_chain(["E", "D", "C", "B", "A"])
116 # pos.add_chain(["D", "X", "B"])
118 # var map = new MultiHashMap[String, String]
119 # map["A"].append(["a", "1"])
120 # map["C"].append(["c", "2"])
121 # map["X"].append(["x", "2"])
124 # assert map.lookup_joined_values(pos["B"]).has_exactly(["a", "1"])
125 # assert map.lookup_joined_values(pos["C"]).has_exactly(["c", "2"])
126 # assert map.lookup_joined_values(pos["D"]).has_exactly(["c", "x", "2"])
128 fun lookup_joined_values
(pe
: POSetElement[K
]): Set[V
]
131 for k
in pe
.poset
.select_smallest
(filter_keys
(pe
.greaters
)) do res
.add_all
self[k
]
137 # Simple way to store an `HashMap[K1, HashMap[K2, V]]`
140 # var hm2 = new HashMap2[Int, String, Float]
141 # hm2[1, "one"] = 1.0
142 # hm2[2, "two"] = 2.0
143 # assert hm2[1, "one"] == 1.0
144 # assert hm2[2, "not-two"] == null
146 class HashMap2[K1, K2, V
]
148 private var level1
= new HashMap[K1, HashMap[K2, V
]]
150 # Return the value associated to the keys `k1` and `k2`.
151 # Return `null` if no such a value.
152 fun [](k1
: K1, k2
: K2): nullable V
154 var level1
= self.level1
155 var level2
= level1
.get_or_null
(k1
)
156 if level2
== null then return null
157 return level2
.get_or_null
(k2
)
160 # Set `v` the value associated to the keys `k1` and `k2`.
161 fun []=(k1
: K1, k2
: K2, v
: V
)
163 var level1
= self.level1
164 var level2
= level1
.get_or_null
(k1
)
165 if level2
== null then
166 level2
= new HashMap[K2, V
]
172 # Remove the item at `k1` and `k2`
173 fun remove_at
(k1
: K1, k2
: K2)
175 var level1
= self.level1
176 var level2
= level1
.get_or_null
(k1
)
177 if level2
== null then return
178 level2
.keys
.remove
(k2
)
181 # Is there a value at `k1, k2`?
182 fun has
(k1
: K1, k2
: K2): Bool
184 if not level1
.keys
.has
(k1
) then return false
185 return level1
[k1
].keys
.has
(k2
)
189 fun clear
do level1
.clear
192 # Simple way to store an `HashMap[K1, HashMap[K2, HashMap[K3, V]]]`
195 # var hm3 = new HashMap3[Int, String, Int, Float]
196 # hm3[1, "one", 11] = 1.0
197 # hm3[2, "two", 22] = 2.0
198 # assert hm3[1, "one", 11] == 1.0
199 # assert hm3[2, "not-two", 22] == null
201 class HashMap3[K1, K2, K3, V
]
203 private var level1
= new HashMap[K1, HashMap2[K2, K3, V
]]
205 # Return the value associated to the keys `k1`, `k2`, and `k3`.
206 # Return `null` if no such a value.
207 fun [](k1
: K1, k2
: K2, k3
: K3): nullable V
209 var level1
= self.level1
210 var level2
= level1
.get_or_null
(k1
)
211 if level2
== null then return null
212 return level2
[k2
, k3
]
215 # Set `v` the value associated to the keys `k1`, `k2`, and `k3`.
216 fun []=(k1
: K1, k2
: K2, k3
: K3, v
: V
)
218 var level1
= self.level1
219 var level2
= level1
.get_or_null
(k1
)
220 if level2
== null then
221 level2
= new HashMap2[K2, K3, V
]
227 # Remove the item at `k1`, `k2` and `k3`
228 fun remove_at
(k1
: K1, k2
: K2, k3
: K3)
230 var level1
= self.level1
231 var level2
= level1
.get_or_null
(k1
)
232 if level2
== null then return
233 level2
.remove_at
(k2
, k3
)
236 # Is there a value at `k1, k2, k3`?
237 fun has
(k1
: K1, k2
: K2, k3
: K3): Bool
239 if not level1
.keys
.has
(k1
) then return false
240 return level1
[k1
].has
(k2
, k3
)
244 fun clear
do level1
.clear
247 # A map with a default value.
250 # var dm = new DefaultMap[String, Int](10)
251 # assert dm["a"] == 10
254 # The default value is used when the key is not present.
255 # And getting a default value does not register the key.
258 # assert dm["a"] == 10
259 # assert dm.length == 0
260 # assert dm.has_key("a") == false
263 # It also means that removed key retrieve the default value.
267 # assert dm["a"] == 2
268 # dm.keys.remove("a")
269 # assert dm["a"] == 10
272 # Warning: the default value is used as is, so using mutable object might
273 # cause side-effects.
276 # var dma = new DefaultMap[String, Array[Int]](new Array[Int])
279 # assert dma["a"] == [65]
280 # assert dma.default == [65]
281 # assert dma["c"] == [65]
284 # assert dma["b"] == [65, 66]
285 # assert dma.default == [65]
287 class DefaultMap[K
, V
]
293 redef fun provide_default_value
(key
) do return default
296 # An unrolled linked list
298 # A sequence implemented as a linked list of arrays.
300 # This data structure is similar to the `List` but it can benefit from
301 # better cache performance, lower data overhead for the nodes metadata and
302 # it spares the GC to allocate many small nodes.
303 class UnrolledList[E
]
306 # Desired capacity for each nodes
308 # By default at `32`, it can be increased for very large lists.
310 # It can be modified anytime, but newly created nodes may still be assigned
311 # the same capacity of old nodes when created by `insert`.
312 var nodes_length
= 32 is writable
314 private var head_node
: UnrolledNode[E
] = new UnrolledNode[E
](nodes_length
)
316 private var tail_node
: UnrolledNode[E
] = head_node
322 head_node
= new UnrolledNode[E
](nodes_length
)
323 tail_node
= head_node
327 # Out parameter of `node_at`
328 private var index_within_node
= 0
330 private fun node_at
(index
: Int): UnrolledNode[E
]
332 assert index
>= 0 and index
< length
335 while index
>= node
.length
do
337 node
= node
.next
.as(not null)
340 index_within_node
= index
344 private fun insert_node
(node
: UnrolledNode[E
], prev
, next
: nullable UnrolledNode[E
])
348 else head_node
= node
352 else tail_node
= node
360 var node
= node_at
(index
)
361 index
= index_within_node
+ node
.head_index
362 return node
.items
[index
]
365 redef fun []=(index
, value
)
367 var node
= node_at
(index
)
368 index
= index_within_node
+ node
.head_index
369 node
.items
[index
] = value
375 if not node
.full
then
376 if node
.tail_index
< node
.capacity
then
377 # There's room at the tail
380 # Move everything over by `d`
381 assert node
.head_index
> 0
382 var d
= node
.head_index
/ 2 + 1
383 node
.move_head
(node
.length
, d
)
384 for i
in d
.times
do node
.items
[node
.tail_index
- i
] = null
386 node
.tail_index
+= -d
+1
388 node
.items
[node
.tail_index-1
] = item
391 node
= new UnrolledNode[E
](nodes_length
)
392 insert_node
(node
, tail_node
, null)
399 redef fun unshift
(item
)
402 if not node
.full
then
403 if node
.head_index
> 0 then
404 # There's room at the head
407 # Move everything over by `d`
408 assert node
.tail_index
< node
.capacity
409 var d
= (node
.capacity-node
.tail_index
) / 2 + 1
411 for i
in d
.times
do node
.items
[node
.head_index
+i
] = null
412 node
.head_index
+= d-1
415 node
.items
[node
.head_index
] = item
418 node
= new UnrolledNode[E
](nodes_length
)
419 insert_node
(node
, null, head_node
)
420 node
.head_index
= node
.capacity-1
421 node
.tail_index
= node
.capacity
422 node
.items
[node
.capacity-1
] = item
432 while node
.length
== 0 do
434 var nullable_node
= node
.prev
435 assert is_not_empty
: nullable_node
!= null
438 self.tail_node
= node
441 var item
= node
.items
[node
.tail_index-1
]
452 while node
.length
== 0 do
454 var nullable_node
= node
.next
455 assert is_not_empty
: nullable_node
!= null
458 self.head_node
= node
461 var item
= node
.items
[node
.head_index
]
467 redef fun insert
(item
, index
)
469 if index
== length
then
474 var node
= node_at
(index
)
475 index
= index_within_node
477 # Move half to a new node
478 var new_node
= new UnrolledNode[E
](nodes_length
.max
(node
.capacity
))
480 # Plug in the new node
481 var next_node
= node
.next
482 insert_node
(new_node
, node
, next_node
)
484 # Move items at and after `index` to the new node
485 var to_displace
= node
.length-index
486 var offset
= (new_node
.capacity-to_displace
)/2
487 for i
in [0..to_displace
[ do
488 new_node
.items
[offset
+i
] = node
.items
[index
+i
]
489 node
.items
[index
+i
] = null
491 new_node
.head_index
= offset
492 new_node
.tail_index
= offset
+ to_displace
493 node
.tail_index
-= to_displace
496 if index
> node
.capacity
/ 2 then
497 new_node
.items
[offset-1
] = item
498 new_node
.head_index
-= 1
500 node
.items
[node
.head_index
+index
] = item
504 if node
.tail_index
< node
.capacity
then
505 # Move items towards the tail
506 node
.move_tail
(index
, 1)
508 node
.items
[node
.head_index
+ index
] = item
510 # Move items towards the head
511 node
.move_head
(index
, 1)
512 node
.items
[node
.head_index
+ index-1
] = item
519 redef fun remove_at
(index
)
521 var node
= node_at
(index
)
522 index
= index_within_node
+ node
.head_index
524 # Shift left all the elements after `index`
525 for i
in [index
+1 .. node
.tail_index
[ do
526 node
.items
[i-1
] = node
.items
[i
]
529 node
.items
[node
.tail_index
] = null
533 var next_node
= node
.next
534 var prev_node
= node
.prev
535 if node
.is_empty
and (next_node
!= null or prev_node
!= null) then
536 # Empty and non-head or tail node, delete
537 if next_node
!= null then
538 next_node
.prev
= node
.prev
539 else tail_node
= prev_node
.as(not null)
541 if prev_node
!= null then
542 prev_node
.next
= node
.next
543 else head_node
= next_node
.as(not null)
547 redef fun iterator
do return new UnrolledIterator[E
](self)
550 # Node composing an `UnrolledList`
552 # Stores the elements in the `items` array. The elements in the `items` array
553 # begin at `head_index` and end right before `tail_index`. The data is contiguous,
554 # but there can be empty cells at the beginning and the end of the array.
555 private class UnrolledNode[E
]
557 var prev
: nullable UnrolledNode[E
] = null
559 var next
: nullable UnrolledNode[E
] = null
561 # Desired length of `items`
564 # `Array` of items in this node, filled with `null`
565 var items
= new Array[nullable E
].filled_with
(null, capacity
) is lazy
567 # Index of the first element in `items`
570 # Index after the last element in `items`
573 fun length
: Int do return tail_index
- head_index
575 fun full
: Bool do return length
== capacity
577 fun is_empty
: Bool do return tail_index
== head_index
579 # Move towards the head all elements before `index` of `displace` cells
580 fun move_tail
(index
, displace
: Int)
582 for i
in [tail_index-1
..head_index
+index
].step
(-1) do
583 items
[i
+displace
] = items
[i
]
587 # Move towards the tail all elements at and after `index` of `displace` cells
588 fun move_head
(index
, displace
: Int)
590 for i
in [head_index
..head_index
+index
[ do
591 items
[i-displace
] = items
[i
]
596 private class UnrolledIterator[E
]
597 super IndexedIterator[E
]
599 var list
: UnrolledList[E
]
601 var node
: nullable UnrolledNode[E
] = list
.head_node
is lazy
603 # Index of the current `item`
606 # Index within the current `node`
607 var index_in_node
: Int = node
.head_index
is lazy
609 redef fun item
do return node
.items
[index_in_node
]
611 redef fun is_ok
do return index
< list
.length
618 if index_in_node
>= node
.tail_index
then
620 if node
!= null then index_in_node
= node
.head_index
625 # Keep track of the best elements according to a distance value.
628 # var bests = new BestDistance[String](5)
629 # bests.update(10, "Too big")
630 # assert bests.best_items.is_empty
631 # bests.update(5, "Just fine")
632 # bests.update(5, "Another one")
633 # assert bests.best_items.has_exactly(["Just fine", "Another one"])
634 # bests.update(2, "A better one")
635 # bests.update(4, "Not good enough")
636 # assert bests.best_distance == 2
637 # assert bests.best_items.has_exactly(["A better one"])
639 class BestDistance[E
]
640 # Current smallest distance
641 var best_distance
: Int is writable
643 # Known elements with the smallest distance
644 var best_items
= new Set[E
] is writable
646 # Register a `candidate` with a `distance`
648 # * To high, it is ignored.
649 # * Equal to the current best, it is added
650 # * Better that them, is is the new best element
652 # Return `true` if the candidate is kept (alone or with other)
653 # returns `false` if the candidate is ignored.
654 fun update
(distance
: Int, candidate
: E
): Bool
656 if distance
> best_distance
then return false
657 if distance
< best_distance
then
658 best_distance
= distance
661 best_items
.add candidate