From: Lucas Bajolet Date: Mon, 24 Mar 2014 18:03:43 +0000 (-0400) Subject: stdlib/strings: Abstracted hash (breaks hash on Buffer temporarily) X-Git-Tag: v0.6.5~7^2~3^2~3 X-Git-Url: http://nitlanguage.org stdlib/strings: Abstracted hash (breaks hash on Buffer temporarily) Signed-off-by: Lucas Bajolet --- diff --git a/lib/standard/string.nit b/lib/standard/string.nit index ecf7cf1..ff18a7d 100644 --- a/lib/standard/string.nit +++ b/lib/standard/string.nit @@ -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