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 System.IO.Unsafe (unsafePerformIO)
26 #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 :: TVar Integer
37 uniqSource = unsafePerformIO (newTVarIO 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
45 newUnique = atomically $ do
46 val <- readTVar uniqSource
48 writeTVar uniqSource $! val + 1
51 -- SDM (18/3/2010): changed from MVar to STM. This fixes
52 -- 1. there was no async exception protection
53 -- 2. there was a space leak (now new value is strict)
54 -- 3. using atomicModifyIORef would be slightly quicker, but can
55 -- suffer from adverse scheduling issues (see #3838)
56 -- 4. also, the STM version is faster.
58 -- | Hashes a 'Unique' into an 'Int'. Two 'Unique's may hash to the
59 -- same value, although in practice this is unlikely. The 'Int'
60 -- returned makes a good hash key.
61 hashUnique :: Unique -> Int
62 #if defined(__GLASGOW_HASKELL__)
63 hashUnique (Unique i) = I# (hashInteger i)
65 hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1))