3e093d31e5a579a1856d7c05b412870fef7e1c87
[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/core/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable
10 --
11 -- An infinite supply of unique objects, supporting ordering and equality.
12 --
13 -----------------------------------------------------------------------------
14
15 module Data.Unique (
16    Unique,              -- instance (Eq, Ord)
17    newUnique,           -- :: IO Unique
18    hashUnique           -- :: Unique -> Int
19  ) where
20
21 import Prelude
22
23 import Control.Concurrent
24 import System.IO.Unsafe (unsafePerformIO)
25
26 #ifdef __GLASGOW_HASKELL__
27 import GHC.Base
28 import GHC.Num  ( Integer(..) )
29 #endif
30
31 newtype Unique = Unique Integer deriving (Eq,Ord)
32
33 uniqSource :: MVar Integer
34 uniqSource = unsafePerformIO (newMVar 0)
35 {-# NOINLINE uniqSource #-}
36
37 newUnique :: IO Unique
38 newUnique = do
39    val <- takeMVar uniqSource
40    let next = val+1
41    putMVar uniqSource next
42    return (Unique next)
43
44 hashUnique :: Unique -> Int
45 #ifdef __GLASGOW_HASKELL__ 
46 hashUnique (Unique (S# i))   = I# i
47 hashUnique (Unique (J# s d)) | s ==# 0#  = 0
48                              | otherwise = I# (indexIntArray# d 0#)
49 #else
50 hashUnique (Unique u) = u `mod` (fromIntegral (maxBound :: Int) + 1)
51 #endif