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__
33 -- | An abstract unique object. Objects of type 'Unique' may be
34 -- compared for equality and ordering and hashed into 'Int'.
35 newtype Unique = Unique Integer deriving (Eq,Ord
36 #ifdef __GLASGOW_HASKELL__
41 uniqSource :: TVar Integer
42 uniqSource = unsafePerformIO (newTVarIO 0)
43 {-# NOINLINE uniqSource #-}
45 -- | Creates a new object of type 'Unique'. The value returned will
46 -- not compare equal to any other value of type 'Unique' returned by
47 -- previous calls to 'newUnique'. There is no limit on the number of
48 -- times 'newUnique' may be called.
49 newUnique :: IO Unique
50 newUnique = atomically $ do
51 val <- readTVar uniqSource
53 writeTVar uniqSource $! next
56 -- SDM (18/3/2010): changed from MVar to STM. This fixes
57 -- 1. there was no async exception protection
58 -- 2. there was a space leak (now new value is strict)
59 -- 3. using atomicModifyIORef would be slightly quicker, but can
60 -- suffer from adverse scheduling issues (see #3838)
61 -- 4. also, the STM version is faster.
63 -- | Hashes a 'Unique' into an 'Int'. Two 'Unique's may hash to the
64 -- same value, although in practice this is unlikely. The 'Int'
65 -- returned makes a good hash key.
66 hashUnique :: Unique -> Int
67 #if defined(__GLASGOW_HASKELL__)
68 hashUnique (Unique i) = I# (hashInteger i)
70 hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1))