git.iko.soy/typeable/pandoc
on fa12d4e help sign in
62 lines 1.7 kB history raw
1{-# LANGUAGE NoImplicitPrelude #-}
2{- |
3 Module : Text.Pandoc.UUID
4 Copyright : Copyright (C) 2010-2019 John MacFarlane
5 License : GNU GPL, version 2 or above
7 Maintainer : John MacFarlane <jgm@berkeley.edu>
8 Stability : alpha
9 Portability : portable
11UUID generation using Version 4 (random method) described
12in RFC4122. See http://tools.ietf.org/html/rfc4122
13-}
15module Text.Pandoc.UUID ( UUID(..), getRandomUUID, getUUID ) where
17import Prelude
18import Data.Bits (clearBit, setBit)
19import Data.Word
20import System.Random (RandomGen, getStdGen, randoms)
21import Text.Printf (printf)
23data UUID = UUID Word8 Word8 Word8 Word8 Word8 Word8 Word8 Word8
24 Word8 Word8 Word8 Word8 Word8 Word8 Word8 Word8
26instance Show UUID where
27 show (UUID a b c d e f g h i j k l m n o p) =
28 "urn:uuid:" ++
29 printf "%02x" a ++
30 printf "%02x" b ++
31 printf "%02x" c ++
32 printf "%02x" d ++
33 "-" ++
34 printf "%02x" e ++
35 printf "%02x" f ++
36 "-" ++
37 printf "%02x" g ++
38 printf "%02x" h ++
39 "-" ++
40 printf "%02x" i ++
41 printf "%02x" j ++
42 "-" ++
43 printf "%02x" k ++
44 printf "%02x" l ++
45 printf "%02x" m ++
46 printf "%02x" n ++
47 printf "%02x" o ++
48 printf "%02x" p
50getUUID :: RandomGen g => g -> UUID
51getUUID gen =
52 case take 16 (randoms gen :: [Word8]) of
53 [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p] ->
54 -- set variant
55 let i' = i `setBit` 7 `clearBit` 6
56 -- set version (0100 for random)
57 g' = g `clearBit` 7 `setBit` 6 `clearBit` 5 `clearBit` 4
58 in UUID a b c d e f g' h i' j k l m n o p
59 _ -> error "not enough random numbers for UUID" -- should not happen
61getRandomUUID :: IO UUID
62getRandomUUID = getUUID <$> getStdGen