on master help sign in
ByteString conversion and nil constant
commit13188f0a922c37228055de3a4facd53bd0ecdea7 authorMark Lentczner <markl@glyphic.com> dateTue 24 Nov 2009, 05:39 (17 years ago) parent396df9a
2 files changed+25−2
Data/UUID.hs+5−1 Data/UUID/Internal.hs+20−1
Data/UUID.hs+5−1
@@ -12,6 +12,7 @@
1212-- This library is useful for comparing, parsing and
1313-- printing Universally Unique Identifiers.
1414-- See <http://en.wikipedia.org/wiki/UUID> for the general idea.
15+-- See <http://tools.ietf.org/html/rfc4122> for the specification.
1516--
1617-- For generating UUIDs, check out 'Data.UUID.V1', 'Data.UUID.V5' and
1718-- 'System.Random'.
@@ -19,7 +20,10 @@
1920module Data.UUID(UUID
2021 ,toString
2122 ,fromString
23+ ,toByteString
24+ ,fromByteString
2225 ,null
26+ ,nil
2327 ) where
2428
2529import Prelude hiding (null)
@@ -27,4 +31,4 @@ import Data.UUID.Internal
2731
2832-- Everything is really implemented in Data.UUID.Internal,
2933-- but I don't want to export the constructors out of the
30−-- package.
34+-- package.
Data/UUID/Internal.hs+20−1
@@ -13,10 +13,13 @@
1313module Data.UUID.Internal
1414 (UUID(..)
1515 ,null
16+ ,nil
1617 ,Node(..)
1718 ,nullNode
1819 ,nodeToList
1920 ,listToNode
21+ ,fromByteString
22+ ,toByteString
2023 ,fromString
2124 ,toString
2225 ,versionMask
@@ -47,6 +50,7 @@ import Foreign.Storable
4750import Data.Binary
4851import Data.Binary.Put
4952import Data.Binary.Get
53+import qualified Data.ByteString.Lazy as Lazy
5054
5155import System.Random
5256
@@ -71,11 +75,16 @@ data UUID = UUID
7175 ,uuid_node :: SLOT(Node)
7276 } deriving (Eq, Ord, Typeable)
7377
74−-- |Returns true if the passed-in UUID is the null UUID.
78+-- |Returns true if the passed-in UUID is the 'nil' UUID.
7579null :: UUID -> Bool
7680null (UUID 0 0 0 0 0 node) | nullNode node = True
7781null _ = False
7882
83+-- |The nil UUID, as defined in RFC 4122.
84+-- It is a UUID of all zeros. @'null' u@ iff @'u' == 'nil'@.
85+nil :: UUID
86+nil = UUID 0 0 0 0 0 (Node 0 0 0 0 0 0)
87+
7988instance Random UUID where
8089 random g = let (timeLow, g1) = randomBoundedIntegral g
8190 (timeMid, g2) = randomBoundedIntegral g1
@@ -220,6 +229,16 @@ instance Binary Node where
220229 return $ Node w1 w2 w3 w4 w5 w6
221230
222231
232+-- |Extract a UUID from a 'ByteString'.
233+-- The argument must be 16 bytes long, otherwise 'nil' is returned.
234+fromByteString :: Lazy.ByteString -> UUID
235+fromByteString bs | Lazy.length bs == 16 = decode bs
236+ | otherwise = nil
237+
238+-- |Encode a UUID into a 'ByteString' in network order.
239+toByteString :: UUID -> Lazy.ByteString
240+toByteString uu = encode uu
241+
223242-- My goal with this instance was to make it work just enough to do what
224243-- I want when used with the HStringTemplate library.
225244instance Data UUID where