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__
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 #if defined(__GLASGOW_HASKELL__)
56 hashUnique (Unique i) = I# (hashInteger i)
58 hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1))