{-# LANGUAGE ForeignFunctionInterface #-}

-- | Module which generates globally unique 'ObjectID's.
module Util.Object (
   ObjectID(..),
   Object(..),
   newObject, -- generates a unique object
   staticObject,
      -- generates a not-necessarily unique object given a
      -- postive integer.  But at least it will be different from all those
      -- generated by newObject, or with a different integer.
   newInt -- generates a unique integer.
   ) where

-- --------------------------------------------------------------------------
-- Class Object
-- --------------------------------------------------------------------------

newtype ObjectID = ObjectID Int deriving (Eq,Ord)

class Object o where
   objectID :: o -> ObjectID

instance Show ObjectID where
   showsPrec d (ObjectID n) r = showsPrec d n r

instance Read ObjectID where
   readsPrec p b =
      case reads b of
         [] -> []
         ((v,xs):_) ->[(ObjectID v,xs)]

-- --------------------------------------------------------------------------
-- New Object Identifier
-- --------------------------------------------------------------------------

foreign import ccall unsafe "new_object.h next_object_id" newInt :: IO Int

newObject :: IO ObjectID
newObject =
   do
      nextInt <- newInt
      return(ObjectID nextInt)

staticObject :: Int -> ObjectID
staticObject i
   | i>0 = ObjectID (-i)
   | True = error "staticObject not given positive integer"