Add missing files
[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 Control.Concurrent.MVar
25 import System.IO.Unsafe (unsafePerformIO)
26
27 #ifdef __GLASGOW_HASKELL__
28 import GHC.Base
29 import GHC.Num
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 :: MVar Integer
37 uniqSource = unsafePerformIO (newMVar 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 = do
46    val <- takeMVar uniqSource
47    let next = val+1
48    putMVar uniqSource next
49    return (Unique next)
50
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)
57 #else
58 hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1))
59 #endif