Fix haddock docs in Hashtable
[ghc-base.git] / Data / HashTable.hs
1 {-# OPTIONS_GHC -fno-implicit-prelude #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  Data.HashTable
6 -- Copyright   :  (c) The University of Glasgow 2003
7 -- License     :  BSD-style (see the file libraries/base/LICENSE)
8 --
9 -- Maintainer  :  libraries@haskell.org
10 -- Stability   :  provisional
11 -- Portability :  portable
12 --
13 -- An implementation of extensible hash tables, as described in
14 -- Per-Ake Larson, /Dynamic Hash Tables/, CACM 31(4), April 1988,
15 -- pp. 446--457.  The implementation is also derived from the one
16 -- in GHC's runtime system (@ghc\/rts\/Hash.{c,h}@).
17 --
18 -----------------------------------------------------------------------------
19
20 module Data.HashTable (
21         -- * Basic hash table operations
22         HashTable, new, insert, delete, lookup, update,
23         -- * Converting to and from lists
24         fromList, toList,
25         -- * Hash functions
26         -- $hash_functions
27         hashInt, hashString,
28         prime,
29         -- * Diagnostics
30         longestChain
31  ) where
32
33 -- This module is imported by Data.Dynamic, which is pretty low down in the
34 -- module hierarchy, so don't import "high-level" modules
35
36 #ifdef __GLASGOW_HASKELL__
37 import GHC.Base
38 #else
39 import Prelude  hiding  ( lookup )
40 #endif
41 import Data.Tuple       ( fst )
42 import Data.Bits
43 import Data.Maybe
44 import Data.List        ( maximumBy, length, concat, foldl', partition )
45 import Data.Int         ( Int32 )
46
47 #if defined(__GLASGOW_HASKELL__)
48 import GHC.Num
49 import GHC.Real         ( fromIntegral )
50 import GHC.Show         ( Show(..) )
51 import GHC.Int          ( Int64 )
52
53 import GHC.IOBase       ( IO, IOArray, newIOArray,
54                           unsafeReadIOArray, unsafeWriteIOArray, unsafePerformIO,
55                           IORef, newIORef, readIORef, writeIORef )
56 #else
57 import Data.Char        ( ord )
58 import Data.IORef       ( IORef, newIORef, readIORef, writeIORef )
59 import System.IO.Unsafe ( unsafePerformIO )
60 import Data.Int         ( Int64 )
61 #  if defined(__HUGS__)
62 import Hugs.IOArray     ( IOArray, newIOArray,
63                           unsafeReadIOArray, unsafeWriteIOArray )
64 #  elif defined(__NHC__)
65 import NHC.IOExtras     ( IOArray, newIOArray, readIOArray, writeIOArray )
66 #  endif
67 #endif
68 import Control.Monad    ( mapM, mapM_, sequence_ )
69
70
71 -----------------------------------------------------------------------
72
73 iNSTRUMENTED :: Bool
74 iNSTRUMENTED = False
75
76 -----------------------------------------------------------------------
77
78 readHTArray  :: HTArray a -> Int32 -> IO a
79 writeMutArray :: MutArray a -> Int32 -> a -> IO ()
80 freezeArray  :: MutArray a -> IO (HTArray a)
81 thawArray    :: HTArray a -> IO (MutArray a)
82 newMutArray   :: (Int32, Int32) -> a -> IO (MutArray a)
83 #if defined(DEBUG) || defined(__NHC__)
84 type MutArray a = IOArray Int32 a
85 type HTArray a = MutArray a
86 newMutArray = newIOArray
87 readHTArray  = readIOArray
88 writeMutArray = writeIOArray
89 freezeArray = return
90 thawArray = return
91 #else
92 type MutArray a = IOArray Int32 a
93 type HTArray a = MutArray a -- Array Int32 a
94 newMutArray = newIOArray
95 readHTArray arr i = readMutArray arr i -- return $! (unsafeAt arr (fromIntegral i))
96 readMutArray  :: MutArray a -> Int32 -> IO a
97 readMutArray arr i = unsafeReadIOArray arr (fromIntegral i)
98 writeMutArray arr i x = unsafeWriteIOArray arr (fromIntegral i) x
99 freezeArray = return -- unsafeFreeze
100 thawArray = return -- unsafeThaw
101 #endif
102
103 data HashTable key val = HashTable {
104                                      cmp     :: !(key -> key -> Bool),
105                                      hash_fn :: !(key -> Int32),
106                                      tab     :: !(IORef (HT key val))
107                                    }
108 -- TODO: the IORef should really be an MVar.
109
110 data HT key val
111   = HT {
112         kcount  :: !Int32,              -- Total number of keys.
113         bmask   :: !Int32,
114         buckets :: !(HTArray [(key,val)])
115        }
116
117 -- ------------------------------------------------------------
118 -- Instrumentation for performance tuning
119
120 -- This ought to be roundly ignored after optimization when
121 -- iNSTRUMENTED=False.
122
123 -- STRICT version of modifyIORef!
124 modifyIORef :: IORef a -> (a -> a) -> IO ()
125 modifyIORef r f = do
126   v <- readIORef r
127   let z = f v in z `seq` writeIORef r z
128
129 data HashData = HD {
130   tables :: !Integer,
131   insertions :: !Integer,
132   lookups :: !Integer,
133   totBuckets :: !Integer,
134   maxEntries :: !Int32,
135   maxChain :: !Int,
136   maxBuckets :: !Int32
137 } deriving (Eq, Show)
138
139 {-# NOINLINE hashData #-}
140 hashData :: IORef HashData
141 hashData =  unsafePerformIO (newIORef (HD { tables=0, insertions=0, lookups=0,
142                                             totBuckets=0, maxEntries=0,
143                                             maxChain=0, maxBuckets=tABLE_MIN } ))
144
145 instrument :: (HashData -> HashData) -> IO ()
146 instrument i | iNSTRUMENTED = modifyIORef hashData i
147              | otherwise    = return ()
148
149 recordNew :: IO ()
150 recordNew = instrument rec
151   where rec hd@HD{ tables=t, totBuckets=b } =
152                hd{ tables=t+1, totBuckets=b+fromIntegral tABLE_MIN }
153
154 recordIns :: Int32 -> Int32 -> [a] -> IO ()
155 recordIns i sz bkt = instrument rec
156   where rec hd@HD{ insertions=ins, maxEntries=mx, maxChain=mc } =
157                hd{ insertions=ins+fromIntegral i, maxEntries=mx `max` sz,
158                    maxChain=mc `max` length bkt }
159
160 recordResize :: Int32 -> Int32 -> IO ()
161 recordResize older newer = instrument rec
162   where rec hd@HD{ totBuckets=b, maxBuckets=mx } =
163                hd{ totBuckets=b+fromIntegral (newer-older),
164                    maxBuckets=mx `max` newer }
165
166 recordLookup :: IO ()
167 recordLookup = instrument lkup
168   where lkup hd@HD{ lookups=l } = hd{ lookups=l+1 }
169
170 -- stats :: IO String
171 -- stats =  fmap show $ readIORef hashData
172
173 -- ----------------------------------------------------------------------------
174 -- Sample hash functions
175
176 -- $hash_functions
177 --
178 -- This implementation of hash tables uses the low-order /n/ bits of the hash
179 -- value for a key, where /n/ varies as the hash table grows.  A good hash
180 -- function therefore will give an even distribution regardless of /n/.
181 --
182 -- If your keyspace is integrals such that the low-order bits between
183 -- keys are highly variable, then you could get away with using 'fromIntegral'
184 -- as the hash function.
185 --
186 -- We provide some sample hash functions for 'Int' and 'String' below.
187
188 golden :: Int32
189 golden = 1013904242 -- = round ((sqrt 5 - 1) * 2^32) :: Int32
190 -- was -1640531527 = round ((sqrt 5 - 1) * 2^31) :: Int32
191 -- but that has bad mulHi properties (even adding 2^32 to get its inverse)
192 -- Whereas the above works well and contains no hash duplications for
193 -- [-32767..65536]
194
195 hashInt32 :: Int32 -> Int32
196 hashInt32 x = mulHi x golden + x
197
198 -- | A sample (and useful) hash function for Int and Int32,
199 -- implemented by extracting the uppermost 32 bits of the 64-bit
200 -- result of multiplying by a 33-bit constant.  The constant is from
201 -- Knuth, derived from the golden ratio:
202 --
203 -- > golden = round ((sqrt 5 - 1) * 2^32)
204 --
205 -- We get good key uniqueness on small inputs
206 -- (a problem with previous versions):
207 --  (length $ group $ sort $ map hashInt [-32767..65536]) == 65536 + 32768
208 --
209 hashInt :: Int -> Int32
210 hashInt x = hashInt32 (fromIntegral x)
211
212 -- hi 32 bits of a x-bit * 32 bit -> 64-bit multiply
213 mulHi :: Int32 -> Int32 -> Int32
214 mulHi a b = fromIntegral (r `shiftR` 32)
215    where r :: Int64
216          r = fromIntegral a * fromIntegral b
217
218 -- | A sample hash function for Strings.  We keep multiplying by the
219 -- golden ratio and adding.  The implementation is:
220 --
221 -- > hashString = foldl' f golden
222 -- >   where f m c = fromIntegral (ord c) * magic + hashInt32 m
223 -- >         magic = 0xdeadbeef
224 --
225 -- Where hashInt32 works just as hashInt shown above.
226 --
227 -- Knuth argues that repeated multiplication by the golden ratio
228 -- will minimize gaps in the hash space, and thus it's a good choice
229 -- for combining together multiple keys to form one.
230 --
231 -- Here we know that individual characters c are often small, and this
232 -- produces frequent collisions if we use ord c alone.  A
233 -- particular problem are the shorter low ASCII and ISO-8859-1
234 -- character strings.  We pre-multiply by a magic twiddle factor to
235 -- obtain a good distribution.  In fact, given the following test:
236 --
237 -- > testp :: Int32 -> Int
238 -- > testp k = (n - ) . length . group . sort . map hs . take n $ ls
239 -- >   where ls = [] : [c : l | l <- ls, c <- ['\0'..'\xff']]
240 -- >         hs = foldl' f golden
241 -- >         f m c = fromIntegral (ord c) * k + hashInt32 m
242 -- >         n = 100000
243 --
244 -- We discover that testp magic = 0.
245
246 hashString :: String -> Int32
247 hashString = foldl' f golden
248    where f m c = fromIntegral (ord c) * magic + hashInt32 m
249          magic = 0xdeadbeef
250
251 -- | A prime larger than the maximum hash table size
252 prime :: Int32
253 prime = 33554467
254
255 -- -----------------------------------------------------------------------------
256 -- Parameters
257
258 tABLE_MAX :: Int32
259 tABLE_MAX  = 32 * 1024 * 1024   -- Maximum size of hash table
260 tABLE_MIN :: Int32
261 tABLE_MIN  = 8
262
263 hLOAD :: Int32
264 hLOAD = 7                       -- Maximum average load of a single hash bucket
265
266 hYSTERESIS :: Int32
267 hYSTERESIS = 64                 -- entries to ignore in load computation
268
269 {- Hysteresis favors long association-list-like behavior for small tables. -}
270
271 -- -----------------------------------------------------------------------------
272 -- Creating a new hash table
273
274 -- | Creates a new hash table.  The following property should hold for the @eq@
275 -- and @hash@ functions passed to 'new':
276 --
277 -- >   eq A B  =>  hash A == hash B
278 --
279 new
280   :: (key -> key -> Bool)    -- ^ @eq@: An equality comparison on keys
281   -> (key -> Int32)          -- ^ @hash@: A hash function on keys
282   -> IO (HashTable key val)  -- ^ Returns: an empty hash table
283
284 new cmpr hash = do
285   recordNew
286   -- make a new hash table with a single, empty, segment
287   let mask = tABLE_MIN-1
288   bkts'  <- newMutArray (0,mask) []
289   bkts   <- freezeArray bkts'
290
291   let
292     kcnt = 0
293     ht = HT {  buckets=bkts, kcount=kcnt, bmask=mask }
294
295   table <- newIORef ht
296   return (HashTable { tab=table, hash_fn=hash, cmp=cmpr })
297
298 -- -----------------------------------------------------------------------------
299 -- Inserting a key\/value pair into the hash table
300
301 -- | Inserts a key\/value mapping into the hash table.
302 --
303 -- Note that 'insert' doesn't remove the old entry from the table -
304 -- the behaviour is like an association list, where 'lookup' returns
305 -- the most-recently-inserted mapping for a key in the table.  The
306 -- reason for this is to keep 'insert' as efficient as possible.  If
307 -- you need to update a mapping, then we provide 'update'.
308 --
309 insert :: HashTable key val -> key -> val -> IO ()
310
311 insert ht key val =
312   updatingBucket CanInsert (\bucket -> ((key,val):bucket, 1, ())) ht key
313
314
315 -- ------------------------------------------------------------
316 -- The core of the implementation is lurking down here, in findBucket,
317 -- updatingBucket, and expandHashTable.
318
319 tooBig :: Int32 -> Int32 -> Bool
320 tooBig k b = k-hYSTERESIS > hLOAD * b
321
322 -- index of bucket within table.
323 bucketIndex :: Int32 -> Int32 -> Int32
324 bucketIndex mask h = h .&. mask
325
326 -- find the bucket in which the key belongs.
327 -- returns (key equality, bucket index, bucket)
328 --
329 -- This rather grab-bag approach gives enough power to do pretty much
330 -- any bucket-finding thing you might want to do.  We rely on inlining
331 -- to throw away the stuff we don't want.  I'm proud to say that this
332 -- plus updatingBucket below reduce most of the other definitions to a
333 -- few lines of code, while actually speeding up the hashtable
334 -- implementation when compared with a version which does everything
335 -- from scratch.
336 {-# INLINE findBucket #-}
337 findBucket :: HashTable key val -> key -> IO (HT key val, Int32, [(key,val)])
338 findBucket HashTable{ tab=ref, hash_fn=hash} key = do
339   table@HT{ buckets=bkts, bmask=b } <- readIORef ref
340   let indx = bucketIndex b (hash key)
341   bucket <- readHTArray bkts indx
342   return (table, indx, bucket)
343
344 data Inserts = CanInsert
345              | Can'tInsert
346              deriving (Eq)
347
348 -- updatingBucket is the real workhorse of all single-element table
349 -- updates.  It takes a hashtable and a key, along with a function
350 -- describing what to do with the bucket in which that key belongs.  A
351 -- flag indicates whether this function may perform table insertions.
352 -- The function returns the new contents of the bucket, the number of
353 -- bucket entries inserted (negative if entries were deleted), and a
354 -- value which becomes the return value for the function as a whole.
355 -- The table sizing is enforced here, calling out to expandSubTable as
356 -- necessary.
357
358 -- This function is intended to be inlined and specialized for every
359 -- calling context (eg every provided bucketFn).
360 {-# INLINE updatingBucket #-}
361
362 updatingBucket :: Inserts -> ([(key,val)] -> ([(key,val)], Int32, a)) ->
363                   HashTable key val -> key ->
364                   IO a
365 updatingBucket canEnlarge bucketFn
366                ht@HashTable{ tab=ref, hash_fn=hash } key = do
367   (table@HT{ kcount=k, buckets=bkts, bmask=b },
368    indx, bckt) <- findBucket ht key
369   (bckt', inserts, result) <- return $ bucketFn bckt
370   let k' = k + inserts
371       table1 = table { kcount=k' }
372   bkts' <- thawArray bkts
373   writeMutArray bkts' indx bckt'
374   freezeArray bkts'
375   table2 <- if canEnlarge == CanInsert && inserts > 0 then do
376                recordIns inserts k' bckt'
377                if tooBig k' b
378                   then expandHashTable hash table1
379                   else return table1
380             else return table1
381   writeIORef ref table2
382   return result
383
384 expandHashTable :: (key -> Int32) -> HT key val -> IO (HT key val)
385 expandHashTable hash table@HT{ buckets=bkts, bmask=mask } = do
386    let
387       oldsize = mask + 1
388       newmask = mask + mask + 1
389    recordResize oldsize (newmask+1)
390    --
391    if newmask > tABLE_MAX-1
392       then return table
393       else do
394    --
395     newbkts' <- newMutArray (0,newmask) []
396
397     let
398      splitBucket oldindex = do
399        bucket <- readHTArray bkts oldindex
400        let (oldb,newb) =
401               partition ((oldindex==). bucketIndex newmask . hash . fst) bucket
402        writeMutArray newbkts' oldindex oldb
403        writeMutArray newbkts' (oldindex + oldsize) newb
404     mapM_ splitBucket [0..mask]
405
406     newbkts <- freezeArray newbkts'
407
408     return ( table{ buckets=newbkts, bmask=newmask } )
409
410 -- -----------------------------------------------------------------------------
411 -- Deleting a mapping from the hash table
412
413 -- Remove a key from a bucket
414 deleteBucket :: (key -> Bool) -> [(key,val)] -> ([(key, val)], Int32, ())
415 deleteBucket _   [] = ([],0,())
416 deleteBucket del (pair@(k,_):bucket) =
417   case deleteBucket del bucket of
418     (bucket', dels, _) | del k     -> dels' `seq` (bucket', dels', ())
419                        | otherwise -> (pair:bucket', dels, ())
420       where dels' = dels - 1
421
422 -- | Remove an entry from the hash table.
423 delete :: HashTable key val -> key -> IO ()
424
425 delete ht@HashTable{ cmp=eq } key =
426   updatingBucket Can'tInsert (deleteBucket (eq key)) ht key
427
428 -- -----------------------------------------------------------------------------
429 -- Updating a mapping in the hash table
430
431 -- | Updates an entry in the hash table, returning 'True' if there was
432 -- already an entry for this key, or 'False' otherwise.  After 'update'
433 -- there will always be exactly one entry for the given key in the table.
434 --
435 -- 'insert' is more efficient than 'update' if you don't care about
436 -- multiple entries, or you know for sure that multiple entries can't
437 -- occur.  However, 'update' is more efficient than 'delete' followed
438 -- by 'insert'.
439 update :: HashTable key val -> key -> val -> IO Bool
440
441 update ht@HashTable{ cmp=eq } key val =
442   updatingBucket CanInsert
443     (\bucket -> let (bucket', dels, _) = deleteBucket (eq key) bucket
444                 in  ((key,val):bucket', 1+dels, dels/=0))
445     ht key
446
447 -- -----------------------------------------------------------------------------
448 -- Looking up an entry in the hash table
449
450 -- | Looks up the value of a key in the hash table.
451 lookup :: HashTable key val -> key -> IO (Maybe val)
452
453 lookup ht@HashTable{ cmp=eq } key = do
454   recordLookup
455   (_, _, bucket) <- findBucket ht key
456   let firstHit (k,v) r | eq key k  = Just v
457                        | otherwise = r
458   return (foldr firstHit Nothing bucket)
459
460 -- -----------------------------------------------------------------------------
461 -- Converting to/from lists
462
463 -- | Convert a list of key\/value pairs into a hash table.  Equality on keys
464 -- is taken from the Eq instance for the key type.
465 --
466 fromList :: (Eq key) => (key -> Int32) -> [(key,val)] -> IO (HashTable key val)
467 fromList hash list = do
468   table <- new (==) hash
469   sequence_ [ insert table k v | (k,v) <- list ]
470   return table
471
472 -- | Converts a hash table to a list of key\/value pairs.
473 --
474 toList :: HashTable key val -> IO [(key,val)]
475 toList = mapReduce id concat
476
477 {-# INLINE mapReduce #-}
478 mapReduce :: ([(key,val)] -> r) -> ([r] -> r) -> HashTable key val -> IO r
479 mapReduce m r HashTable{ tab=ref } = do
480   HT{ buckets=bckts, bmask=b } <- readIORef ref
481   fmap r (mapM (fmap m . readHTArray bckts) [0..b])
482
483 -- -----------------------------------------------------------------------------
484 -- Diagnostics
485
486 -- | This function is useful for determining whether your hash
487 -- function is working well for your data set.  It returns the longest
488 -- chain of key\/value pairs in the hash table for which all the keys
489 -- hash to the same bucket.  If this chain is particularly long (say,
490 -- longer than 14 elements or so), then it might be a good idea to try
491 -- a different hash function.
492 --
493 longestChain :: HashTable key val -> IO [(key,val)]
494 longestChain = mapReduce id (maximumBy lengthCmp)
495   where lengthCmp (_:x)(_:y) = lengthCmp x y
496         lengthCmp []   []    = EQ
497         lengthCmp []   _     = LT
498         lengthCmp _    []    = GT