# 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
# 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.
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