1{-# LANGUAGE DeriveDataTypeable, TypeFamilies, CPP #-}
5-- Copyright : (c) 2008-2009, 2012 Antoine Latter
6-- (c) 2009 Mark Lentczner
10-- Maintainer : aslatter@gmail.com
11-- Stability : experimental
12-- Portability : portable
14module Data.UUID.Internal
36import Prelude hiding (null)
38import Control.Applicative ((<*>))
39import Control.DeepSeq (NFData(..))
40import Control.Monad (liftM4, guard)
41import Data.Functor ((<$>))
45import Data.List (elemIndices)
46import Foreign.Ptr (Ptr)
48#if MIN_VERSION_base(4,0,0)
51import Data.Generics.Basics
54import Foreign.Storable
59import qualified Data.ByteString as B
60import qualified Data.ByteString.Internal as BI
61import qualified Data.ByteString.Lazy as BL
62import qualified Data.ByteString.Unsafe as BU
64import Data.UUID.Builder
70-- |The UUID type. A 'Random' instance is provided which produces
71-- version 4 UUIDs as specified in RFC 4122. The 'Storable' and
72-- 'Binary' instances are compatible with RFC 4122, storing the fields
73-- in network order as 16 bytes.
76 {-# UNPACK #-} !Word32
77 {-# UNPACK #-} !Word32
78 {-# UNPACK #-} !Word32
79 {-# UNPACK #-} !Word32
80 deriving (Eq, Ord, Typeable)
82 Other representations that we tried are:
83 Mimic V1 structure: !Word32 !Word16 !Word16 !Word16
84 !Word8 !Word8 !Word8 !Word8 !Word8 !Word8
85 Sixteen bytes: !Word8 ... (x 16)
86 Simple list of bytes: [Word8]
87 ByteString (strict) ByteString
88 Immutable array: UArray Int Word8
90 None was as fast, overall, as the representation used here.
93-- | Covert a 'UUID' into a sequence of 'Word32' values.
94-- Usefull for when you need to serialize a UUID and
95-- neither 'Storable' nor 'Binary' are appropriate.
96-- Introduced in version 1.2.2.
97toWords :: UUID -> (Word32, Word32, Word32, Word32)
98toWords (UUID w1 w2 w3 w4) = (w1, w2, w3, w4)
100-- | Create a 'UUID' from a sequence of 'Word32'. The
101-- opposite of 'toWords'. Useful when you need a total
102-- function for constructing 'UUID' values.
103-- Introduced in version 1.2.2.
104fromWords :: Word32 -> Word32 -> Word32 -> Word32 -> UUID
109 time_low :: Word32 -- 0-3
110 , time_mid :: Word16 -- 4-5
111 , time_hi_and_version :: Word16 -- 6-7
112 , clock_seq_hi_res :: Word8 -- 8
113 , clock_seq_low :: Word8 -- 9
121 deriving (Read, Show, Eq, Ord)
123unpack :: UUID -> UnpackedUUID
124unpack (UUID w0 w1 w2 w3) =
125 build /-/ w0 /-/ w1 /-/ w2 /-/ w3
128 build x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF =
130 time_low = word x0 x1 x2 x3
131 , time_mid = w8to16 x4 x5
132 , time_hi_and_version = w8to16 x6 x7
133 , clock_seq_hi_res = x8
143pack :: UnpackedUUID -> UUID
145 makeFromBytes /-/ (time_low unpacked)
146 /-/ (time_mid unpacked)
147 /-/ (time_hi_and_version unpacked)
148 /-/ (clock_seq_hi_res unpacked)
149 /-/ (clock_seq_low unpacked)
150 /-/ (node_0 unpacked) /-/ (node_1 unpacked)
151 /-/ (node_2 unpacked) /-/ (node_3 unpacked)
152 /-/ (node_4 unpacked) /-/ (node_5 unpacked)
159-- |Build a Word32 from four Word8 values, presented in big-endian order
160word :: Word8 -> Word8 -> Word8 -> Word8 -> Word32
161word a b c d = (fromIntegral a `shiftL` 24)
162 .|. (fromIntegral b `shiftL` 16)
163 .|. (fromIntegral c `shiftL` 8)
164 .|. (fromIntegral d )
166-- |Extract a Word8 from a Word32. Bytes, high to low, are numbered from 3 to 0,
167byte :: Int -> Word32 -> Word8
168byte i w = fromIntegral (w `shiftR` (i * 8))
171-- |Make a UUID from sixteen Word8 values
172makeFromBytes :: Word8 -> Word8 -> Word8 -> Word8
173 -> Word8 -> Word8 -> Word8 -> Word8
174 -> Word8 -> Word8 -> Word8 -> Word8
175 -> Word8 -> Word8 -> Word8 -> Word8
177makeFromBytes b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf
179 where w0 = word b0 b1 b2 b3
180 w1 = word b4 b5 b6 b7
181 w2 = word b8 b9 ba bb
182 w3 = word bc bd be bf
184-- |Make a UUID from four Word32 values
185makeFromWords :: Word32 -> Word32 -> Word32 -> Word32 -> UUID
188-- |A Builder for constructing a UUID of a given version.
189buildFromBytes :: Word8
190 -> Word8 -> Word8 -> Word8 -> Word8
191 -> Word8 -> Word8 -> Word8 -> Word8
192 -> Word8 -> Word8 -> Word8 -> Word8
193 -> Word8 -> Word8 -> Word8 -> Word8
195buildFromBytes v b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf =
196 makeFromBytes b0 b1 b2 b3 b4 b5 b6' b7 b8' b9 ba bb bc bd be bf
197 where b6' = b6 .&. 0x0f .|. (v `shiftL` 4)
198 b8' = b8 .&. 0x3f .|. 0x80
200-- |Build a UUID of a given version from Word32 values.
201buildFromWords :: Word8 -> Word32 -> Word32 -> Word32 -> Word32 -> UUID
202buildFromWords v w0 w1 w2 w3 = makeFromWords w0 w1' w2' w3
203 where w1' = w1 .&. 0xffff0fff .|. ((fromIntegral v) `shiftL` 12)
204 w2' = w2 .&. 0x3fffffff .|. 0x80000000
207-- |Return the bytes that make up the UUID
208toList :: UUID -> [Word8]
209toList (UUID w0 w1 w2 w3) =
210 [byte 3 w0, byte 2 w0, byte 1 w0, byte 0 w0,
211 byte 3 w1, byte 2 w1, byte 1 w1, byte 0 w1,
212 byte 3 w2, byte 2 w2, byte 1 w2, byte 0 w2,
213 byte 3 w3, byte 2 w3, byte 1 w3, byte 0 w3]
215-- |Construct a UUID from a list of Word8. Returns Nothing if the list isn't
216-- exactly sixteen bytes long
217fromList :: [Word8] -> Maybe UUID
218fromList [b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf] =
219 Just $ makeFromBytes b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf
227-- |Returns true if the passed-in UUID is the 'nil' UUID.
230 -- Note: This actually faster than:
231 -- null (UUID 0 0 0 0) = True
234-- |The nil UUID, as defined in RFC 4122.
235-- It is a UUID of all zeros. @'null' u@ iff @'u' == 'nil'@.
239-- |Extract a UUID from a 'ByteString' in network byte order.
240-- The argument must be 16 bytes long, otherwise 'Nothing' is returned.
241fromByteString :: BL.ByteString -> Maybe UUID
242fromByteString = fromList . BL.unpack
244-- |Encode a UUID into a 'ByteString' in network order.
245toByteString :: UUID -> BL.ByteString
246toByteString = BL.pack . toList
248-- |If the passed in 'String' can be parsed as a 'UUID', it will be.
249-- The hyphens may not be omitted.
253-- fromString \"c2cc10e1-57d6-4b6f-9899-38d972112d8c\"
256-- Hex digits may be upper or lower-case.
257fromString :: String -> Maybe UUID
258fromString xs | validFmt = fromString' xs
259 | otherwise = Nothing
260 where validFmt = elemIndices '-' xs == [8,13,18,23]
262fromString' :: String -> Maybe UUID
264 (w0, s1) <- hexWord s0
265 (w1, s2) <- hexWord s1
266 (w2, s3) <- hexWord s2
267 (w3, s4) <- hexWord s3
268 if s4 /= "" then Nothing
269 else Just $ UUID w0 w1 w2 w3
270 where hexWord :: String -> Maybe (Word32, String)
271 hexWord s = Just (0, s) >>= hexByte >>= hexByte
272 >>= hexByte >>= hexByte
274 hexByte :: (Word32, String) -> Maybe (Word32, String)
275 hexByte (w, '-':ds) = hexByte (w, ds)
276 hexByte (w, hi:lo:ds)
277 | bothHex = Just ((w `shiftL` 8) .|. octet, ds)
278 | otherwise = Nothing
279 where bothHex = isHexDigit hi && isHexDigit lo
280 octet = fromIntegral (16 * digitToInt hi + digitToInt lo)
283-- | Convert a UUID into a hypenated string using lower-case letters.
287-- toString \<$\> fromString \"550e8400-e29b-41d4-a716-446655440000\"
289toString :: UUID -> String
290toString (UUID w0 w1 w2 w3) = hexw w0 $ hexw' w1 $ hexw' w2 $ hexw w3 ""
291 where hexw :: Word32 -> String -> String
292 hexw w s = hexn w 28 : hexn w 24 : hexn w 20 : hexn w 16
293 : hexn w 12 : hexn w 8 : hexn w 4 : hexn w 0 : s
295 hexw' :: Word32 -> String -> String
296 hexw' w s = '-' : hexn w 28 : hexn w 24 : hexn w 20 : hexn w 16
297 : '-' : hexn w 12 : hexn w 8 : hexn w 4 : hexn w 0 : s
299 hexn :: Word32 -> Int -> Char
300 hexn w r = intToDigit $ fromIntegral ((w `shiftR` r) .&. 0xf)
302-- | Convert a UUID into a hyphentated string using lower-case letters, packed
303-- as ASCII bytes into `B.ByteString`.
305-- This should be equivalent to `toString` with `Data.ByteString.Char8.pack`.
306toASCIIBytes :: UUID -> B.ByteString
307toASCIIBytes uuid = BI.unsafeCreate 36 (pokeASCII uuid)
309-- | Helper function for `toASCIIBytes`
310pokeASCII :: UUID -> Ptr Word8 -> IO ()
311pokeASCII uuid ptr = do
321 (w0, w1, w2, w3) = toWords uuid
324 pokeDash ix = pokeElemOff ptr ix 45
328 pokeWord (ix + 1) w 24
329 pokeWord (ix + 2) w 20
330 pokeWord (ix + 3) w 16
331 pokeWord (ix + 4) w 12
332 pokeWord (ix + 5) w 8
333 pokeWord (ix + 6) w 4
334 pokeWord (ix + 7) w 0
336 -- We skip the dash in the middle
339 pokeWord (ix + 1) w 24
340 pokeWord (ix + 2) w 20
341 pokeWord (ix + 3) w 16
342 pokeWord (ix + 5) w 12
343 pokeWord (ix + 6) w 8
344 pokeWord (ix + 7) w 4
345 pokeWord (ix + 8) w 0
348 pokeElemOff ptr ix (fromIntegral (toDigit ((w `shiftR` r) .&. 0xf)))
350 toDigit :: Word32 -> Word32
351 toDigit w = if w < 10 then 48 + w else 97 + w - 10
353-- | If the passed in `B.ByteString` can be parsed as an ASCII representation of
354-- a `UUID`, it will be. The hyphens may not be omitted.
356-- This should be equivalent to `fromString` with `Data.ByteString.Char8.unpack`.
357fromASCIIBytes :: B.ByteString -> Maybe UUID
358fromASCIIBytes bs = do
360 fromWords <$> single 0 <*> double 9 14 <*> double 19 24 <*> single 28
363 dashIx bs' ix = BU.unsafeIndex bs' ix == 45
365 -- Important: check the length first, given the `unsafeIndex` later.
367 B.length bs == 36 && dashIx bs 8 && dashIx bs 13 &&
368 dashIx bs 18 && dashIx bs 23
370 single ix = combine <$> octet ix <*> octet (ix + 2)
371 <*> octet (ix + 4) <*> octet (ix + 6)
372 double ix0 ix1 = combine <$> octet ix0 <*> octet (ix0 + 2)
373 <*> octet ix1 <*> octet (ix1 + 2)
375 combine o0 o1 o2 o3 = shiftL o0 24 .|. shiftL o1 16 .|. shiftL o2 8 .|. o3
378 hi <- fromIntegral <$> toDigit (BU.unsafeIndex bs ix)
379 lo <- fromIntegral <$> toDigit (BU.unsafeIndex bs (ix + 1))
380 return (16 * hi + lo)
382 toDigit :: Word8 -> Maybe Word8
385 | w >= 48 && w <= 57 = Just (w - 48)
387 | w >= 65 && w <= 70 = Just (10 + w - 65)
389 | w >= 97 && w <= 102 = Just (10 + w - 97)
390 | otherwise = Nothing
392-- | Similar to `toASCIIBytes` except we produce a lazy `BL.ByteString`.
393toLazyASCIIBytes :: UUID -> BL.ByteString
394toLazyASCIIBytes = BL.fromStrict . toASCIIBytes
396-- | Similar to `fromASCIIBytes` except parses from a lazy `BL.ByteString`.
397fromLazyASCIIBytes :: BL.ByteString -> Maybe UUID
398fromLazyASCIIBytes bs =
399 if BL.length bs == 36 then fromASCIIBytes (BL.toStrict bs) else Nothing
405instance Random UUID where
406 random g = (fromGenNext w0 w1 w2 w3 w4, g4)
407 where (w0, g0) = next g
412 randomR _ = random -- range is ignored
414-- |Build a UUID from the results of five calls to next on a StdGen.
415-- While next on StdGet returns an Int, it doesn't provide 32 bits of
416-- randomness. This code relies on at last 28 bits of randomness in the
417-- and optimizes its use so as to make only five random values, not six.
418fromGenNext :: Int -> Int -> Int -> Int -> Int -> UUID
419fromGenNext w0 w1 w2 w3 w4 =
420 buildFromBytes 4 /-/ (ThreeByte w0)
422 /-/ w2 -- use all 4 bytes because we know the version
423 -- field will "cover" the upper, non-random bits
427-- |A ByteSource to extract only three bytes from an Int, since next on StdGet
428-- only returns 31 bits of randomness.
429type instance ByteSink ThreeByte g = Takes3Bytes g
430newtype ThreeByte = ThreeByte Int
431instance ByteSource ThreeByte where
432 f /-/ (ThreeByte w) = f b1 b2 b3
433 where b1 = fromIntegral (w `shiftR` 16)
434 b2 = fromIntegral (w `shiftR` 8)
437instance NFData UUID where
440instance Hashable UUID where
441 hash (UUID w0 w1 w2 w3) =
442 hash w0 `hashWithSalt` w1
445 hashWithSalt s (UUID w0 w1 w2 w3) =
451instance Show UUID where
454instance Read UUID where
456 let noSpaces = dropWhile isSpace str
457 in case fromString (take 36 noSpaces) of
459 Just u -> [(u,drop 36 noSpaces)]
462instance Storable UUID where
469 <$> peekByteOff p off -- Word32
470 <*> peekByteOff p (off+4) -- Word16
471 <*> peekByteOff p (off+6) -- Word16
472 <*> peekByteOff p (off+8) -- Word8
473 <*> peekByteOff p (off+9) -- Word8
474 <*> peekByteOff p (off+10) -- Word8
475 <*> peekByteOff p (off+11) -- Word8
476 <*> peekByteOff p (off+12) -- Word8
477 <*> peekByteOff p (off+13) -- Word8
478 <*> peekByteOff p (off+14) -- Word8
479 <*> peekByteOff p (off+15) -- Word8
482 pokeByteOff p off u =
484 (UnpackedUUID x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) ->
487 pokeByteOff p (off+4) x1
488 pokeByteOff p (off+6) x2
489 pokeByteOff p (off+8) x3
490 pokeByteOff p (off+9) x4
491 pokeByteOff p (off+10) x5
492 pokeByteOff p (off+11) x6
493 pokeByteOff p (off+12) x7
494 pokeByteOff p (off+13) x8
495 pokeByteOff p (off+14) x9
496 pokeByteOff p (off+15) x10
498instance Binary UUID where
499 put (UUID w0 w1 w2 w3) =
500 putWord32be w0 >> putWord32be w1 >> putWord32be w2 >> putWord32be w3
501 get = liftM4 UUID getWord32be getWord32be getWord32be getWord32be
504-- My goal with this instance was to make it work just enough to do what
505-- I want when used with the HStringTemplate library.
506instance Data UUID where
507 toConstr uu = mkConstr uuidType (show uu) [] (error "fixity")
508 gunfold _ _ = error "gunfold"
509 dataTypeOf _ = uuidType
512uuidType = mkNoRepType "Data.UUID.UUID"
514#if !(MIN_VERSION_base(4,2,0))
515mkNoRepType :: String -> DataType
516mkNoRepType = mkNorepType
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list