ab3d64718d6f7e8d3b648d316bbf994c6eb35fbd
[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 import Data.Typeable
31 #endif
32
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__
37    ,Typeable
38 #endif
39    )
40
41 uniqSource :: TVar Integer
42 uniqSource = unsafePerformIO (newTVarIO 0)
43 {-# NOINLINE uniqSource #-}
44
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
52   let next = val+1
53   writeTVar uniqSource $! next
54   return (Unique next)
55
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.
62
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)
69 #else
70 hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1))
71 #endif