module Data.CQRS.GUID
( GUID
, fromByteString
, hexDecode
, hexEncode
, newGUID
, toByteString
) where
import Control.Monad (liftM)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import Data.ByteString.Char8 ()
import Data.Default (Default(..))
import Data.Serialize (Serialize(..))
import Data.Typeable (Typeable)
import Data.Word (Word8)
import System.Random (randomRIO)
newtype GUID = GUID ByteString
deriving (Show, Typeable, Eq, Ord)
instance Default GUID where
def = GUID $ B.pack $ replicate 32 0
randomWord8 :: IO Word8
randomWord8 = fmap fromInteger $ randomRIO (0,255)
newGUID :: IO GUID
newGUID = do
uuid <- sequence $ replicate 32 randomWord8
return $ GUID $ B.pack uuid
instance Serialize GUID where
put = put . toByteString
get = liftM fromByteString get
hexEncode :: GUID -> ByteString
hexEncode (GUID s) = B16.encode s
hexDecode :: ByteString -> Maybe GUID
hexDecode s =
case B16.decode s of
(a,b) | B.length b == 0 -> Just $ GUID a
_ -> Nothing
fromByteString :: ByteString -> GUID
fromByteString = GUID
toByteString :: GUID -> ByteString
toByteString (GUID g) = g