summaryrefslogtreecommitdiff
path: root/libraries/base/Data/Unique.hs
diff options
context:
space:
mode:
authorIan Lynagh <igloo@earth.li>2008-09-04 10:09:51 +0000
committerIan Lynagh <igloo@earth.li>2008-09-04 10:09:51 +0000
commit672a5a99bc0dfbcc13ddae010784b343b07ce445 (patch)
tree508d365317746f65c0d1e38fe2a74b3b4144fecd /libraries/base/Data/Unique.hs
parent96c6210f8a68a37cc69937edf57ff03b4c779cbc (diff)
downloadhaskell-672a5a99bc0dfbcc13ddae010784b343b07ce445.tar.gz
Add missing files
Diffstat (limited to 'libraries/base/Data/Unique.hs')
-rw-r--r--libraries/base/Data/Unique.hs59
1 files changed, 59 insertions, 0 deletions
diff --git a/libraries/base/Data/Unique.hs b/libraries/base/Data/Unique.hs
new file mode 100644
index 0000000000..6f8c24f0e3
--- /dev/null
+++ b/libraries/base/Data/Unique.hs
@@ -0,0 +1,59 @@
+-----------------------------------------------------------------------------
+-- |
+-- Module : Data.Unique
+-- Copyright : (c) The University of Glasgow 2001
+-- License : BSD-style (see the file libraries/base/LICENSE)
+--
+-- Maintainer : libraries@haskell.org
+-- Stability : experimental
+-- Portability : non-portable
+--
+-- An abstract interface to a unique symbol generator.
+--
+-----------------------------------------------------------------------------
+
+module Data.Unique (
+ -- * Unique objects
+ Unique, -- instance (Eq, Ord)
+ newUnique, -- :: IO Unique
+ hashUnique -- :: Unique -> Int
+ ) where
+
+import Prelude
+
+import Control.Concurrent.MVar
+import System.IO.Unsafe (unsafePerformIO)
+
+#ifdef __GLASGOW_HASKELL__
+import GHC.Base
+import GHC.Num
+#endif
+
+-- | An abstract unique object. Objects of type 'Unique' may be
+-- compared for equality and ordering and hashed into 'Int'.
+newtype Unique = Unique Integer deriving (Eq,Ord)
+
+uniqSource :: MVar Integer
+uniqSource = unsafePerformIO (newMVar 0)
+{-# NOINLINE uniqSource #-}
+
+-- | Creates a new object of type 'Unique'. The value returned will
+-- not compare equal to any other value of type 'Unique' returned by
+-- previous calls to 'newUnique'. There is no limit on the number of
+-- times 'newUnique' may be called.
+newUnique :: IO Unique
+newUnique = do
+ val <- takeMVar uniqSource
+ let next = val+1
+ putMVar uniqSource next
+ return (Unique next)
+
+-- | Hashes a 'Unique' into an 'Int'. Two 'Unique's may hash to the
+-- same value, although in practice this is unlikely. The 'Int'
+-- returned makes a good hash key.
+hashUnique :: Unique -> Int
+#if defined(__GLASGOW_HASKELL__)
+hashUnique (Unique i) = I# (hashInteger i)
+#else
+hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1))
+#endif