@@ -0,0 +1,46 @@
1+{-
2+
3+This file is part of the Haskell package cassava-streams. It is
4+subject to the license terms in the LICENSE file found in the
5+top-level directory of this distribution and at
6+git://pmade.com/cassava-streams/LICENSE. No part of cassava-streams
7+package, including this file, may be copied, modified, propagated, or
8+distributed except according to the terms contained in the LICENSE
9+file.
10+
11+-}
12+
13+--------------------------------------------------------------------------------
14+module System.IO.Streams.Csv.Encode
15+ ( encodeStream
16+ , encodeStreamByName
17+ ) where
18+
19+--------------------------------------------------------------------------------
20+import Data.ByteString (ByteString)
21+import Data.Csv
22+import System.IO.Streams (OutputStream, makeOutputStream)
23+import qualified System.IO.Streams as Streams
24+
25+--------------------------------------------------------------------------------
26+-- | Create a new @OutputStream@ that can be fed @ToRecord@ values
27+-- which are converted to CSV. The records are encoded into
28+-- @ByteString@s and passed on to the given downstream @OutputStream@.
29+encodeStream :: ToRecord a
30+ => OutputStream ByteString -- ^ Downstream.
31+ -> IO (OutputStream a) -- ^ New @OutputStream@.
32+encodeStream output = makeOutputStream stream where
33+ stream Nothing = Streams.write Nothing output
34+ stream (Just x) = Streams.writeLazyByteString (encode [x]) output
35+
36+--------------------------------------------------------------------------------
37+-- | Create a new @OutputStream@ that can be fed @ToNamedRecord@
38+-- values which are converted to CSV. The records are encoded into
39+-- @ByteString@s and passed on to the given downstream @OutputStream@.
40+encodeStreamByName :: ToNamedRecord a
41+ => Header -- ^ CSV Header.
42+ -> OutputStream ByteString -- ^ Downstream.
43+ -> IO (OutputStream a) -- ^ New @OutputStream@.
44+encodeStreamByName hdr output = makeOutputStream stream where
45+ stream Nothing = Streams.write Nothing output
46+ stream (Just x) = Streams.writeLazyByteString (encodeByName hdr [x]) output