Debian Codegraph @

Data/ASN1/BinaryEncoding/Writer.hs

raw
1 -- |
2 -- Module : Data.ASN1.BinaryEncoding.Writer
3 -- License : BSD-style
4 -- Maintainer : Vincent Hanquez <[email protected]>
5 -- Stability : experimental
6 -- Portability : unknown
7 --
8 -- Serialize events for streaming.
9 --
10 module Data.ASN1.BinaryEncoding.Writer
11 ( toByteString
12 , toLazyByteString
13 ) where
14
15 import Data.ByteString (ByteString)
16 import qualified Data.ByteString as B
17 import qualified Data.ByteString.Lazy as L
18 import Data.ASN1.Types.Lowlevel
19 import Data.ASN1.Serialize
20
21 -- | transform a list of ASN1 Events into a strict bytestring
22 toByteString :: [ASN1Event] -> ByteString
23 toByteString = B.concat . L.toChunks . toLazyByteString
24
25 -- | transform a list of ASN1 Events into a lazy bytestring
26 toLazyByteString :: [ASN1Event] -> L.ByteString
27 toLazyByteString evs = L.fromChunks $ loop [] evs
28 where loop _ [] = []
29 loop acc (x@(Header (ASN1Header _ _ pc len)):xs) = toBs x : loop (if pc then (len == LenIndefinite):acc else acc) xs
30 loop acc (ConstructionEnd:xs) = case acc of
31 [] -> error "malformed stream: end before construction"
32 (True:r) -> toBs ConstructionEnd : loop r xs
33 (False:r) -> loop r xs
34 loop acc (x:xs) = toBs x : loop acc xs
35
36 toBs (Header hdr) = putHeader hdr
37 toBs (Primitive bs) = bs
38 toBs ConstructionBegin = B.empty
39 toBs ConstructionEnd = B.empty