97251ff36c6969168c2dcd012fc9537bd3da5496
[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 -- $Id: Unique.hs,v 1.1 2001/07/04 10:48:39 simonmar Exp $
12 --
13 -- An infinite supply of unique objects, supporting ordering and equality.
14 --
15 -----------------------------------------------------------------------------
16
17 module Data.Unique (
18    Unique,              -- instance (Eq, Ord)
19    newUnique,           -- :: IO Unique
20    hashUnique           -- :: Unique -> Int
21  ) where
22
23 import Prelude
24
25 import Control.Concurrent
26 import System.IO.Unsafe (unsafePerformIO)
27
28 #ifdef __GLASGOW_HASKELL__
29 import GHC.Base
30 import GHC.Num  ( Integer(..) )
31 #endif
32
33 newtype Unique = Unique Integer deriving (Eq,Ord)
34
35 uniqSource :: MVar Integer
36 uniqSource = unsafePerformIO (newMVar 0)
37 {-# NOINLINE uniqSource #-}
38
39 newUnique :: IO Unique
40 newUnique = do
41    val <- takeMVar uniqSource
42    let next = val+1
43    putMVar uniqSource next
44    return (Unique next)
45
46 hashUnique :: Unique -> Int
47 #ifdef __GLASGOW_HASKELL__ 
48 hashUnique (Unique (S# i))   = I# i
49 hashUnique (Unique (J# s d)) | s ==# 0#  = 0
50                              | otherwise = I# (indexIntArray# d 0#)
51 #else
52 hashUnique (Unique u) = u `mod` (fromIntegral (maxBound :: Int) + 1)
53 #endif