stdlib/strings: Abstracted hash (breaks hash on Buffer temporarily)
authorLucas Bajolet <r4pass@hotmail.com>
Mon, 24 Mar 2014 18:03:43 +0000 (14:03 -0400)
committerLucas Bajolet <r4pass@hotmail.com>
Tue, 25 Mar 2014 19:42:21 +0000 (15:42 -0400)
Signed-off-by: Lucas Bajolet <r4pass@hotmail.com>

lib/standard/string.nit

index ecf7cf1..ff18a7d 100644 (file)
@@ -38,6 +38,8 @@ abstract class Text
        # Type of self (used for factorization of several methods, ex : substring_from, empty...)
        type SELFTYPE: Text
 
+       var hash_cache: nullable Int = null
+
        # Gets a view on the chars of the Text object
        fun chars: SELFVIEW is abstract
 
@@ -462,6 +464,23 @@ abstract class Text
        # Flat representation of self
        fun flatten: FlatText is abstract
 
+       redef fun hash
+       do
+               if hash_cache == null then
+                       # djb2 hash algorithm
+                       var h = 5381
+                       var i = length - 1
+
+                       for char in self.chars do
+                               h = (h * 32) + h + char.ascii
+                               i -= 1
+                       end
+
+                       hash_cache = h
+               end
+               return hash_cache.as(not null)
+       end
+
 end
 
 # All kinds of array-based text representations.
@@ -872,21 +891,25 @@ class FlatString
 
        redef fun hash
        do
-               # djb2 hash algorythm
-               var h = 5381
-               var i = length - 1
+               if hash_cache == null then
+                       # djb2 hash algorythm
+                       var h = 5381
+                       var i = length - 1
 
-               var myitems = items
-               var strStart = index_from
+                       var myitems = items
+                       var strStart = index_from
 
-               i += strStart
+                       i += strStart
+
+                       while i >= strStart do
+                               h = (h * 32) + h + self.items[i].ascii
+                               i -= 1
+                       end
 
-               while i >= strStart do
-                       h = (h * 32) + h + self.items[i].ascii
-                       i -= 1
+                       hash_cache = h
                end
 
-               return h
+               return hash_cache.as(not null)
        end
 end