This codec module implements a subset of XDR -- eXternal Data Representation (RFC: 4506)
A thin wrapper around the cereal package, inspired by Python's xdrlib.
There are 2 representations of string:
- plain Haskell string, assuming UTF-8-encoded (see examples);
- lazy bytestring, for ASCII texts & so-called opaque data.
Strings in other encodings can always be transformed from/to lazy bytestrings using the proper
encode
/decode
function pair.
Using this module is quite simple (as the name implies).
Don't forget to enable the ScopedTypeVariables
extension.
- String: "abcd测试"
- UInt: 123456
- Hyper: -1234567890
- Boolean: False
- Float: 5.7
- Double: 6.4
- Array of Strings: ["hello", "world"]
- Array of Doubles: [1.9, 2.2, 3.141592653589793238462643383279502884, 0.0]
Output will be written to "test.data".
testPack :: IO ()
testPack = LBS.writeFile "test.data" (xdrPack packs)
where packs = do
pack "abcd测试"
pack (123456 :: UInt)
pack (-1234567890 :: Hyper)
pack False
pack (5.7 :: Float)
pack (6.4 :: Double)
pack ["hello", "world"]
pack ([1.9, 2.2, 3.141592653589793238462643383279502884, 0.0] :: [Double])
Read a file named "test.data" (...contains data previously generated by testPack
).
Print out the result of unpack
ing.
testUnpack :: IO ()
testUnpack = do
dat <- LBS.readFile "test.data"
let (Right result) = xdrUnpack unpacks dat
putStrLn result
where unpacks = do
a :: String <- unpack
b :: UInt <- unpack
c :: Hyper <- unpack
d :: Bool <- unpack
e :: Float <- unpack
f :: Double <- unpack
g :: [String] <- unpack
h :: [Double] <- unpack
return $ "got" ++
": string " ++ a ++
", uint " ++ show b ++
", hyper " ++ show c ++
", boolean " ++ show d ++
", float " ++ show e ++
", double " ++ show f ++
", a list of strings " ++ show g ++
", a list of doubles " ++ show h ++ "."
See examples/GangliaMessage.hs