lib/serialization: optimize `StrictHashMap` as a subclass of `HashMap`
authorAlexis Laferrière <alexis.laf@xymus.net>
Sat, 23 May 2015 17:51:57 +0000 (13:51 -0400)
committerAlexis Laferrière <alexis.laf@xymus.net>
Mon, 25 May 2015 15:50:15 +0000 (11:50 -0400)
Signed-off-by: Alexis Laferrière <alexis.laf@xymus.net>

lib/serialization/engine_tools.nit

index 1e0ee0b..33d36b4 100644 (file)
 module engine_tools
 
 import serialization
+intrude import standard::collection::hash_collection
 
-# Maps instances to a value, uses `is_same_instance`
-#
-# Warning: This class does not implement all the services from `Map`.
+# Maps instances to a value, uses `is_same_serialized` and `serialization_hash`.
 class StrictHashMap[K, V]
-       super Map[K, V]
-
-       # private
-       var map = new HashMap[K, Array[Couple[K, V]]]
-
-       redef var length = 0
-
-       redef fun is_empty do return length == 0
+       super HashMap[K, V]
 
-       # private
-       fun node_at(key: K): nullable Couple[K, V]
+       redef fun index_at(k)
        do
-               if not map.keys.has(key) then return null
-
-               var arr = map[key]
-               for couple in arr do
-                       if couple.first.is_same_serialized(key) then
-                               return couple
-                       end
-               end
+               if k == null then return 0
 
-               return null
+               var i = k.serialization_hash % _capacity
+               if i < 0 then i = - i
+               return i
        end
 
-       redef fun [](key)
+       redef fun node_at_idx(i, k)
        do
-               var node = node_at(key)
-               assert node != null
-               return node.second
-       end
-
-       redef fun []=(key, value)
-       do
-               var node = node_at(key)
-               if node != null then
-                       node.second = value
-                       return
+               var c = _array[i]
+               while c != null do
+                       var ck = c._key
+                       if ck.is_same_serialized(k) then
+                               break
+                       end
+                       c = c._next_in_bucklet
                end
-
-               var arr
-               if not map.keys.has(key) then
-                       arr = new Array[Couple[K, V]]
-                       map[key] = arr
-               else arr = map[key]
-
-               arr.add new Couple[K, V](key, value)
-               self.length += 1
+               return c
        end
-
-       redef fun has_key(key) do return node_at(key) != null
 end