1 {-# LANGUAGE RankNTypes, TypeFamilies, CPP #-}
3 {-| This module provides @pipes@ utilities for \"text streams\", which are
4 streams of 'Text' chunks. The individual chunks are uniformly @strict@, but
5 a 'Producer' can be converted to and from lazy 'Text's; an 'IO.Handle' can
6 be associated with a 'Producer' or 'Consumer' according as it is read or written to.
8 To stream to or from 'IO.Handle's, one can use 'fromHandle' or 'toHandle'. For
9 example, the following program copies a document from one file to another:
12 > import qualified Data.Text.Pipes as Text
16 > withFile "inFile.txt" ReadMode $ \hIn ->
17 > withFile "outFile.txt" WriteMode $ \hOut ->
18 > runEffect $ Text.fromHandle hIn >-> Text.toHandle hOut
20 To stream from files, the following is perhaps more Prelude-like (note that it uses Pipes.Safe):
23 > import qualified Data.Text.Pipes as Text
26 > main = runSafeT $ runEffect $ Text.readFile "inFile.txt" >-> Text.writeFile "outFile.txt"
28 You can stream to and from 'stdin' and 'stdout' using the predefined 'stdin'
29 and 'stdout' proxies, as with the following \"echo\" program:
31 > main = runEffect $ Text.stdin >-> Text.stdout
33 You can also translate pure lazy 'TL.Text's to and from proxies:
35 > main = runEffect $ Text.fromLazy (TL.pack "Hello, world!\n") >-> Text.stdout
37 In addition, this module provides many functions equivalent to lazy
38 'Text' functions so that you can transform or fold text streams. For
39 example, to stream only the first three lines of 'stdin' to 'stdout' you
43 > import qualified Pipes.Text as Text
44 > import qualified Pipes.Parse as Parse
46 > main = runEffect $ takeLines 3 Text.stdin >-> Text.stdout
48 > takeLines n = Text.unlines . Parse.takeFree n . Text.lines
50 The above program will never bring more than one chunk of text (~ 32 KB) into
51 memory, no matter how long the lines are.
53 Note that functions in this library are designed to operate on streams that
54 are insensitive to text boundaries. This means that they may freely split
55 text into smaller texts and /discard empty texts/. However, they will
56 /never concatenate texts/ in order to provide strict upper bounds on memory
84 #if MIN_VERSION_text(0,11,4)
122 #if MIN_VERSION_text(0,11,4)
134 -- * Character Parsers
148 import Control.Exception (throwIO, try)
149 import Control.Monad (liftM, unless)
150 import Control.Monad.Trans.State.Strict (StateT(..))
151 import qualified Data.Text as T
152 import qualified Data.Text.IO as T
153 import qualified Data.Text.Encoding as TE
154 import qualified Data.Text.Encoding.Error as TE
155 import Data.Text (Text)
156 import qualified Data.Text.Lazy as TL
157 import qualified Data.Text.Lazy.IO as TL
158 import Data.Text.Lazy.Internal (foldrChunks, defaultChunkSize)
159 import Data.ByteString.Unsafe (unsafeTake, unsafeDrop)
160 import Data.ByteString (ByteString)
161 import qualified Data.ByteString as B
162 import Data.Char (ord, isSpace)
163 import Data.Functor.Identity (Identity)
164 import qualified Data.List as List
165 import Foreign.C.Error (Errno(Errno), ePIPE)
166 import qualified GHC.IO.Exception as G
168 import qualified Pipes.ByteString.Parse as PBP
169 import Pipes.Text.Parse (
170 nextChar, drawChar, unDrawChar, peekChar, isEndOfChars )
171 import Pipes.Core (respond, Server')
172 import qualified Pipes.Parse as PP
173 import Pipes.Parse (input, concat, FreeT)
174 import qualified Pipes.Safe.Prelude as Safe
175 import qualified Pipes.Safe as Safe
176 import Pipes.Safe (MonadSafe(..), Base(..))
177 import qualified Pipes.Prelude as P
178 import qualified System.IO as IO
179 import Data.Char (isSpace)
180 import Data.Word (Word8)
181 import Prelude hiding (
210 -- | Convert a lazy 'TL.Text' into a 'Producer' of strict 'Text's
211 fromLazy :: (Monad m) => TL.Text -> Producer' Text m ()
212 fromLazy = foldrChunks (\e a -> yield e >> a) (return ())
213 {-# INLINABLE fromLazy #-}
215 -- | Stream text from 'stdin'
216 stdin :: MonadIO m => Producer' Text m ()
217 stdin = fromHandle IO.stdin
218 {-# INLINABLE stdin #-}
220 {-| Convert a 'IO.Handle' into a text stream using a text size
221 determined by the good sense of the text library.
225 fromHandle :: MonadIO m => IO.Handle -> Producer' Text m ()
226 fromHandle h = go where
227 go = do txt <- liftIO (T.hGetChunk h)
228 unless (T.null txt) $ do yield txt
230 {-# INLINABLE fromHandle#-}
232 {-| Stream text from a file using Pipes.Safe
234 >>> runSafeT $ runEffect $ Text.readFile "hello.hs" >-> Text.map toUpper >-> hoist lift Text.stdout
235 MAIN = PUTSTRLN "HELLO WORLD"
238 readFile :: (MonadSafe m, Base m ~ IO) => FilePath -> Producer' Text m ()
239 readFile file = Safe.withFile file IO.ReadMode fromHandle
240 {-# INLINABLE readFile #-}
242 {-| Stream lines of text from stdin (for testing in ghci etc.)
244 >>> let safely = runSafeT . runEffect
245 >>> safely $ for Text.stdinLn (lift . lift . print . T.length)
252 stdinLn :: MonadIO m => Producer' Text m ()
255 eof <- liftIO (IO.hIsEOF IO.stdin)
257 txt <- liftIO (T.hGetLine IO.stdin)
262 {-| Stream text to 'stdout'
264 Unlike 'toHandle', 'stdout' gracefully terminates on a broken output pipe.
266 Note: For best performance, use @(for source (liftIO . putStr))@ instead of
267 @(source >-> stdout)@ in suitable cases.
269 stdout :: MonadIO m => Consumer' Text m ()
274 x <- liftIO $ try (T.putStr txt)
276 Left (G.IOError { G.ioe_type = G.ResourceVanished
277 , G.ioe_errno = Just ioe })
280 Left e -> liftIO (throwIO e)
282 {-# INLINABLE stdout #-}
284 stdoutLn :: (MonadIO m) => Consumer' Text m ()
289 x <- liftIO $ try (T.putStrLn str)
291 Left (G.IOError { G.ioe_type = G.ResourceVanished
292 , G.ioe_errno = Just ioe })
295 Left e -> liftIO (throwIO e)
297 {-# INLINABLE stdoutLn #-}
299 {-| Convert a text stream into a 'Handle'
301 Note: again, for best performance, where possible use
302 @(for source (liftIO . hPutStr handle))@ instead of @(source >-> toHandle handle)@.
304 toHandle :: MonadIO m => IO.Handle -> Consumer' Text m r
305 toHandle h = for cat (liftIO . T.hPutStr h)
306 {-# INLINABLE toHandle #-}
308 {-# RULES "p >-> toHandle h" forall p h .
309 p >-> toHandle h = for p (\txt -> liftIO (T.hPutStr h txt))
313 -- | Stream text into a file. Uses @pipes-safe@.
314 writeFile :: (MonadSafe m, Base m ~ IO) => FilePath -> Consumer' Text m ()
315 writeFile file = Safe.withFile file IO.WriteMode toHandle
317 -- | Apply a transformation to each 'Char' in the stream
318 map :: (Monad m) => (Char -> Char) -> Pipe Text Text m r
319 map f = P.map (T.map f)
320 {-# INLINABLE map #-}
322 {-# RULES "p >-> map f" forall p f .
323 p >-> map f = for p (\txt -> yield (T.map f txt))
326 -- | Map a function over the characters of a text stream and concatenate the results
328 :: (Monad m) => (Char -> Text) -> Pipe Text Text m r
329 concatMap f = P.map (T.concatMap f)
330 {-# INLINABLE concatMap #-}
332 {-# RULES "p >-> concatMap f" forall p f .
333 p >-> concatMap f = for p (\txt -> yield (T.concatMap f txt))
336 -- | Transform a Pipe of 'Text' into a Pipe of 'ByteString's using UTF-8
337 -- encoding; @encodeUtf8 = Pipes.Prelude.map TE.encodeUtf8@ so more complex
338 -- encoding pipes can easily be constructed with the functions in @Data.Text.Encoding@
339 encodeUtf8 :: Monad m => Pipe Text ByteString m r
340 encodeUtf8 = P.map TE.encodeUtf8
341 {-# INLINEABLE encodeUtf8 #-}
343 {-# RULES "p >-> encodeUtf8" forall p .
344 p >-> encodeUtf8 = for p (\txt -> yield (TE.encodeUtf8 txt))
347 -- | Transform a Pipe of 'String's into one of 'Text' chunks
348 pack :: Monad m => Pipe String Text m r
350 {-# INLINEABLE pack #-}
352 {-# RULES "p >-> pack" forall p .
353 p >-> pack = for p (\txt -> yield (T.pack txt))
356 -- | Transform a Pipes of 'Text' chunks into one of 'String's
357 unpack :: Monad m => Pipe Text String m r
358 unpack = for cat (\t -> yield (T.unpack t))
359 {-# INLINEABLE unpack #-}
361 {-# RULES "p >-> unpack" forall p .
362 p >-> unpack = for p (\txt -> yield (T.unpack txt))
365 -- | @toCaseFold@, @toLower@, @toUpper@ and @stripStart@ are standard 'Text' utility,
366 -- here acting on a 'Text' pipe, rather as they would on a lazy text
367 toCaseFold :: Monad m => Pipe Text Text m ()
368 toCaseFold = P.map T.toCaseFold
369 {-# INLINEABLE toCaseFold #-}
371 {-# RULES "p >-> toCaseFold" forall p .
372 p >-> toCaseFold = for p (\txt -> yield (T.toCaseFold txt))
376 -- | lowercase incoming 'Text'
377 toLower :: Monad m => Pipe Text Text m ()
378 toLower = P.map T.toLower
379 {-# INLINEABLE toLower #-}
381 {-# RULES "p >-> toLower" forall p .
382 p >-> toLower = for p (\txt -> yield (T.toLower txt))
385 -- | uppercase incoming 'Text'
386 toUpper :: Monad m => Pipe Text Text m ()
387 toUpper = P.map T.toUpper
388 {-# INLINEABLE toUpper #-}
390 {-# RULES "p >-> toUpper" forall p .
391 p >-> toUpper = for p (\txt -> yield (T.toUpper txt))
394 -- | Remove leading white space from an incoming succession of 'Text's
395 stripStart :: Monad m => Pipe Text Text m r
398 let text = T.stripStart chunk
402 {-# INLINEABLE stripStart #-}
404 -- | @(take n)@ only allows @n@ individual characters to pass;
405 -- contrast @Pipes.Prelude.take@ which would let @n@ chunks pass.
406 take :: (Monad m, Integral a) => a -> Pipe Text Text m ()
407 take n0 = go n0 where
412 let len = fromIntegral (T.length txt)
414 then yield (T.take (fromIntegral n) txt)
418 {-# INLINABLE take #-}
420 -- | @(drop n)@ drops the first @n@ characters
421 drop :: (Monad m, Integral a) => a -> Pipe Text Text m r
422 drop n0 = go n0 where
427 let len = fromIntegral (T.length txt)
430 yield (T.drop (fromIntegral n) txt)
433 {-# INLINABLE drop #-}
435 -- | Take characters until they fail the predicate
436 takeWhile :: (Monad m) => (Char -> Bool) -> Pipe Text Text m ()
437 takeWhile predicate = go
441 let (prefix, suffix) = T.span predicate txt
447 {-# INLINABLE takeWhile #-}
449 -- | Drop characters until they fail the predicate
450 dropWhile :: (Monad m) => (Char -> Bool) -> Pipe Text Text m r
451 dropWhile predicate = go where
454 case T.findIndex (not . predicate) txt of
459 {-# INLINABLE dropWhile #-}
461 -- | Only allows 'Char's to pass if they satisfy the predicate
462 filter :: (Monad m) => (Char -> Bool) -> Pipe Text Text m r
463 filter predicate = P.map (T.filter predicate)
464 {-# INLINABLE filter #-}
466 {-# RULES "p >-> filter q" forall p q .
467 p >-> filter q = for p (\txt -> yield (T.filter q txt))
470 -- | Strict left scan over the characters
473 => (Char -> Char -> Char) -> Char -> Pipe Text Text m r
474 scan step begin = go begin
478 let txt' = T.scanl step c txt
482 {-# INLINABLE scan #-}
484 {-| Fold a pure 'Producer' of strict 'Text's into a lazy
487 toLazy :: Producer Text Identity () -> TL.Text
488 toLazy = TL.fromChunks . P.toList
489 {-# INLINABLE toLazy #-}
491 {-| Fold an effectful 'Producer' of strict 'Text's into a lazy
494 Note: 'toLazyM' is not an idiomatic use of @pipes@, but I provide it for
495 simple testing purposes. Idiomatic @pipes@ style consumes the chunks
496 immediately as they are generated instead of loading them all into memory.
498 toLazyM :: (Monad m) => Producer Text m () -> m TL.Text
499 toLazyM = liftM TL.fromChunks . P.toListM
500 {-# INLINABLE toLazyM #-}
502 -- | Reduce the text stream using a strict left fold over characters
505 => (x -> Char -> x) -> x -> (x -> r) -> Producer Text m () -> m r
506 fold step begin done = P.fold (T.foldl' step) begin done
507 {-# INLINABLE fold #-}
509 -- | Retrieve the first 'Char'
510 head :: (Monad m) => Producer Text m () -> m (Maybe Char)
516 Left _ -> return Nothing
517 Right (c, _) -> return (Just c)
518 {-# INLINABLE head #-}
520 -- | Retrieve the last 'Char'
521 last :: (Monad m) => Producer Text m () -> m (Maybe Char)
531 else go (Just $ T.last txt) p'
532 {-# INLINABLE last #-}
534 -- | Determine if the stream is empty
535 null :: (Monad m) => Producer Text m () -> m Bool
537 {-# INLINABLE null #-}
539 -- | Count the number of characters in the stream
540 length :: (Monad m, Num n) => Producer Text m () -> m n
541 length = P.fold (\n txt -> n + fromIntegral (T.length txt)) 0 id
542 {-# INLINABLE length #-}
544 -- | Fold that returns whether 'M.Any' received 'Char's satisfy the predicate
545 any :: (Monad m) => (Char -> Bool) -> Producer Text m () -> m Bool
546 any predicate = P.any (T.any predicate)
547 {-# INLINABLE any #-}
549 -- | Fold that returns whether 'M.All' received 'Char's satisfy the predicate
550 all :: (Monad m) => (Char -> Bool) -> Producer Text m () -> m Bool
551 all predicate = P.all (T.all predicate)
552 {-# INLINABLE all #-}
554 -- | Return the maximum 'Char' within a text stream
555 maximum :: (Monad m) => Producer Text m () -> m (Maybe Char)
556 maximum = P.fold step Nothing id
561 else Just $ case mc of
562 Nothing -> T.maximum txt
563 Just c -> max c (T.maximum txt)
564 {-# INLINABLE maximum #-}
566 -- | Return the minimum 'Char' within a text stream (surely very useful!)
567 minimum :: (Monad m) => Producer Text m () -> m (Maybe Char)
568 minimum = P.fold step Nothing id
574 Nothing -> Just (T.minimum txt)
575 Just c -> Just (min c (T.minimum txt))
576 {-# INLINABLE minimum #-}
578 -- | Find the first element in the stream that matches the predicate
581 => (Char -> Bool) -> Producer Text m () -> m (Maybe Char)
582 find predicate p = head (p >-> filter predicate)
583 {-# INLINABLE find #-}
585 -- | Index into a text stream
587 :: (Monad m, Integral a)
588 => a-> Producer Text m () -> m (Maybe Char)
589 index n p = head (p >-> drop n)
590 {-# INLINABLE index #-}
593 -- | Store a tally of how many segments match the given 'Text'
594 count :: (Monad m, Num n) => Text -> Producer Text m () -> m n
595 count c p = P.fold (+) 0 id (p >-> P.map (fromIntegral . T.count c))
596 {-# INLINABLE count #-}
598 #if MIN_VERSION_text(0,11,4)
599 -- | Transform a Pipe of 'ByteString's expected to be UTF-8 encoded
600 -- into a Pipe of Text
603 => Producer ByteString m r -> Producer Text m (Producer ByteString m r)
604 decodeUtf8 = go TE.streamDecodeUtf8
608 Left r -> return (return r)
609 Right (chunk, p') -> do
610 let TE.Some text l dec' = dec chunk
618 {-# INLINEABLE decodeUtf8 #-}
620 -- | Transform a Pipe of 'ByteString's expected to be UTF-8 encoded
621 -- into a Pipe of Text with a replacement function of type @String -> Maybe Word8 -> Maybe Char@
622 -- E.g. 'Data.Text.Encoding.Error.lenientDecode', which simply replaces bad bytes with \"�\"
626 -> Producer ByteString m r -> Producer Text m (Producer ByteString m r)
627 decodeUtf8With onErr = go (TE.streamDecodeUtf8With onErr)
631 Left r -> return (return r)
632 Right (chunk, p') -> do
633 let TE.Some text l dec' = dec chunk
641 {-# INLINEABLE decodeUtf8With #-}
643 -- | A simple pipe from 'ByteString' to 'Text'; a decoding error will arise
644 -- with any chunk that contains a sequence of bytes that is unreadable. Otherwise
645 -- only few bytes will only be moved from one chunk to the next before decoding.
646 pipeDecodeUtf8 :: Monad m => Pipe ByteString Text m r
647 pipeDecodeUtf8 = go TE.streamDecodeUtf8
648 where go dec = do chunk <- await
650 TE.Some text l dec' -> do yield text
652 {-# INLINEABLE pipeDecodeUtf8 #-}
654 -- | A simple pipe from 'ByteString' to 'Text' using a replacement function.
658 -> Pipe ByteString Text m r
659 pipeDecodeUtf8With onErr = go (TE.streamDecodeUtf8With onErr)
660 where go dec = do chunk <- await
662 TE.Some text l dec' -> do yield text
664 {-# INLINEABLE pipeDecodeUtf8With #-}
667 -- | Splits a 'Producer' after the given number of characters
669 :: (Monad m, Integral n)
672 -> Producer' Text m (Producer Text m r)
679 Left r -> return (return r)
680 Right (txt, p') -> do
681 let len = fromIntegral (T.length txt)
687 let (prefix, suffix) = T.splitAt (fromIntegral n) txt
689 return (yield suffix >> p')
690 {-# INLINABLE splitAt #-}
692 -- | Split a text stream into 'FreeT'-delimited text streams of fixed size
694 :: (Monad m, Integral n)
695 => n -> Producer Text m r -> FreeT (Producer Text m) m r
696 chunksOf n p0 = PP.FreeT (go p0)
702 Right (txt, p') -> PP.Free $ do
703 p'' <- splitAt n (yield txt >> p')
704 return $ PP.FreeT (go p'')
705 {-# INLINABLE chunksOf #-}
707 {-| Split a text stream in two, where the first text stream is the longest
708 consecutive group of text that satisfy the predicate
714 -> Producer' Text m (Producer Text m r)
720 Left r -> return (return r)
721 Right (txt, p') -> do
722 let (prefix, suffix) = T.span predicate txt
729 return (yield suffix >> p')
730 {-# INLINABLE span #-}
732 {-| Split a text stream in two, where the first text stream is the longest
733 consecutive group of characters that don't satisfy the predicate
739 -> Producer Text m (Producer Text m r)
740 break predicate = span (not . predicate)
741 {-# INLINABLE break #-}
743 {-| Split a text stream into sub-streams delimited by characters that satisfy the
750 -> PP.FreeT (Producer Text m) m r
751 splitWith predicate p0 = PP.FreeT (go0 p0)
756 Left r -> return (PP.Pure r)
760 else return $ PP.Free $ do
761 p'' <- span (not . predicate) (yield txt >> p')
762 return $ PP.FreeT (go1 p'')
767 Right (_, p') -> PP.Free $ do
768 p'' <- span (not . predicate) p'
769 return $ PP.FreeT (go1 p'')
770 {-# INLINABLE splitWith #-}
772 -- | Split a text stream using the given 'Char' as the delimiter
776 -> FreeT (Producer Text m) m r
777 split c = splitWith (c ==)
778 {-# INLINABLE split #-}
780 {-| Group a text stream into 'FreeT'-delimited text streams using the supplied
785 => (Char -> Char -> Bool)
787 -> FreeT (Producer Text m) m r
788 groupBy equal p0 = PP.FreeT (go p0)
793 Left r -> return (PP.Pure r)
794 Right (txt, p') -> case (T.uncons txt) of
797 return $ PP.Free $ do
798 p'' <- span (equal c) (yield txt >> p')
799 return $ PP.FreeT (go p'')
800 {-# INLINABLE groupBy #-}
802 -- | Group a text stream into 'FreeT'-delimited text streams of identical characters
804 :: (Monad m) => Producer Text m r -> FreeT (Producer Text m) m r
806 {-# INLINABLE group #-}
808 {-| Split a text stream into 'FreeT'-delimited lines
811 :: (Monad m) => Producer Text m r -> FreeT (Producer Text m) m r
812 lines p0 = PP.FreeT (go0 p0)
817 Left r -> return (PP.Pure r)
821 else return $ PP.Free $ go1 (yield txt >> p')
823 p' <- break ('\n' ==) p
824 return $ PP.FreeT $ do
827 Left r -> return $ PP.Pure r
828 Right (_, p'') -> go0 p''
829 {-# INLINABLE lines #-}
833 -- | Split a text stream into 'FreeT'-delimited words
835 :: (Monad m) => Producer Text m r -> FreeT (Producer Text m) m r
839 x <- next (p >-> dropWhile isSpace)
842 Right (bs, p') -> PP.Free $ do
843 p'' <- break isSpace (yield bs >> p')
845 {-# INLINABLE words #-}
848 -- | Intersperse a 'Char' in between the characters of the text stream
850 :: (Monad m) => Char -> Producer Text m r -> Producer Text m r
857 Right (txt, p') -> do
858 yield (T.intersperse c txt)
864 Right (txt, p') -> do
865 yield (T.singleton c)
866 yield (T.intersperse c txt)
868 {-# INLINABLE intersperse #-}
870 {-| 'intercalate' concatenates the 'FreeT'-delimited text streams after
871 interspersing a text stream in between them
875 => Producer Text m ()
876 -> FreeT (Producer Text m) m r
881 x <- lift (PP.runFreeT f)
883 PP.Pure r -> return r
888 x <- lift (PP.runFreeT f)
890 PP.Pure r -> return r
895 {-# INLINABLE intercalate #-}
897 {-| Join 'FreeT'-delimited lines into a text stream
900 :: (Monad m) => FreeT (Producer Text m) m r -> Producer Text m r
904 x <- lift (PP.runFreeT f)
906 PP.Pure r -> return r
909 yield $ T.singleton '\n'
911 {-# INLINABLE unlines #-}
913 {-| Join 'FreeT'-delimited words into a text stream
916 :: (Monad m) => FreeT (Producer Text m) m r -> Producer Text m r
917 unwords = intercalate (yield $ T.pack " ")
918 {-# INLINABLE unwords #-}
921 The following parsing utilities are single-character analogs of the ones found
926 @Pipes.Text.Parse@ re-exports 'nextChar', 'drawChar', 'unDrawChar', 'peekChar', and 'isEndOfChars'.
928 @Data.Text@ re-exports the 'Text' type.
930 @Pipes.Parse@ re-exports 'input', 'concat', and 'FreeT' (the type).