change to use STM, fixing 4 things
[ghc-base.git] / Data / Unique.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Unique
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable
10 --
11 -- An abstract interface to a unique symbol generator.
12 --
13 -----------------------------------------------------------------------------
14
15 module Data.Unique (
16    -- * Unique objects
17    Unique,              -- instance (Eq, Ord)
18    newUnique,           -- :: IO Unique
19    hashUnique           -- :: Unique -> Int
20  ) where
21
22 import Prelude
23
24 import System.IO.Unsafe (unsafePerformIO)
25
26 #ifdef __GLASGOW_HASKELL__
27 import GHC.Base
28 import GHC.Num
29 import GHC.Conc
30 #endif
31
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)
35
36 uniqSource :: TVar Integer
37 uniqSource = unsafePerformIO (newTVarIO 0)
38 {-# NOINLINE uniqSource #-}
39
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
47   let next = val+1
48   writeTVar uniqSource $! val + 1
49   return (Unique next)
50
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.
57
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)
64 #else
65 hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1))
66 #endif