Safe Haskell | None |
---|
TNET
is a library that implements the TNET serialization protocol
to be used for PGI
(http://code.google.com/p/polyweb/source/browse/doc/PGI.txt)
applications. The TNET protocol
(http://tnetstrings.org) is designed to be simple to implement in
any language, please look at the README for the changes to the
original tnetstrings spec.
TNET Parser
Classes
The TNET
typeclass represents types that
can be encoded and decoded in the TNET format.
An example instance:
data Person = Person { name :: String , age :: Integer } instance TNET Person where toTNET (Person n a) = dict [ "name" .= n , "age" .= a ] fromTNET tval = do n <- tval .: "name" a <- tval .: "age" return $ Person n a
Types
A TValue
represents a raw TNET object. TNET values
are one of the following types:
- a string of bytes
- a UTF-8 encoded string
- an integer
- a floating point number
- a boolean
- null
- a dictionary type
- a list of TValues
TNET serialization functions
decode :: TNET a => ByteString -> Maybe aSource
Decode a TNET format bytestring into a Haskell value. An explicit type annotation may be needed if the type of the decoded value can not be determined:
>>>
decode "0:~" :: Maybe ()
Just ()
>>>
decode "0:~" :: Maybe (Maybe String)
Just Nothing
>>>
decode "1:5#" :: Maybe Integer
Just 5
let x = decode "4:true!" in case x of Just True -> putStrLn "got true!" Just False -> putStrLn "got false!" Nothing -> putStrLn "error decoding"
encode :: TNET a => a -> ByteStringSource
Encode a Haskell value into the TNET format. Some examples:
>>>
encode 5
"1:5#"
>>>
encode "Hello"
"5:Hello$"
>>>
encode (-12.3)
"5:-12.3^"
>>>
encode ()
"0:~"
Helpers for defining TNET datatypes
dict :: [(String, TValue)] -> TValueSource
Used to create a TNET dictionary from
TNET values. Meant to be used with the
.=
operator as in the following example:
myDict = dict [ "a" .= 5 , "is_dict" .= True ]
(.:) :: TNET a => TValue -> String -> Maybe aSource
Helper function to extract TNET values from a TNET dictionary. Meant to be used as in the following example:
data Person = Person { name :: String , age :: Integer } personFromDict :: TValue -> Maybe Person personFromDict tdict = do name <- tdict .: "name" age <- tdict .: "age" return $ Person name age