on 2d73448 help sign in
typeable/uuid/Data/UUID/Internal.hs
59 lines 1.9 kB history raw
1-- |
2-- Module : Data.UUID.Internal
3-- Copyright : (c) 2008 Antoine Latter
4--
5-- License : BSD-style
6--
7-- Maintainer : aslatter@gmail.com
8-- Stability : experimental
9-- Portability : portable
10--
11-- If the public interface in "Data.UUID" doesn't give you
12-- the flexibility you need, you should be able to find
13-- something here.
15module Data.UUID.Internal(UUID(..)
16 ,toBytes
17 ,fromBytes
18 ,unsafeFromBytes
19 ,toForeignPtr
20 ,fromForeignPtr
21 ) where
23import Foreign.ForeignPtr
24import Foreign.C
25import Foreign
27-- |The UUID type. Represents 128-bits of identification.
28newtype UUID = U (ForeignPtr CChar)
30-- |Returns the passed in UUID as a list of 16 bytes.
31toBytes :: UUID -> [Word8]
32toBytes (U fp) = unsafePerformIO $ withForeignPtr fp $ \p ->
33 peekArray 16 (castPtr p)
35-- |Creates a UUID out of a list of bytes.
36-- Will throw an error if the list is not of length 16.
37fromBytes :: [Word8] -> UUID
38fromBytes xs = if length xs == 16
39 then unsafeFromBytes xs
40 else error "Data.UUID.Internal.fromBytes: passed in list of bytes must be of length 16."
42-- |Creates a UUID out of a list of bytes.
43-- Does not perform a length check.
44-- Behavior is undefined for lists not of length 16.
45unsafeFromBytes :: [Word8] -> UUID
46unsafeFromBytes xs = U $ castForeignPtr $ unsafePerformIO $ do
47 p <- mallocForeignPtrBytes 16
48 withForeignPtr p $ flip pokeArray xs
49 return p
51-- |Given a UUID, returns a pointer to the 16 bytes
52-- of memory that make up the UUID.
53toForeignPtr :: UUID -> ForeignPtr CChar
54toForeignPtr (U p) = p
56-- |The passed in pointer is treated as if it were a pointer
57-- to 16 bytes of memory. You're in trouble if it isn't.
58fromForeignPtr :: ForeignPtr CChar -> UUID
59fromForeignPtr = U