on cebcaa2 help sign in
typeable/uuid/Data/UUID/Internal.hs
45 lines 1.5 kB history raw
1module Data.UUID.Internal(UUID(..)
2 ,toBytes
3 ,fromBytes
4 ,unsafeFromBytes
5 ,toForeignPtr
6 ,fromForeignPtr
7 ) where
9import Foreign.ForeignPtr
10import Foreign.C
11import Foreign
13-- |The UUID type. Represents 128-bits of identification.
14newtype UUID = U (ForeignPtr CChar)
16-- |Returns the passed in UUID as a list of 16 bytes.
17toBytes :: UUID -> [Word8]
18toBytes (U fp) = unsafePerformIO $ withForeignPtr fp $ \p ->
19 peekArray 16 (castPtr p)
21-- |Creates a UUID out of a list of bytes.
22-- Will throw an error if the list is not of length 16.
23fromBytes :: [Word8] -> UUID
24fromBytes xs = if length xs == 16
25 then unsafeFromBytes xs
26 else error "Data.UUID.Internal.fromBytes: passed in list of bytes must be of length 16."
28-- |Creates a UUID out of a list of bytes.
29-- Does not perform a length check.
30-- Behavior is undefined for lists not of length 16.
31unsafeFromBytes :: [Word8] -> UUID
32unsafeFromBytes xs = U $ castForeignPtr $ unsafePerformIO $ do
33 p <- mallocForeignPtrBytes 16
34 withForeignPtr p $ flip pokeArray xs
35 return p
37-- |Given a UUID, returns a pointer to the 16 bytes
38-- of memory that make up the UUID.
39toForeignPtr :: UUID -> ForeignPtr CChar
40toForeignPtr (U p) = p
42-- |The passed in pointer is treated as if it were a pointer
43-- to 16 bytes of memory. You're in trouble if it isn't.
44fromForeignPtr :: ForeignPtr CChar -> UUID
45fromForeignPtr = U