1 -----------------------------------------------------------------------------
3 -- Module : Data.Unique
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : non-portable
11 -- An abstract interface to a unique symbol generator.
13 -----------------------------------------------------------------------------
17 Unique, -- instance (Eq, Ord)
18 newUnique, -- :: IO Unique
19 hashUnique -- :: Unique -> Int
24 import Control.Concurrent.MVar
25 import System.IO.Unsafe (unsafePerformIO)
27 #ifdef __GLASGOW_HASKELL__
29 import GHC.Num ( Integer(..) )
32 -- | An abstract unique object. Objects of type 'Unique' may be
33 -- compared for equality and ordering and hashed into 'Int'.
34 newtype Unique = Unique Integer deriving (Eq,Ord)
36 uniqSource :: MVar Integer
37 uniqSource = unsafePerformIO (newMVar 0)
38 {-# NOINLINE uniqSource #-}
40 -- | Creates a new object of type 'Unique'. The value returned will
41 -- not compare equal to any other value of type 'Unique' returned by
42 -- previous calls to 'newUnique'. There is no limit on the number of
43 -- times 'newUnique' may be called.
44 newUnique :: IO Unique
46 val <- takeMVar uniqSource
48 putMVar uniqSource next
51 -- | Hashes a 'Unique' into an 'Int'. Two 'Unique's may hash to the
52 -- same value, although in practice this is unlikely. The 'Int'
53 -- returned makes a good hash key.
54 hashUnique :: Unique -> Int
55 #ifdef __GLASGOW_HASKELL__
56 hashUnique (Unique (S# i)) = I# i
57 hashUnique (Unique (J# s d)) | s ==# 0# = 0
58 | otherwise = I# (indexIntArray# d 0#)
60 hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1))