X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=Data%2FUnique.hs;h=1c1ceb88eef52e2943acb87279adf79525d09ba6;hb=a0d7892da0d00fee781a550ef353df8734be5884;hp=81fe6d87a02f58b1fe2d294b2703f2fefd0fb283;hpb=f7a485978f04e84b086f1974b88887cc72d832d0;p=haskell-directory.git diff --git a/Data/Unique.hs b/Data/Unique.hs index 81fe6d8..1c1ceb8 100644 --- a/Data/Unique.hs +++ b/Data/Unique.hs @@ -8,11 +8,12 @@ -- Stability : experimental -- Portability : non-portable -- --- An infinite supply of unique objects, supporting ordering and equality. +-- An abstract interface to a unique symbol generator. -- ----------------------------------------------------------------------------- module Data.Unique ( + -- * Unique objects Unique, -- instance (Eq, Ord) newUnique, -- :: IO Unique hashUnique -- :: Unique -> Int @@ -20,7 +21,7 @@ module Data.Unique ( import Prelude -import Control.Concurrent +import Control.Concurrent.MVar import System.IO.Unsafe (unsafePerformIO) #ifdef __GLASGOW_HASKELL__ @@ -28,12 +29,18 @@ import GHC.Base import GHC.Num ( Integer(..) ) #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 @@ -41,11 +48,14 @@ newUnique = do 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 #ifdef __GLASGOW_HASKELL__ hashUnique (Unique (S# i)) = I# i hashUnique (Unique (J# s d)) | s ==# 0# = 0 | otherwise = I# (indexIntArray# d 0#) #else -hashUnique (Unique u) = u `mod` (fromIntegral (maxBound :: Int) + 1) +hashUnique (Unique u) = fromInteger (u `mod` (toInteger (maxBound :: Int) + 1)) #endif