HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Modulestreaming-bytestring-0.3.2Haskell2010

Streaming.ByteString

See the simple examples of use here and the ghci examples especially in Streaming.ByteString.Char8. We begin with a slight modification of the documentation to Data.ByteString.Lazy:

A time and space-efficient implementation of effectful byte streams using a stream of packed Word8 arrays, suitable for high performance use, both in terms of large data quantities, or high speed requirements. Streaming ByteStrings are encoded as streams of strict chunks of bytes.

A key feature of streaming ByteStrings is the means to manipulate large or unbounded streams of data without requiring the entire sequence to be resident in memory. To take advantage of this you have to write your functions in a streaming style, e.g. classic pipeline composition. The default I/O chunk size is 32k, which should be good in most circumstances.

Some operations, such as concat, append, and cons, have better complexity than their Data.ByteString equivalents, due to optimisations resulting from the list spine structure. For other operations streaming, like lazy, ByteStrings are usually within a few percent of strict ones.

This module is intended to be imported qualified, to avoid name clashes with Prelude functions. eg.

import qualified Streaming.ByteString as Q

Original GHC implementation by Bryan O'Sullivan. Rewritten to use UArray by Simon Marlow. Rewritten to support slices and use ForeignPtr by David Roundy. Rewritten again and extended by Don Stewart and Duncan Coutts. Lazy variant by Duncan Coutts and Don Stewart. Streaming variant by Michael Thompson, following the ideas of Gabriel Gonzales' pipes-bytestring.

  • 2 types
  • 95 values

The ByteStream type

2 declarations
datadata ByteStream (m :: Type -> Type) r
#

A space-efficient representation of a succession of Word8 vectors, supporting many efficient operations.

An effectful ByteStream contains 8-bit bytes, or by using the operations from Streaming.ByteString.Char8 it can be interpreted as containing 8-bit characters.

Instances14MonadTrans, MFunctor, MonadBase, Monad, Functor, Applicative, …
typetype ByteString = ByteStream
#

Deprecated. Use ByteStream instead.

A type alias for back-compatibility.

Introducing and eliminating ByteStreams

16 declarations
valueempty :: ByteStream m ()
#

O(1) The empty ByteStream -- i.e. return () Note that ByteStream m w is generally a monoid for monoidal values of w, like ().

valuefromLazy :: Monad m => ByteString -> ByteStream m ()
#

O(c) Transmute a pseudo-pure lazy bytestring to its representation as a monadic stream of chunks.

Example3 expressions
Q.putStrLn $ Q.fromLazy "hi"hiQ.fromLazy "hi"Chunk "hi" (Empty (()))  -- note: a 'show' instance works in the identity monadQ.fromLazy $ BL.fromChunks ["here", "are", "some", "chunks"]Chunk "here" (Chunk "are" (Chunk "some" (Chunk "chunks" (Empty (())))))
valuetoLazy :: Monad m => ByteStream m r -> m (Of ByteString r)
#

O(n) Convert an effectful byte stream into a single lazy ByteString with the same internal chunk structure, retaining the original return value.

This is the canonical way of breaking streaming (toStrict and the like are far more demonic). Essentially one is dividing the interleaved layers of effects and bytes into one immense layer of effects, followed by the memory of the succession of bytes.

Because one preserves the return value, toLazy is a suitable argument for mapped:

S.mapped Q.toLazy :: Stream (ByteStream m) m r -> Stream (Of L.ByteString) m r
Example2 expressions
Q.toLazy "hello""hello" :> ()S.toListM $ traverses Q.toLazy $ Q.lines "one\ntwo\nthree\nfour\nfive\n"["one","two","three","four","five",""]  -- [L.ByteString]
valuetoLazy_ :: Monad m => ByteStream m r -> m ByteString
#

O(n) Convert an effectful byte stream into a single lazy ByteStream with the same internal chunk structure. See toLazy which preserve connectedness by keeping the return value of the effectful bytestring.

valuetoStrict :: Monad m => ByteStream m r -> m (Of ByteString r)
#

O(n) Convert a monadic byte stream into a single strict ByteString, retaining the return value of the original pair. This operation is for use with mapped.

mapped R.toStrict :: Monad m => Stream (ByteStream m) m r -> Stream (Of ByteString) m r

It is subject to all the objections one makes to Data.ByteString.Lazy toStrict; all of these are devastating.

valuetoStrict_ :: Monad m => ByteStream m r -> m ByteString
#

O(n) Convert a byte stream into a single strict ByteString.

Note that this is an expensive operation that forces the whole monadic ByteString into memory and then copies all the data. If possible, try to avoid converting back and forth between streaming and strict bytestrings.

valueeffects :: Monad m => ByteStream m r -> m r
#

Perform the effects contained in an effectful bytestring, ignoring the bytes.

valuecopy :: Monad m => ByteStream m r -> ByteStream (ByteStream m) r
#

Make the information in a bytestring available to more than one eliminating fold, e.g.

Example1 expression
Q.count 'l' $ Q.count 'o' $ Q.copy $ "hello\nworld"3 :> (2 :> ())
Example1 expression
Q.length $ Q.count 'l' $ Q.count 'o' $ Q.copy $ Q.copy "hello\nworld"11 :> (3 :> (2 :> ()))
Example3 expressions
runResourceT $ Q.writeFile "hello2.txt" $ Q.writeFile "hello1.txt" $ Q.copy $ "hello\nworld\n":! cat hello2.txthelloworld:! cat hello1.txthelloworld

This sort of manipulation could as well be acheived by combining folds - using Control.Foldl for example. But any sort of manipulation can be involved in the fold. Here are a couple of trivial complications involving splitting by lines:

Example5 expressions
let doubleLines = Q.unlines . maps (<* Q.chunk "\n" ) . Q.lineslet emphasize = Q.unlines . maps (<* Q.chunk "!" ) . Q.linesrunResourceT $ Q.writeFile "hello2.txt" $ emphasize $ Q.writeFile "hello1.txt" $ doubleLines $ Q.copy $ "hello\nworld":! cat hello2.txthello!world!:! cat hello1.txthelloworld

As with the parallel operations in Streaming.Prelude, we have

Q.effects . Q.copy       = id
hoist Q.effects . Q.copy = id

The duplication does not by itself involve the copying of bytestring chunks; it just makes two references to each chunk as it arises. This does, however double the number of constructors associated with each chunk.

valuedrained
  1. :: (Monad m, MonadTrans t, Monad (t m))
  2. => t m (ByteStream m r)
  3. -> t m r
#

Perform the effects contained in the second in an effectful pair of bytestrings, ignoring the bytes. It would typically be used at the type

ByteStream m (ByteStream m r) -> ByteStream m r
valuemwrap :: m (ByteStream m r) -> ByteStream m r
#

Reconceive an effect that results in an effectful bytestring as an effectful bytestring. Compare Streaming.mwrap. The closest equivalent of

Example1 expression
Streaming.wrap :: f (Stream f m r) -> Stream f m r

is here consChunk. mwrap is the smart constructor for the internal Go constructor.

Transforming ByteStreams

4 declarations
valuefor
  1. :: Monad m
  2. => ByteStream m r
  3. -> ByteString -> ByteStream m x
  4. -> ByteStream m r
#

for xs f applies f to each chunk in the stream, and concatenates the resulting streams.

Generalised in 0.2.4 to match streaming: the callback's (ignored) return value can be of any type.

Basic interface

7 declarations
valuecons' :: Word8 -> ByteStream m r -> ByteStream m r
#

O(1) Unlike cons, 'cons'' is strict in the ByteString that we are consing onto. More precisely, it forces the head and the first chunk. It does this because, for space efficiency, it may coalesce the new byte onto the first 'chunk' rather than starting a new 'chunk'.

So that means you can't use a lazy recursive contruction like this:

let xs = cons\' c xs in xs

You can however use cons, as well as repeat and cycle, to build infinite byte streams.

Substrings

0 declarations

Breaking strings

valuedrop :: Monad m => Int64 -> ByteStream m r -> ByteStream m r
#

O(n/c) drop n xs returns the suffix of xs after the first n elements, or [] if n > length xs.

Example2 expressions
Q.putStrLn $ Q.drop 6 "Wisconsin"sinQ.putStrLn $ Q.drop 16 "Wisconsin"
valuegroup :: Monad m => ByteStream m r -> Stream (ByteStream m) m r
#

The group function takes a ByteStream and returns a list of ByteStreams such that the concatenation of the result is equal to the argument. Moreover, each sublist in the result contains only equal elements. For example,

group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]

It is a special case of groupBy, which allows the programmer to supply their own equality test.

valuesplitAt
  1. :: Monad m
  2. => Int64
  3. -> ByteStream m r
  4. -> ByteStream m (ByteStream m r)
#

O(n/c) splitAt n xs is equivalent to (take n xs, drop n xs).

Example2 expressions
rest <- Q.putStrLn $ Q.splitAt 3 "therapist is a danger to good hyphenation, as Knuth notes"theQ.putStrLn $ Q.splitAt 19 restrapist is a danger
valuesplitWith
  1. :: Monad m
  2. => Word8 -> Bool
  3. -> ByteStream m r
  4. -> Stream (ByteStream m) m r
#

O(n) Splits a ByteStream into components delimited by separators, where the predicate returns True for a separator element. The resulting components do not contain the separators. Two adjacent separators result in an empty component in the output. eg.

splitWith (=='a') "aabbaca" == ["","","bb","c",""]
splitWith (=='a') []        == []
valuetake :: Monad m => Int64 -> ByteStream m r -> ByteStream m ()
#

O(n/c) take n, applied to a ByteStream xs, returns the prefix of xs of length n, or xs itself if n > length xs.

Note that in the streaming context this drops the final return value; splitAt preserves this information, and is sometimes to be preferred.

Example4 expressions
Q.putStrLn $ Q.take 8 $ "Is there a God?" >> return TrueIs thereQ.putStrLn $ "Is there a God?" >> return TrueIs there a God?Truerest <- Q.putStrLn $ Q.splitAt 8 $ "Is there a God?" >> return TrueIs thereQ.effects  restTrue

Breaking into many substrings

valuesplit :: Monad m => Word8 -> ByteStream m r -> Stream (ByteStream m) m r
#

O(n) Break a ByteStream into pieces separated by the byte argument, consuming the delimiter. I.e.

split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
split 'a'  "aXaXaXa"    == ["","X","X","X",""]
split 'x'  "x"          == ["",""]

and

intercalate [c] . split c == id
split == splitWith . (==)

As for all splitting functions in this library, this function does not copy the substrings, it just constructs new ByteStreams that are slices of the original.

Special folds

Builders

4 declarations

Take a builder constructed otherwise and convert it to a genuine streaming bytestring.

Example1 expression
Q.putStrLn $ Q.toStreamingByteString $ stringUtf8 "哈斯克尔" <> stringUtf8 " " <> integerDec 98哈斯克尔 98

This benchmark shows its performance is indistinguishable from toLazyByteString

valuetoBuilder :: ByteStream IO () -> Builder
#

A simple construction of a builder from a ByteString.

Example2 expressions
let aaa = "10000 is a number\n" :: Q.ByteString IO () hPutBuilder  IO.stdout $ toBuilder  aaa10000 is a number
valueconcatBuilders :: Stream (Of Builder) IO () -> Builder
#

Concatenate a stream of builders (not a streaming bytestring!) into a single builder.

Example2 expressions
let aa = yield (integerDec 10000) >> yield (string8 " is a number.") >> yield (char8 '\n')hPutBuilder IO.stdout $ concatBuilders aa10000 is a number.

Building ByteStreams

0 declarations

Infinite ByteStreams

valuerepeat :: Word8 -> ByteStream m r
#

repeat x is an infinite ByteStream, with x the value of every element.

Example2 expressions
R.stdout $ R.take 50 $ R.repeat 60<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<Q.putStrLn $ Q.take 50 $ Q.repeat 'z'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
valueiterate :: (Word8 -> Word8) -> Word8 -> ByteStream m r
#

iterate f x returns an infinite ByteStream of repeated applications -- of f to x:

iterate f x == [x, f x, f (f x), ...]
Example2 expressions
R.stdout $ R.take 50 $ R.iterate succ 39()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYQ.putStrLn $ Q.take 50 $ Q.iterate succ '\''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY
valuecycle :: Monad m => ByteStream m r -> ByteStream m s
#

cycle ties a finite ByteStream into a circular one, or equivalently, the infinite repetition of the original ByteStream. For an empty bytestring (like return 17) it of course makes an unproductive loop

Example1 expression
Q.putStrLn $ Q.take 7 $ Q.cycle  "y\n"yyyy

Unfolding ByteStreams

valueunfoldM :: Monad m => (a -> Maybe (Word8, a)) -> a -> ByteStream m ()
#

O(n) The unfoldM function is analogous to the Stream unfoldr. unfoldM builds a ByteStream from a seed value. The function takes the element and returns Nothing if it is done producing the ByteStream or returns Just (a,b), in which case, a is a prepending to the ByteStream and b is used as the next element in a recursive call.

valuereread :: Monad m => (s -> m (Maybe ByteString)) -> s -> ByteStream m ()
#

Stream chunks from something that contains m (Maybe ByteString) until it returns Nothing. reread is of particular use rendering io-streams input streams as byte streams in the present sense.

import qualified Data.ByteString as B
import qualified System.IO.Streams as S
Q.reread S.read            :: S.InputStream B.ByteString -> Q.ByteStream IO ()
Q.reread (liftIO . S.read) :: MonadIO m => S.InputStream B.ByteString -> Q.ByteStream m ()

The other direction here is

S.unfoldM Q.unconsChunk    :: Q.ByteString IO r -> IO (S.InputStream B.ByteString)

Folds, including support for Control.Foldl

15 declarations
valuefoldr :: Monad m => (Word8 -> a -> a) -> a -> ByteStream m () -> m a
#

foldr, applied to a binary operator, a starting value (typically the right-identity of the operator), and a ByteStream, reduces the ByteStream using the binary operator, from right to left.

valuefold
  1. :: Monad m
  2. => x -> Word8 -> x
  3. -> x
  4. -> x -> b
  5. -> ByteStream m r
  6. -> m (Of b r)
#

fold keeps the return value of the left-folded bytestring. Useful for simultaneous folds over a segmented bytestream.

valuefold_
  1. :: Monad m
  2. => x -> Word8 -> x
  3. -> x
  4. -> x -> b
  5. -> ByteStream m ()
  6. -> m b
#

fold_, applied to a binary operator, a starting value (typically the left-identity of the operator), and a ByteStream, reduces the ByteStream using the binary operator, from left to right. We use the style of the foldl library for left folds

valuehead :: Monad m => ByteStream m r -> m (Of (Maybe Word8) r)
#

O(c) Extract the first element of a ByteStream, if there is one. Suitable for use with mapped:

S.mapped Q.head :: Stream (Q.ByteStream m) m r -> Stream (Of (Maybe Word8)) m r
valuelength :: Monad m => ByteStream m r -> m (Of Int r)
#

O(n/c) length returns the length of a byte stream as an Int together with the return value. This makes various maps possible.

Example2 expressions
Q.length "one\ntwo\three\nfour\nfive\n"23 :> ()S.print $ S.take 3 $ mapped Q.length $ Q.lines "one\ntwo\three\nfour\nfive\n"384
valuelength_ :: Monad m => ByteStream m r -> m Int
#

Like length, report the length in bytes of the ByteStream by running through its contents. Since the return value is in the effect m, this is one way to "get out" of the stream.

valuenull :: Monad m => ByteStream m r -> m (Of Bool r)
#

Test whether a ByteStream is empty, collecting its return value; to reach the return value, this operation must check the whole length of the string.

Example3 expressions
Q.null "one\ntwo\three\nfour\nfive\n"False :> ()Q.null ""True :> ()S.print $ mapped R.null $ Q.lines "yours,\nMeredith"FalseFalse

Suitable for use with mapped:

S.mapped Q.null :: Streaming (ByteStream m) m r -> Stream (Of Bool) m r
valuenull_ :: Monad m => ByteStream m r -> m Bool
#

O(1) Test whether a ByteStream is empty. The value is of course in the monad of the effects.

Example3 expressions
Q.null "one\ntwo\three\nfour\nfive\n"FalseQ.null $ Q.take 0 Q.stdinTrue:t Q.null $ Q.take 0 Q.stdinQ.null $ Q.take 0 Q.stdin :: MonadIO m => m Bool
valuenulls
  1. :: Monad m
  2. => ByteStream m r
  3. -> m (Sum (ByteStream m) (ByteStream m) r)
#

O1 Distinguish empty from non-empty lines, while maintaining streaming; the empty ByteStrings are on the right

Example1 expression
nulls  ::  ByteStream m r -> m (Sum (ByteStream m) (ByteStream m) r)

There are many (generally slower) ways to remove null bytestrings from a Stream (ByteStream m) m r (besides using denull). If we pass next to

Example1 expression
mapped nulls bs :: Stream (Sum (ByteStream m) (ByteStream m)) m r

then can then apply Streaming.separate to get

Example1 expression
separate (mapped nulls bs) :: Stream (ByteStream m) (Stream (ByteStream m) m) r

The inner monad is now made of the empty bytestrings; we act on this with hoist , considering that

Example1 expression
:t Q.effects . Q.concatQ.effects . Q.concat  :: Monad m => Stream (Q.ByteStream m) m r -> m r

we have

Example1 expression
hoist (Q.effects . Q.concat) . separate . mapped Q.nulls  :: Monad n =>  Stream (Q.ByteStream n) n b -> Stream (Q.ByteStream n) n b
valuecount :: Monad m => Word8 -> ByteStream m r -> m (Of Int r)
#

Returns the number of times its argument appears in the ByteStream. Suitable for use with mapped:

S.mapped (Q.count 37) :: Stream (Q.ByteStream m) m r -> Stream (Of Int) m r

I/O with ByteStreams

0 declarations

Standard input and output

valueinteract :: (ByteStream IO () -> ByteStream IO r) -> IO r
#

A synonym for hPut, for compatibility

hPutStr :: Handle -> ByteStream IO r -> IO r hPutStr = hPut

  • - | Write a ByteStream to stdout putStr :: ByteStream IO r -> IO r putStr = hPut IO.stdout

The interact function takes a function of type ByteStream -> ByteStream as its argument. The entire input from the standard input device is passed to this function as its argument, and the resulting string is output on the standard output device.

interact morph = stdout (morph stdin)

Files

valuereadFile :: MonadResource m => FilePath -> ByteStream m ()
#

Read an entire file into a chunked ByteStream IO (). The handle will be held open until EOF is encountered. The block governed by runResourceT will end with the closing of any handles opened.

Example2 expressions
:! cat hello.txtHello world.Goodbye world.runResourceT $ Q.stdout $ Q.readFile "hello.txt"Hello world.Goodbye world.
valuewriteFile :: MonadResource m => FilePath -> ByteStream m r -> m r
#

Write a ByteStream to a file. Use Control.Monad.Trans.ResourceT.runResourceT to ensure that the handle is closed.

Example5 expressions
:set -XOverloadedStringsrunResourceT $ Q.writeFile "hello.txt" "Hello world.\nGoodbye world.\n":! cat "hello.txt"Hello world.Goodbye world.runResourceT $ Q.writeFile "hello2.txt" $ Q.readFile "hello.txt":! cat hello2.txtHello world.Goodbye world.
valueappendFile :: MonadResource m => FilePath -> ByteStream m r -> m r
#

Append a ByteStream to a file. Use Control.Monad.Trans.ResourceT.runResourceT to ensure that the handle is closed.

Example4 expressions
runResourceT $ Q.writeFile "hello.txt" "Hello world.\nGoodbye world.\n"runResourceT $ Q.stdout $ Q.readFile "hello.txt"Hello world.Goodbye world.runResourceT $ Q.appendFile "hello.txt" "sincerely yours,\nArthur\n"runResourceT $ Q.stdout $  Q.readFile "hello.txt"Hello world.Goodbye world.sincerely yours,Arthur

I/O with Handles

valuehGetContentsN :: MonadIO m => Int -> Handle -> ByteStream m ()
#

Read entire handle contents lazily into a ByteStream. Chunks are read on demand, in at most k-sized chunks. It does not block waiting for a whole k-sized chunk, so if less than k bytes are available then they will be returned immediately as a smaller chunk.

Note: the Handle should be placed in binary mode with System.IO.hSetBinaryMode for hGetContentsN to work correctly.

valuehGetNonBlocking :: MonadIO m => Handle -> Int -> ByteStream m ()
#

hGetNonBlocking is similar to hGet, except that it will never block waiting for data to become available, instead it returns only whatever data is available. If there is no data available to be read, hGetNonBlocking returns empty.

Note: on Windows and with Haskell implementation other than GHC, this function does not work correctly; it behaves identically to hGet.

valuehGetNonBlockingN :: MonadIO m => Int -> Handle -> Int -> ByteStream m ()
#

hGetNonBlockingN is similar to hGetContentsN, except that it will never block waiting for data to become available, instead it returns only whatever data is available. Chunks are read on demand, in k-sized chunks.

Simple chunkwise operations

10 declarations
valuechunkFold
  1. :: Monad m
  2. => x -> ByteString -> x
  3. -> x
  4. -> x -> a
  5. -> ByteStream m r
  6. -> m (Of a r)
#

chunkFold is preferable to foldlChunks since it is an appropriate argument for Control.Foldl.purely which permits many folds and sinks to be run simultaneously on one bytestream.

Etc.

4 declarations
valuedematerialize
  1. :: Monad m
  2. => ByteStream m r
  3. -> forall x. (r -> x) -> (ByteString -> x -> x) -> (m x -> x) -> x
#

Resolve a succession of chunks into its Church encoding; this is not a safe operation; it is equivalent to exposing the constructors

valuematerialize
  1. :: forall x. (r -> x) -> (ByteString -> x -> x) -> (m x -> x) -> x
  2. -> ByteStream m r
#

Construct a succession of chunks from its Church encoding (compare GHC.Exts.build)