-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | Fast, compact, strict and lazy byte strings with a list interface
gr
grAn efficient compact, immutable byte string type (both strict and
grlazy) suitable for binary or 8-bit character data.
gr
grThe <a>ByteString</a> type represents sequences of bytes or 8-bit
grcharacters. It is suitable for high performance use, both in terms of
grlarge data quantities, or high speed requirements. The
gr<a>ByteString</a> functions follow the same style as Haskell's
grordinary lists, so it is easy to convert code from using <a>String</a>
grto <a>ByteString</a>.
gr
grTwo <a>ByteString</a> variants are provided:
gr
gr<ul>
gr<li>Strict <a>ByteString</a>s keep the string as a single large array.
grThis makes them convenient for passing data between C and
grHaskell.</li>
gr<li>Lazy <a>ByteString</a>s use a lazy list of strict chunks which
grmakes it suitable for I/O streaming tasks.</li>
gr</ul>
gr
grThe <tt>Char8</tt> modules provide a character-based view of the same
grunderlying <a>ByteString</a> types. This makes it convenient to handle
grmixed binary and 8-bit character content (which is common in many file
grformats and network protocols).
gr
grThe <a>Builder</a> module provides an efficient way to build up
gr<a>ByteString</a>s in an ad-hoc way by repeated concatenation. This is
grideal for fast serialisation or pretty printing.
gr
grThere is also a <a>ShortByteString</a> type which has a lower memory
groverhead and can can be converted to or from a <a>ByteString</a>, but
grsupports very few other operations. It is suitable for keeping many
grshort strings in memory.
gr
gr<a>ByteString</a>s are not designed for Unicode. For Unicode strings
gryou should use the <a>Text</a> type from the <tt>text</tt> package.
gr
grThese modules are intended to be imported qualified, to avoid name
grclashes with <a>Prelude</a> functions, e.g.
gr
gr<pre>
grimport qualified Data.ByteString as BS
gr</pre>
@package bytestring
@version 0.10.8.2


-- | A compact representation suitable for storing short byte strings in
grmemory.
gr
grIn typical use cases it can be imported alongside
gr<a>Data.ByteString</a>, e.g.
gr
gr<pre>
grimport qualified Data.ByteString       as B
grimport qualified Data.ByteString.Short as B
gr         (ShortByteString, toShort, fromShort)
gr</pre>
gr
grOther <a>ShortByteString</a> operations clash with
gr<a>Data.ByteString</a> or <a>Prelude</a> functions however, so they
grshould be imported <tt>qualified</tt> with a different alias e.g.
gr
gr<pre>
grimport qualified Data.ByteString.Short as B.Short
gr</pre>
module Data.ByteString.Short

-- | A compact representation of a <a>Word8</a> vector.
gr
grIt has a lower memory overhead than a <a>ByteString</a> and and does
grnot contribute to heap fragmentation. It can be converted to or from a
gr<a>ByteString</a> (at the cost of copying the string data). It
grsupports very few other operations.
gr
grIt is suitable for use as an internal representation for code that
grneeds to keep many short strings in memory, but it <i>should not</i>
grbe used as an interchange type. That is, it should not generally be
grused in public APIs. The <a>ByteString</a> type is usually more
grsuitable for use in interfaces; it is more flexible and it supports a
grwide range of operations.
data ShortByteString

-- | <i>O(n)</i>. Convert a <a>ByteString</a> into a
gr<a>ShortByteString</a>.
gr
grThis makes a copy, so does not retain the input string.
toShort :: ByteString -> ShortByteString

-- | <i>O(n)</i>. Convert a <a>ShortByteString</a> into a
gr<a>ByteString</a>.
fromShort :: ShortByteString -> ByteString

-- | <i>O(n)</i>. Convert a list into a <a>ShortByteString</a>
pack :: [Word8] -> ShortByteString

-- | <i>O(n)</i>. Convert a <a>ShortByteString</a> into a list.
unpack :: ShortByteString -> [Word8]

-- | <i>O(1)</i>. The empty <a>ShortByteString</a>.
empty :: ShortByteString

-- | <i>O(1)</i> Test whether a <a>ShortByteString</a> is empty.
null :: ShortByteString -> Bool

-- | <i>O(1)</i> The length of a <a>ShortByteString</a>.
length :: ShortByteString -> Int

-- | <i>O(1)</i> <a>ShortByteString</a> index (subscript) operator,
grstarting from 0.
index :: ShortByteString -> Int -> Word8


-- | A module containing unsafe <a>ByteString</a> operations.
gr
grWhile these functions have a stable API and you may use these
grfunctions in applications, do carefully consider the documented
grpre-conditions; incorrect use can break referential transparency or
grworse.
module Data.ByteString.Unsafe

-- | A variety of <a>head</a> for non-empty ByteStrings. <a>unsafeHead</a>
gromits the check for the empty case, so there is an obligation on the
grprogrammer to provide a proof that the ByteString is non-empty.
unsafeHead :: ByteString -> Word8

-- | A variety of <a>tail</a> for non-empty ByteStrings. <a>unsafeTail</a>
gromits the check for the empty case. As with <a>unsafeHead</a>, the
grprogrammer must provide a separate proof that the ByteString is
grnon-empty.
unsafeTail :: ByteString -> ByteString

-- | A variety of <a>init</a> for non-empty ByteStrings. <a>unsafeInit</a>
gromits the check for the empty case. As with <a>unsafeHead</a>, the
grprogrammer must provide a separate proof that the ByteString is
grnon-empty.
unsafeInit :: ByteString -> ByteString

-- | A variety of <a>last</a> for non-empty ByteStrings. <a>unsafeLast</a>
gromits the check for the empty case. As with <a>unsafeHead</a>, the
grprogrammer must provide a separate proof that the ByteString is
grnon-empty.
unsafeLast :: ByteString -> Word8

-- | Unsafe <a>ByteString</a> index (subscript) operator, starting from 0,
grreturning a <a>Word8</a> This omits the bounds check, which means
grthere is an accompanying obligation on the programmer to ensure the
grbounds are checked in some other way.
unsafeIndex :: ByteString -> Int -> Word8

-- | A variety of <a>take</a> which omits the checks on <tt>n</tt> so there
gris an obligation on the programmer to provide a proof that <tt>0 &lt;=
grn &lt;= <a>length</a> xs</tt>.
unsafeTake :: Int -> ByteString -> ByteString

-- | A variety of <a>drop</a> which omits the checks on <tt>n</tt> so there
gris an obligation on the programmer to provide a proof that <tt>0 &lt;=
grn &lt;= <a>length</a> xs</tt>.
unsafeDrop :: Int -> ByteString -> ByteString

-- | <i>O(1) construction</i> Use a <tt>ByteString</tt> with a function
grrequiring a <tt>CString</tt>.
gr
grThis function does zero copying, and merely unwraps a
gr<tt>ByteString</tt> to appear as a <tt>CString</tt>. It is
gr<i>unsafe</i> in two ways:
gr
gr<ul>
gr<li>After calling this function the <tt>CString</tt> shares the
grunderlying byte buffer with the original <tt>ByteString</tt>. Thus
grmodifying the <tt>CString</tt>, either in C, or using poke, will cause
grthe contents of the <tt>ByteString</tt> to change, breaking
grreferential transparency. Other <tt>ByteStrings</tt> created by
grsharing (such as those produced via <a>take</a> or <a>drop</a>) will
gralso reflect these changes. Modifying the <tt>CString</tt> will break
grreferential transparency. To avoid this, use <tt>useAsCString</tt>,
grwhich makes a copy of the original <tt>ByteString</tt>.</li>
gr<li><tt>CStrings</tt> are often passed to functions that require them
grto be null-terminated. If the original <tt>ByteString</tt> wasn't null
grterminated, neither will the <tt>CString</tt> be. It is the
grprogrammers responsibility to guarantee that the <tt>ByteString</tt>
gris indeed null terminated. If in doubt, use
gr<tt>useAsCString</tt>.</li>
gr<li>The memory may freed at any point after the subcomputation
grterminates, so the pointer to the storage must *not* be used after
grthis.</li>
gr</ul>
unsafeUseAsCString :: ByteString -> (CString -> IO a) -> IO a

-- | <i>O(1) construction</i> Use a <tt>ByteString</tt> with a function
grrequiring a <tt>CStringLen</tt>.
gr
grThis function does zero copying, and merely unwraps a
gr<tt>ByteString</tt> to appear as a <tt>CStringLen</tt>. It is
gr<i>unsafe</i>:
gr
gr<ul>
gr<li>After calling this function the <tt>CStringLen</tt> shares the
grunderlying byte buffer with the original <tt>ByteString</tt>. Thus
grmodifying the <tt>CStringLen</tt>, either in C, or using poke, will
grcause the contents of the <tt>ByteString</tt> to change, breaking
grreferential transparency. Other <tt>ByteStrings</tt> created by
grsharing (such as those produced via <a>take</a> or <a>drop</a>) will
gralso reflect these changes. Modifying the <tt>CStringLen</tt> will
grbreak referential transparency. To avoid this, use
gr<tt>useAsCStringLen</tt>, which makes a copy of the original
gr<tt>ByteString</tt>.</li>
gr</ul>
unsafeUseAsCStringLen :: ByteString -> (CStringLen -> IO a) -> IO a

-- | <i>O(n)</i> Build a <tt>ByteString</tt> from a <tt>CString</tt>. This
grvalue will have <i>no</i> finalizer associated to it, and will not be
grgarbage collected by Haskell. The ByteString length is calculated
grusing <i>strlen(3)</i>, and thus the complexity is a <i>O(n)</i>.
gr
grThis function is <i>unsafe</i>. If the <tt>CString</tt> is later
grmodified, this change will be reflected in the resulting
gr<tt>ByteString</tt>, breaking referential transparency.
unsafePackCString :: CString -> IO ByteString

-- | <i>O(1)</i> Build a <tt>ByteString</tt> from a <tt>CStringLen</tt>.
grThis value will have <i>no</i> finalizer associated with it, and will
grnot be garbage collected by Haskell. This operation has <i>O(1)</i>
grcomplexity as we already know the final size, so no <i>strlen(3)</i>
gris required.
gr
grThis function is <i>unsafe</i>. If the original <tt>CStringLen</tt> is
grlater modified, this change will be reflected in the resulting
gr<tt>ByteString</tt>, breaking referential transparency.
unsafePackCStringLen :: CStringLen -> IO ByteString

-- | <i>O(n)</i> Build a <tt>ByteString</tt> from a malloced
gr<tt>CString</tt>. This value will have a <tt>free(3)</tt> finalizer
grassociated to it.
gr
grThis function is <i>unsafe</i>. If the original <tt>CString</tt> is
grlater modified, this change will be reflected in the resulting
gr<tt>ByteString</tt>, breaking referential transparency.
gr
grThis function is also unsafe if you call its finalizer twice, which
grwill result in a <i>double free</i> error, or if you pass it a CString
grnot allocated with <tt>malloc</tt>.
unsafePackMallocCString :: CString -> IO ByteString

-- | <i>O(1)</i> Build a <tt>ByteString</tt> from a malloced
gr<tt>CStringLen</tt>. This value will have a <tt>free(3)</tt> finalizer
grassociated to it.
gr
grThis function is <i>unsafe</i>. If the original <tt>CString</tt> is
grlater modified, this change will be reflected in the resulting
gr<tt>ByteString</tt>, breaking referential transparency.
gr
grThis function is also unsafe if you call its finalizer twice, which
grwill result in a <i>double free</i> error, or if you pass it a CString
grnot allocated with <tt>malloc</tt>.
unsafePackMallocCStringLen :: CStringLen -> IO ByteString

-- | <i>O(n)</i> Pack a null-terminated sequence of bytes, pointed to by an
grAddr# (an arbitrary machine address assumed to point outside the
grgarbage-collected heap) into a <tt>ByteString</tt>. A much faster way
grto create an Addr# is with an unboxed string literal, than to pack a
grboxed string. A unboxed string literal is compiled to a static
gr<tt>char []</tt> by GHC. Establishing the length of the string
grrequires a call to <tt>strlen(3)</tt>, so the Addr# must point to a
grnull-terminated buffer (as is the case with "string"# literals in
grGHC). Use <tt>unsafePackAddressLen</tt> if you know the length of the
grstring statically.
gr
grAn example:
gr
gr<pre>
grliteralFS = unsafePackAddress "literal"#
gr</pre>
gr
grThis function is <i>unsafe</i>. If you modify the buffer pointed to by
grthe original Addr# this modification will be reflected in the
grresulting <tt>ByteString</tt>, breaking referential transparency.
gr
grNote this also won't work if your Addr# has embedded '\0' characters
grin the string, as <tt>strlen</tt> will return too short a length.
unsafePackAddress :: Addr# -> IO ByteString

-- | <i>O(1)</i> <a>unsafePackAddressLen</a> provides constant-time
grconstruction of <a>ByteString</a>s, which is ideal for string
grliterals. It packs a sequence of bytes into a <tt>ByteString</tt>,
grgiven a raw <a>Addr#</a> to the string, and the length of the string.
gr
grThis function is <i>unsafe</i> in two ways:
gr
gr<ul>
gr<li>the length argument is assumed to be correct. If the length
grargument is incorrect, it is possible to overstep the end of the byte
grarray.</li>
gr<li>if the underying Addr# is later modified, this change will be
grreflected in resulting <tt>ByteString</tt>, breaking referential
grtransparency.</li>
gr</ul>
gr
grIf in doubt, don't use this function.
unsafePackAddressLen :: Int -> Addr# -> IO ByteString

-- | <i>O(1)</i> Construct a <a>ByteString</a> given a Ptr Word8 to a
grbuffer, a length, and an IO action representing a finalizer. This
grfunction is not available on Hugs.
gr
grThis function is <i>unsafe</i>, it is possible to break referential
grtransparency by modifying the underlying buffer pointed to by the
grfirst argument. Any changes to the original buffer will be reflected
grin the resulting <tt>ByteString</tt>.
unsafePackCStringFinalizer :: Ptr Word8 -> Int -> IO () -> IO ByteString

-- | Explicitly run the finaliser associated with a <a>ByteString</a>.
grReferences to this value after finalisation may generate invalid
grmemory references.
gr
grThis function is <i>unsafe</i>, as there may be other
gr<tt>ByteStrings</tt> referring to the same underlying pages. If you
gruse this, you need to have a proof of some kind that all
gr<a>ByteString</a>s ever generated from the underlying byte array are
grno longer live.
unsafeFinalize :: ByteString -> IO ()


-- | A time and space-efficient implementation of byte vectors using packed
grWord8 arrays, suitable for high performance use, both in terms of
grlarge data quantities, or high speed requirements. Byte vectors are
grencoded as strict <a>Word8</a> arrays of bytes, held in a
gr<a>ForeignPtr</a>, and can be passed between C and Haskell with little
greffort.
gr
grThe recomended way to assemble ByteStrings from smaller parts is to
gruse the builder monoid from <a>Data.ByteString.Builder</a>.
gr
grThis module is intended to be imported <tt>qualified</tt>, to avoid
grname clashes with <a>Prelude</a> functions. eg.
gr
gr<pre>
grimport qualified Data.ByteString as B
gr</pre>
gr
grOriginal GHC implementation by Bryan O'Sullivan. Rewritten to use
gr<a>UArray</a> by Simon Marlow. Rewritten to support slices and use
gr<a>ForeignPtr</a> by David Roundy. Rewritten again and extended by Don
grStewart and Duncan Coutts.
module Data.ByteString

-- | A space-efficient representation of a <a>Word8</a> vector, supporting
grmany efficient operations.
gr
grA <a>ByteString</a> contains 8-bit bytes, or by using the operations
grfrom <a>Data.ByteString.Char8</a> it can be interpreted as containing
gr8-bit characters.
data ByteString

-- | <i>O(1)</i> The empty <a>ByteString</a>
empty :: ByteString

-- | <i>O(1)</i> Convert a <a>Word8</a> into a <a>ByteString</a>
singleton :: Word8 -> ByteString

-- | <i>O(n)</i> Convert a <tt>[<a>Word8</a>]</tt> into a
gr<a>ByteString</a>.
gr
grFor applications with large numbers of string literals, pack can be a
grbottleneck. In such cases, consider using packAddress (GHC only).
pack :: [Word8] -> ByteString

-- | <i>O(n)</i> Converts a <a>ByteString</a> to a <tt>[<a>Word8</a>]</tt>.
unpack :: ByteString -> [Word8]

-- | <i>O(n)</i> <a>cons</a> is analogous to (:) for lists, but of
grdifferent complexity, as it requires making a copy.
cons :: Word8 -> ByteString -> ByteString
infixr 5 `cons`

-- | <i>O(n)</i> Append a byte to the end of a <a>ByteString</a>
snoc :: ByteString -> Word8 -> ByteString
infixl 5 `snoc`

-- | <i>O(n)</i> Append two ByteStrings
append :: ByteString -> ByteString -> ByteString

-- | <i>O(1)</i> Extract the first element of a ByteString, which must be
grnon-empty. An exception will be thrown in the case of an empty
grByteString.
head :: ByteString -> Word8

-- | <i>O(1)</i> Extract the head and tail of a ByteString, returning
grNothing if it is empty.
uncons :: ByteString -> Maybe (Word8, ByteString)

-- | <i>O(1)</i> Extract the <a>init</a> and <a>last</a> of a ByteString,
grreturning Nothing if it is empty.
unsnoc :: ByteString -> Maybe (ByteString, Word8)

-- | <i>O(1)</i> Extract the last element of a ByteString, which must be
grfinite and non-empty. An exception will be thrown in the case of an
grempty ByteString.
last :: ByteString -> Word8

-- | <i>O(1)</i> Extract the elements after the head of a ByteString, which
grmust be non-empty. An exception will be thrown in the case of an empty
grByteString.
tail :: ByteString -> ByteString

-- | <i>O(1)</i> Return all the elements of a <a>ByteString</a> except the
grlast one. An exception will be thrown in the case of an empty
grByteString.
init :: ByteString -> ByteString

-- | <i>O(1)</i> Test whether a ByteString is empty.
null :: ByteString -> Bool

-- | <i>O(1)</i> <a>length</a> returns the length of a ByteString as an
gr<a>Int</a>.
length :: ByteString -> Int

-- | <i>O(n)</i> <a>map</a> <tt>f xs</tt> is the ByteString obtained by
grapplying <tt>f</tt> to each element of <tt>xs</tt>.
map :: (Word8 -> Word8) -> ByteString -> ByteString

-- | <i>O(n)</i> <a>reverse</a> <tt>xs</tt> efficiently returns the
grelements of <tt>xs</tt> in reverse order.
reverse :: ByteString -> ByteString

-- | <i>O(n)</i> The <a>intersperse</a> function takes a <a>Word8</a> and a
gr<a>ByteString</a> and `intersperses' that byte between the elements of
grthe <a>ByteString</a>. It is analogous to the intersperse function on
grLists.
intersperse :: Word8 -> ByteString -> ByteString

-- | <i>O(n)</i> The <a>intercalate</a> function takes a <a>ByteString</a>
grand a list of <a>ByteString</a>s and concatenates the list after
grinterspersing the first argument between each element of the list.
intercalate :: ByteString -> [ByteString] -> ByteString

-- | The <a>transpose</a> function transposes the rows and columns of its
gr<a>ByteString</a> argument.
transpose :: [ByteString] -> [ByteString]

-- | <a>foldl</a>, applied to a binary operator, a starting value
gr(typically the left-identity of the operator), and a ByteString,
grreduces the ByteString using the binary operator, from left to right.
foldl :: (a -> Word8 -> a) -> a -> ByteString -> a

-- | <a>foldl'</a> is like <a>foldl</a>, but strict in the accumulator.
foldl' :: (a -> Word8 -> a) -> a -> ByteString -> a

-- | <a>foldl1</a> is a variant of <a>foldl</a> that has no starting value
grargument, and thus must be applied to non-empty <tt>ByteStrings</tt>.
grAn exception will be thrown in the case of an empty ByteString.
foldl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8

-- | 'foldl1\'' is like <a>foldl1</a>, but strict in the accumulator. An
grexception will be thrown in the case of an empty ByteString.
foldl1' :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8

-- | <a>foldr</a>, applied to a binary operator, a starting value
gr(typically the right-identity of the operator), and a ByteString,
grreduces the ByteString using the binary operator, from right to left.
foldr :: (Word8 -> a -> a) -> a -> ByteString -> a

-- | <a>foldr'</a> is like <a>foldr</a>, but strict in the accumulator.
foldr' :: (Word8 -> a -> a) -> a -> ByteString -> a

-- | <a>foldr1</a> is a variant of <a>foldr</a> that has no starting value
grargument, and thus must be applied to non-empty <a>ByteString</a>s An
grexception will be thrown in the case of an empty ByteString.
foldr1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8

-- | 'foldr1\'' is a variant of <a>foldr1</a>, but is strict in the
graccumulator.
foldr1' :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8

-- | <i>O(n)</i> Concatenate a list of ByteStrings.
concat :: [ByteString] -> ByteString

-- | Map a function over a <a>ByteString</a> and concatenate the results
concatMap :: (Word8 -> ByteString) -> ByteString -> ByteString

-- | <i>O(n)</i> Applied to a predicate and a ByteString, <a>any</a>
grdetermines if any element of the <a>ByteString</a> satisfies the
grpredicate.
any :: (Word8 -> Bool) -> ByteString -> Bool

-- | <i>O(n)</i> Applied to a predicate and a <a>ByteString</a>, <a>all</a>
grdetermines if all elements of the <a>ByteString</a> satisfy the
grpredicate.
all :: (Word8 -> Bool) -> ByteString -> Bool

-- | <i>O(n)</i> <a>maximum</a> returns the maximum value from a
gr<a>ByteString</a> This function will fuse. An exception will be thrown
grin the case of an empty ByteString.
maximum :: ByteString -> Word8

-- | <i>O(n)</i> <a>minimum</a> returns the minimum value from a
gr<a>ByteString</a> This function will fuse. An exception will be thrown
grin the case of an empty ByteString.
minimum :: ByteString -> Word8

-- | <a>scanl</a> is similar to <a>foldl</a>, but returns a list of
grsuccessive reduced values from the left. This function will fuse.
gr
gr<pre>
grscanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
gr</pre>
gr
grNote that
gr
gr<pre>
grlast (scanl f z xs) == foldl f z xs.
gr</pre>
scanl :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString

-- | <a>scanl1</a> is a variant of <a>scanl</a> that has no starting value
grargument. This function will fuse.
gr
gr<pre>
grscanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
gr</pre>
scanl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString

-- | scanr is the right-to-left dual of scanl.
scanr :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString

-- | <a>scanr1</a> is a variant of <a>scanr</a> that has no starting value
grargument.
scanr1 :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString

-- | The <a>mapAccumL</a> function behaves like a combination of <a>map</a>
grand <a>foldl</a>; it applies a function to each element of a
grByteString, passing an accumulating parameter from left to right, and
grreturning a final value of this accumulator together with the new
grlist.
mapAccumL :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)

-- | The <a>mapAccumR</a> function behaves like a combination of <a>map</a>
grand <a>foldr</a>; it applies a function to each element of a
grByteString, passing an accumulating parameter from right to left, and
grreturning a final value of this accumulator together with the new
grByteString.
mapAccumR :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)

-- | <i>O(n)</i> <a>replicate</a> <tt>n x</tt> is a ByteString of length
gr<tt>n</tt> with <tt>x</tt> the value of every element. The following
grholds:
gr
gr<pre>
grreplicate w c = unfoldr w (\u -&gt; Just (u,u)) c
gr</pre>
gr
grThis implemenation uses <tt>memset(3)</tt>
replicate :: Int -> Word8 -> ByteString

-- | <i>O(n)</i>, where <i>n</i> is the length of the result. The
gr<a>unfoldr</a> function is analogous to the List 'unfoldr'.
gr<a>unfoldr</a> builds a ByteString from a seed value. The function
grtakes the element and returns <a>Nothing</a> if it is done producing
grthe ByteString or returns <a>Just</a> <tt>(a,b)</tt>, in which case,
gr<tt>a</tt> is the next byte in the string, and <tt>b</tt> is the seed
grvalue for further production.
gr
grExamples:
gr
gr<pre>
gr   unfoldr (\x -&gt; if x &lt;= 5 then Just (x, x + 1) else Nothing) 0
gr== pack [0, 1, 2, 3, 4, 5]
gr</pre>
unfoldr :: (a -> Maybe (Word8, a)) -> a -> ByteString

-- | <i>O(n)</i> Like <a>unfoldr</a>, <a>unfoldrN</a> builds a ByteString
grfrom a seed value. However, the length of the result is limited by the
grfirst argument to <a>unfoldrN</a>. This function is more efficient
grthan <a>unfoldr</a> when the maximum length of the result is known.
gr
grThe following equation relates <a>unfoldrN</a> and <a>unfoldr</a>:
gr
gr<pre>
grfst (unfoldrN n f s) == take n (unfoldr f s)
gr</pre>
unfoldrN :: Int -> (a -> Maybe (Word8, a)) -> a -> (ByteString, Maybe a)

-- | <i>O(1)</i> <a>take</a> <tt>n</tt>, applied to a ByteString
gr<tt>xs</tt>, returns the prefix of <tt>xs</tt> of length <tt>n</tt>,
gror <tt>xs</tt> itself if <tt>n &gt; <a>length</a> xs</tt>.
take :: Int -> ByteString -> ByteString

-- | <i>O(1)</i> <a>drop</a> <tt>n xs</tt> returns the suffix of
gr<tt>xs</tt> after the first <tt>n</tt> elements, or <tt>[]</tt> if
gr<tt>n &gt; <a>length</a> xs</tt>.
drop :: Int -> ByteString -> ByteString

-- | <i>O(1)</i> <a>splitAt</a> <tt>n xs</tt> is equivalent to
gr<tt>(<a>take</a> n xs, <a>drop</a> n xs)</tt>.
splitAt :: Int -> ByteString -> (ByteString, ByteString)

-- | <a>takeWhile</a>, applied to a predicate <tt>p</tt> and a ByteString
gr<tt>xs</tt>, returns the longest prefix (possibly empty) of
gr<tt>xs</tt> of elements that satisfy <tt>p</tt>.
takeWhile :: (Word8 -> Bool) -> ByteString -> ByteString

-- | <a>dropWhile</a> <tt>p xs</tt> returns the suffix remaining after
gr<a>takeWhile</a> <tt>p xs</tt>.
dropWhile :: (Word8 -> Bool) -> ByteString -> ByteString

-- | <a>span</a> <tt>p xs</tt> breaks the ByteString into two segments. It
gris equivalent to <tt>(<a>takeWhile</a> p xs, <a>dropWhile</a> p
grxs)</tt>
span :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <a>spanEnd</a> behaves like <a>span</a> but from the end of the
gr<a>ByteString</a>. We have
gr
gr<pre>
grspanEnd (not.isSpace) "x y z" == ("x y ","z")
gr</pre>
gr
grand
gr
gr<pre>
grspanEnd (not . isSpace) ps
gr   ==
grlet (x,y) = span (not.isSpace) (reverse ps) in (reverse y, reverse x)
gr</pre>
spanEnd :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <a>break</a> <tt>p</tt> is equivalent to <tt><a>span</a> (<a>not</a> .
grp)</tt>.
gr
grUnder GHC, a rewrite rule will transform break (==) into a call to the
grspecialised breakByte:
gr
gr<pre>
grbreak ((==) x) = breakByte x
grbreak (==x) = breakByte x
gr</pre>
break :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <a>breakEnd</a> behaves like <a>break</a> but from the end of the
gr<a>ByteString</a>
gr
grbreakEnd p == spanEnd (not.p)
breakEnd :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)

-- | The <a>group</a> function takes a ByteString and returns a list of
grByteStrings such that the concatenation of the result is equal to the
grargument. Moreover, each sublist in the result contains only equal
grelements. For example,
gr
gr<pre>
grgroup "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
gr</pre>
gr
grIt is a special case of <a>groupBy</a>, which allows the programmer to
grsupply their own equality test. It is about 40% faster than <i>groupBy
gr(==)</i>
group :: ByteString -> [ByteString]

-- | The <a>groupBy</a> function is the non-overloaded version of
gr<a>group</a>.
groupBy :: (Word8 -> Word8 -> Bool) -> ByteString -> [ByteString]

-- | <i>O(n)</i> Return all initial segments of the given
gr<a>ByteString</a>, shortest first.
inits :: ByteString -> [ByteString]

-- | <i>O(n)</i> Return all final segments of the given <a>ByteString</a>,
grlongest first.
tails :: ByteString -> [ByteString]

-- | <i>O(n)</i> The <a>stripPrefix</a> function takes two ByteStrings and
grreturns <a>Just</a> the remainder of the second iff the first is its
grprefix, and otherwise <a>Nothing</a>.
stripPrefix :: ByteString -> ByteString -> Maybe ByteString

-- | <i>O(n)</i> The <a>stripSuffix</a> function takes two ByteStrings and
grreturns <a>Just</a> the remainder of the second iff the first is its
grsuffix, and otherwise <a>Nothing</a>.
stripSuffix :: ByteString -> ByteString -> Maybe ByteString

-- | <i>O(n)</i> Break a <a>ByteString</a> into pieces separated by the
grbyte argument, consuming the delimiter. I.e.
gr
gr<pre>
grsplit '\n' "a\nb\nd\ne" == ["a","b","d","e"]
grsplit 'a'  "aXaXaXa"    == ["","X","X","X",""]
grsplit 'x'  "x"          == ["",""]
gr</pre>
gr
grand
gr
gr<pre>
grintercalate [c] . split c == id
grsplit == splitWith . (==)
gr</pre>
gr
grAs for all splitting functions in this library, this function does not
grcopy the substrings, it just constructs new <tt>ByteStrings</tt> that
grare slices of the original.
split :: Word8 -> ByteString -> [ByteString]

-- | <i>O(n)</i> Splits a <a>ByteString</a> into components delimited by
grseparators, where the predicate returns True for a separator element.
grThe resulting components do not contain the separators. Two adjacent
grseparators result in an empty component in the output. eg.
gr
gr<pre>
grsplitWith (=='a') "aabbaca" == ["","","bb","c",""]
grsplitWith (=='a') []        == []
gr</pre>
splitWith :: (Word8 -> Bool) -> ByteString -> [ByteString]

-- | <i>O(n)</i> The <a>isPrefixOf</a> function takes two ByteStrings and
grreturns <a>True</a> if the first is a prefix of the second.
isPrefixOf :: ByteString -> ByteString -> Bool

-- | <i>O(n)</i> The <a>isSuffixOf</a> function takes two ByteStrings and
grreturns <a>True</a> iff the first is a suffix of the second.
gr
grThe following holds:
gr
gr<pre>
grisSuffixOf x y == reverse x `isPrefixOf` reverse y
gr</pre>
gr
grHowever, the real implemenation uses memcmp to compare the end of the
grstring only, with no reverse required..
isSuffixOf :: ByteString -> ByteString -> Bool

-- | Check whether one string is a substring of another. <tt>isInfixOf p
grs</tt> is equivalent to <tt>not (null (findSubstrings p s))</tt>.
isInfixOf :: ByteString -> ByteString -> Bool

-- | Break a string on a substring, returning a pair of the part of the
grstring prior to the match, and the rest of the string.
gr
grThe following relationships hold:
gr
gr<pre>
grbreak (== c) l == breakSubstring (singleton c) l
gr</pre>
gr
grand:
gr
gr<pre>
grfindSubstring s l ==
gr   if null s then Just 0
gr             else case breakSubstring s l of
gr                      (x,y) | null y    -&gt; Nothing
gr                            | otherwise -&gt; Just (length x)
gr</pre>
gr
grFor example, to tokenise a string, dropping delimiters:
gr
gr<pre>
grtokenise x y = h : if null t then [] else tokenise x (drop (length x) t)
gr    where (h,t) = breakSubstring x y
gr</pre>
gr
grTo skip to the first occurence of a string:
gr
gr<pre>
grsnd (breakSubstring x y)
gr</pre>
gr
grTo take the parts of a string before a delimiter:
gr
gr<pre>
grfst (breakSubstring x y)
gr</pre>
gr
grNote that calling `breakSubstring x` does some preprocessing work, so
gryou should avoid unnecessarily duplicating breakSubstring calls with
grthe same pattern.
breakSubstring :: ByteString -> ByteString -> (ByteString, ByteString)

-- | Get the first index of a substring in another string, or
gr<a>Nothing</a> if the string is not found. <tt>findSubstring p s</tt>
gris equivalent to <tt>listToMaybe (findSubstrings p s)</tt>.

-- | <i>Deprecated: findSubstring is deprecated in favour of
grbreakSubstring.</i>
findSubstring :: ByteString -> ByteString -> Maybe Int

-- | Find the indexes of all (possibly overlapping) occurances of a
grsubstring in a string.

-- | <i>Deprecated: findSubstrings is deprecated in favour of
grbreakSubstring.</i>
findSubstrings :: ByteString -> ByteString -> [Int]

-- | <i>O(n)</i> <a>elem</a> is the <a>ByteString</a> membership predicate.
elem :: Word8 -> ByteString -> Bool

-- | <i>O(n)</i> <a>notElem</a> is the inverse of <a>elem</a>
notElem :: Word8 -> ByteString -> Bool

-- | <i>O(n)</i> The <a>find</a> function takes a predicate and a
grByteString, and returns the first element in matching the predicate,
gror <a>Nothing</a> if there is no such element.
gr
gr<pre>
grfind f p = case findIndex f p of Just n -&gt; Just (p ! n) ; _ -&gt; Nothing
gr</pre>
find :: (Word8 -> Bool) -> ByteString -> Maybe Word8

-- | <i>O(n)</i> <a>filter</a>, applied to a predicate and a ByteString,
grreturns a ByteString containing those characters that satisfy the
grpredicate.
filter :: (Word8 -> Bool) -> ByteString -> ByteString

-- | <i>O(n)</i> The <a>partition</a> function takes a predicate a
grByteString and returns the pair of ByteStrings with elements which do
grand do not satisfy the predicate, respectively; i.e.,
gr
gr<pre>
grpartition p bs == (filter p xs, filter (not . p) xs)
gr</pre>
partition :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <i>O(1)</i> <a>ByteString</a> index (subscript) operator, starting
grfrom 0.
index :: ByteString -> Int -> Word8

-- | <i>O(n)</i> The <a>elemIndex</a> function returns the index of the
grfirst element in the given <a>ByteString</a> which is equal to the
grquery element, or <a>Nothing</a> if there is no such element. This
grimplementation uses memchr(3).
elemIndex :: Word8 -> ByteString -> Maybe Int

-- | <i>O(n)</i> The <a>elemIndices</a> function extends <a>elemIndex</a>,
grby returning the indices of all elements equal to the query element,
grin ascending order. This implementation uses memchr(3).
elemIndices :: Word8 -> ByteString -> [Int]

-- | <i>O(n)</i> The <a>elemIndexEnd</a> function returns the last index of
grthe element in the given <a>ByteString</a> which is equal to the query
grelement, or <a>Nothing</a> if there is no such element. The following
grholds:
gr
gr<pre>
grelemIndexEnd c xs ==
gr(-) (length xs - 1) `fmap` elemIndex c (reverse xs)
gr</pre>
elemIndexEnd :: Word8 -> ByteString -> Maybe Int

-- | The <a>findIndex</a> function takes a predicate and a
gr<a>ByteString</a> and returns the index of the first element in the
grByteString satisfying the predicate.
findIndex :: (Word8 -> Bool) -> ByteString -> Maybe Int

-- | The <a>findIndices</a> function extends <a>findIndex</a>, by returning
grthe indices of all elements satisfying the predicate, in ascending
grorder.
findIndices :: (Word8 -> Bool) -> ByteString -> [Int]

-- | count returns the number of times its argument appears in the
grByteString
gr
gr<pre>
grcount = length . elemIndices
gr</pre>
gr
grBut more efficiently than using length on the intermediate list.
count :: Word8 -> ByteString -> Int

-- | <i>O(n)</i> <a>zip</a> takes two ByteStrings and returns a list of
grcorresponding pairs of bytes. If one input ByteString is short, excess
grelements of the longer ByteString are discarded. This is equivalent to
gra pair of <a>unpack</a> operations.
zip :: ByteString -> ByteString -> [(Word8, Word8)]

-- | <a>zipWith</a> generalises <a>zip</a> by zipping with the function
grgiven as the first argument, instead of a tupling function. For
grexample, <tt><a>zipWith</a> (+)</tt> is applied to two ByteStrings to
grproduce the list of corresponding sums.
zipWith :: (Word8 -> Word8 -> a) -> ByteString -> ByteString -> [a]

-- | <i>O(n)</i> <a>unzip</a> transforms a list of pairs of bytes into a
grpair of ByteStrings. Note that this performs two <a>pack</a>
groperations.
unzip :: [(Word8, Word8)] -> (ByteString, ByteString)

-- | <i>O(n)</i> Sort a ByteString efficiently, using counting sort.
sort :: ByteString -> ByteString

-- | <i>O(n)</i> Make a copy of the <a>ByteString</a> with its own storage.
grThis is mainly useful to allow the rest of the data pointed to by the
gr<a>ByteString</a> to be garbage collected, for example if a large
grstring has been read in, and only a small part of it is needed in the
grrest of the program.
copy :: ByteString -> ByteString

-- | <i>O(n).</i> Construct a new <tt>ByteString</tt> from a
gr<tt>CString</tt>. The resulting <tt>ByteString</tt> is an immutable
grcopy of the original <tt>CString</tt>, and is managed on the Haskell
grheap. The original <tt>CString</tt> must be null terminated.
packCString :: CString -> IO ByteString

-- | <i>O(n).</i> Construct a new <tt>ByteString</tt> from a
gr<tt>CStringLen</tt>. The resulting <tt>ByteString</tt> is an immutable
grcopy of the original <tt>CStringLen</tt>. The <tt>ByteString</tt> is a
grnormal Haskell value and will be managed on the Haskell heap.
packCStringLen :: CStringLen -> IO ByteString

-- | <i>O(n) construction</i> Use a <tt>ByteString</tt> with a function
grrequiring a null-terminated <tt>CString</tt>. The <tt>CString</tt> is
gra copy and will be freed automatically; it must not be stored or used
grafter the subcomputation finishes.
useAsCString :: ByteString -> (CString -> IO a) -> IO a

-- | <i>O(n) construction</i> Use a <tt>ByteString</tt> with a function
grrequiring a <tt>CStringLen</tt>. As for <tt>useAsCString</tt> this
grfunction makes a copy of the original <tt>ByteString</tt>. It must not
grbe stored or used after the subcomputation finishes.
useAsCStringLen :: ByteString -> (CStringLen -> IO a) -> IO a

-- | Read a line from stdin.
getLine :: IO ByteString

-- | getContents. Read stdin strictly. Equivalent to hGetContents stdin The
gr<a>Handle</a> is closed after the contents have been read.
getContents :: IO ByteString

-- | Write a ByteString to stdout
putStr :: ByteString -> IO ()

-- | Write a ByteString to stdout, appending a newline byte

-- | <i>Deprecated: Use Data.ByteString.Char8.putStrLn instead. (Functions
grthat rely on ASCII encodings belong in Data.ByteString.Char8)</i>
putStrLn :: ByteString -> IO ()

-- | The interact function takes a function of type <tt>ByteString -&gt;
grByteString</tt> as its argument. The entire input from the standard
grinput device is passed to this function as its argument, and the
grresulting string is output on the standard output device.
interact :: (ByteString -> ByteString) -> IO ()

-- | Read an entire file strictly into a <a>ByteString</a>.
readFile :: FilePath -> IO ByteString

-- | Write a <a>ByteString</a> to a file.
writeFile :: FilePath -> ByteString -> IO ()

-- | Append a <a>ByteString</a> to a file.
appendFile :: FilePath -> ByteString -> IO ()

-- | Read a line from a handle
hGetLine :: Handle -> IO ByteString

-- | Read a handle's entire contents strictly into a <a>ByteString</a>.
gr
grThis function reads chunks at a time, increasing the chunk size on
greach read. The final string is then realloced to the appropriate size.
grFor files &gt; half of available memory, this may lead to memory
grexhaustion. Consider using <a>readFile</a> in this case.
gr
grThe Handle is closed once the contents have been read, or if an
grexception is thrown.
hGetContents :: Handle -> IO ByteString

-- | Read a <a>ByteString</a> directly from the specified <a>Handle</a>.
grThis is far more efficient than reading the characters into a
gr<a>String</a> and then using <a>pack</a>. First argument is the Handle
grto read from, and the second is the number of bytes to read. It
grreturns the bytes read, up to n, or <a>empty</a> if EOF has been
grreached.
gr
gr<a>hGet</a> is implemented in terms of <a>hGetBuf</a>.
gr
grIf the handle is a pipe or socket, and the writing end is closed,
gr<a>hGet</a> will behave as if EOF was reached.
hGet :: Handle -> Int -> IO ByteString

-- | Like <a>hGet</a>, except that a shorter <a>ByteString</a> may be
grreturned if there are not enough bytes immediately available to
grsatisfy the whole request. <a>hGetSome</a> only blocks if there is no
grdata available, and EOF has not yet been reached.
hGetSome :: Handle -> Int -> IO ByteString

-- | hGetNonBlocking is similar to <a>hGet</a>, except that it will never
grblock waiting for data to become available, instead it returns only
grwhatever data is available. If there is no data available to be read,
gr<a>hGetNonBlocking</a> returns <a>empty</a>.
gr
grNote: on Windows and with Haskell implementation other than GHC, this
grfunction does not work correctly; it behaves identically to
gr<a>hGet</a>.
hGetNonBlocking :: Handle -> Int -> IO ByteString

-- | Outputs a <a>ByteString</a> to the specified <a>Handle</a>.
hPut :: Handle -> ByteString -> IO ()

-- | Similar to <a>hPut</a> except that it will never block. Instead it
grreturns any tail that did not get written. This tail may be
gr<a>empty</a> in the case that the whole string was written, or the
grwhole original string if nothing was written. Partial writes are also
grpossible.
gr
grNote: on Windows and with Haskell implementation other than GHC, this
grfunction does not work correctly; it behaves identically to
gr<a>hPut</a>.
hPutNonBlocking :: Handle -> ByteString -> IO ByteString

-- | A synonym for <tt>hPut</tt>, for compatibility
hPutStr :: Handle -> ByteString -> IO ()

-- | Write a ByteString to a handle, appending a newline byte

-- | <i>Deprecated: Use Data.ByteString.Char8.hPutStrLn instead. (Functions
grthat rely on ASCII encodings belong in Data.ByteString.Char8)</i>
hPutStrLn :: Handle -> ByteString -> IO ()

-- | <a>breakByte</a> breaks its ByteString argument at the first occurence
grof the specified byte. It is more efficient than <a>break</a> as it is
grimplemented with <tt>memchr(3)</tt>. I.e.
gr
gr<pre>
grbreak (=='c') "abcd" == breakByte 'c' "abcd"
gr</pre>

-- | <i>Deprecated: It is an internal function and should never have been
grexported. Use 'break (== x)' instead. (There are rewrite rules that
grhandle this special case of <a>break</a>.)</i>
breakByte :: Word8 -> ByteString -> (ByteString, ByteString)


-- | A time and space-efficient implementation of lazy byte vectors using
grlists of packed <a>Word8</a> arrays, suitable for high performance
gruse, both in terms of large data quantities, or high speed
grrequirements. Lazy ByteStrings are encoded as lazy lists of strict
grchunks of bytes.
gr
grA key feature of lazy ByteStrings is the means to manipulate large or
grunbounded streams of data without requiring the entire sequence to be
grresident in memory. To take advantage of this you have to write your
grfunctions in a lazy streaming style, e.g. classic pipeline
grcomposition. The default I/O chunk size is 32k, which should be good
grin most circumstances.
gr
grSome operations, such as <a>concat</a>, <a>append</a>, <a>reverse</a>
grand <a>cons</a>, have better complexity than their
gr<a>Data.ByteString</a> equivalents, due to optimisations resulting
grfrom the list spine structure. For other operations lazy ByteStrings
grare usually within a few percent of strict ones.
gr
grThe recomended way to assemble lazy ByteStrings from smaller parts is
grto use the builder monoid from <a>Data.ByteString.Builder</a>.
gr
grThis module is intended to be imported <tt>qualified</tt>, to avoid
grname clashes with <a>Prelude</a> functions. eg.
gr
gr<pre>
grimport qualified Data.ByteString.Lazy as B
gr</pre>
gr
grOriginal GHC implementation by Bryan O'Sullivan. Rewritten to use
gr<a>UArray</a> by Simon Marlow. Rewritten to support slices and use
gr<a>ForeignPtr</a> by David Roundy. Rewritten again and extended by Don
grStewart and Duncan Coutts. Lazy variant by Duncan Coutts and Don
grStewart.
module Data.ByteString.Lazy

-- | A space-efficient representation of a <a>Word8</a> vector, supporting
grmany efficient operations.
gr
grA lazy <a>ByteString</a> contains 8-bit bytes, or by using the
groperations from <a>Data.ByteString.Lazy.Char8</a> it can be
grinterpreted as containing 8-bit characters.
data ByteString

-- | <i>O(1)</i> The empty <a>ByteString</a>
empty :: ByteString

-- | <i>O(1)</i> Convert a <a>Word8</a> into a <a>ByteString</a>
singleton :: Word8 -> ByteString

-- | <i>O(n)</i> Convert a '[Word8]' into a <a>ByteString</a>.
pack :: [Word8] -> ByteString

-- | <i>O(n)</i> Converts a <a>ByteString</a> to a '[Word8]'.
unpack :: ByteString -> [Word8]

-- | <i>O(1)</i> Convert a strict <a>ByteString</a> into a lazy
gr<a>ByteString</a>.
fromStrict :: ByteString -> ByteString

-- | <i>O(n)</i> Convert a lazy <a>ByteString</a> into a strict
gr<a>ByteString</a>.
gr
grNote that this is an <i>expensive</i> operation that forces the whole
grlazy ByteString into memory and then copies all the data. If possible,
grtry to avoid converting back and forth between strict and lazy
grbytestrings.
toStrict :: ByteString -> ByteString

-- | <i>O(c)</i> Convert a list of strict <a>ByteString</a> into a lazy
gr<a>ByteString</a>
fromChunks :: [ByteString] -> ByteString

-- | <i>O(c)</i> Convert a lazy <a>ByteString</a> into a list of strict
gr<a>ByteString</a>
toChunks :: ByteString -> [ByteString]

-- | Consume the chunks of a lazy ByteString with a natural right fold.
foldrChunks :: (ByteString -> a -> a) -> a -> ByteString -> a

-- | Consume the chunks of a lazy ByteString with a strict, tail-recursive,
graccumulating left fold.
foldlChunks :: (a -> ByteString -> a) -> a -> ByteString -> a

-- | <i>O(1)</i> <a>cons</a> is analogous to '(:)' for lists.
cons :: Word8 -> ByteString -> ByteString
infixr 5 `cons`

-- | <i>O(1)</i> Unlike <a>cons</a>, 'cons\'' is strict in the ByteString
grthat we are consing onto. More precisely, it forces the head and the
grfirst chunk. It does this because, for space efficiency, it may
grcoalesce the new byte onto the first 'chunk' rather than starting a
grnew 'chunk'.
gr
grSo that means you can't use a lazy recursive contruction like this:
gr
gr<pre>
grlet xs = cons\' c xs in xs
gr</pre>
gr
grYou can however use <a>cons</a>, as well as <a>repeat</a> and
gr<a>cycle</a>, to build infinite lazy ByteStrings.
cons' :: Word8 -> ByteString -> ByteString
infixr 5 `cons'`

-- | <i>O(n/c)</i> Append a byte to the end of a <a>ByteString</a>
snoc :: ByteString -> Word8 -> ByteString
infixl 5 `snoc`

-- | <i>O(n/c)</i> Append two ByteStrings
append :: ByteString -> ByteString -> ByteString

-- | <i>O(1)</i> Extract the first element of a ByteString, which must be
grnon-empty.
head :: ByteString -> Word8

-- | <i>O(1)</i> Extract the head and tail of a ByteString, returning
grNothing if it is empty.
uncons :: ByteString -> Maybe (Word8, ByteString)

-- | <i>O(n/c)</i> Extract the <a>init</a> and <a>last</a> of a ByteString,
grreturning Nothing if it is empty.
gr
gr<ul>
gr<li>It is no faster than using <a>init</a> and <a>last</a></li>
gr</ul>
unsnoc :: ByteString -> Maybe (ByteString, Word8)

-- | <i>O(n/c)</i> Extract the last element of a ByteString, which must be
grfinite and non-empty.
last :: ByteString -> Word8

-- | <i>O(1)</i> Extract the elements after the head of a ByteString, which
grmust be non-empty.
tail :: ByteString -> ByteString

-- | <i>O(n/c)</i> Return all the elements of a <a>ByteString</a> except
grthe last one.
init :: ByteString -> ByteString

-- | <i>O(1)</i> Test whether a ByteString is empty.
null :: ByteString -> Bool

-- | <i>O(n/c)</i> <a>length</a> returns the length of a ByteString as an
gr<a>Int64</a>
length :: ByteString -> Int64

-- | <i>O(n)</i> <a>map</a> <tt>f xs</tt> is the ByteString obtained by
grapplying <tt>f</tt> to each element of <tt>xs</tt>.
map :: (Word8 -> Word8) -> ByteString -> ByteString

-- | <i>O(n)</i> <a>reverse</a> <tt>xs</tt> returns the elements of
gr<tt>xs</tt> in reverse order.
reverse :: ByteString -> ByteString

-- | The <a>intersperse</a> function takes a <a>Word8</a> and a
gr<a>ByteString</a> and `intersperses' that byte between the elements of
grthe <a>ByteString</a>. It is analogous to the intersperse function on
grLists.
intersperse :: Word8 -> ByteString -> ByteString

-- | <i>O(n)</i> The <a>intercalate</a> function takes a <a>ByteString</a>
grand a list of <a>ByteString</a>s and concatenates the list after
grinterspersing the first argument between each element of the list.
intercalate :: ByteString -> [ByteString] -> ByteString

-- | The <a>transpose</a> function transposes the rows and columns of its
gr<a>ByteString</a> argument.
transpose :: [ByteString] -> [ByteString]

-- | <a>foldl</a>, applied to a binary operator, a starting value
gr(typically the left-identity of the operator), and a ByteString,
grreduces the ByteString using the binary operator, from left to right.
foldl :: (a -> Word8 -> a) -> a -> ByteString -> a

-- | 'foldl\'' is like <a>foldl</a>, but strict in the accumulator.
foldl' :: (a -> Word8 -> a) -> a -> ByteString -> a

-- | <a>foldl1</a> is a variant of <a>foldl</a> that has no starting value
grargument, and thus must be applied to non-empty <tt>ByteStrings</tt>.
foldl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8

-- | 'foldl1\'' is like <a>foldl1</a>, but strict in the accumulator.
foldl1' :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8

-- | <a>foldr</a>, applied to a binary operator, a starting value
gr(typically the right-identity of the operator), and a ByteString,
grreduces the ByteString using the binary operator, from right to left.
foldr :: (Word8 -> a -> a) -> a -> ByteString -> a

-- | <a>foldr1</a> is a variant of <a>foldr</a> that has no starting value
grargument, and thus must be applied to non-empty <a>ByteString</a>s
foldr1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8

-- | <i>O(n)</i> Concatenate a list of ByteStrings.
concat :: [ByteString] -> ByteString

-- | Map a function over a <a>ByteString</a> and concatenate the results
concatMap :: (Word8 -> ByteString) -> ByteString -> ByteString

-- | <i>O(n)</i> Applied to a predicate and a ByteString, <a>any</a>
grdetermines if any element of the <a>ByteString</a> satisfies the
grpredicate.
any :: (Word8 -> Bool) -> ByteString -> Bool

-- | <i>O(n)</i> Applied to a predicate and a <a>ByteString</a>, <a>all</a>
grdetermines if all elements of the <a>ByteString</a> satisfy the
grpredicate.
all :: (Word8 -> Bool) -> ByteString -> Bool

-- | <i>O(n)</i> <a>maximum</a> returns the maximum value from a
gr<a>ByteString</a>
maximum :: ByteString -> Word8

-- | <i>O(n)</i> <a>minimum</a> returns the minimum value from a
gr<a>ByteString</a>
minimum :: ByteString -> Word8

-- | <a>scanl</a> is similar to <a>foldl</a>, but returns a list of
grsuccessive reduced values from the left. This function will fuse.
gr
gr<pre>
grscanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
gr</pre>
gr
grNote that
gr
gr<pre>
grlast (scanl f z xs) == foldl f z xs.
gr</pre>
scanl :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString

-- | The <a>mapAccumL</a> function behaves like a combination of <a>map</a>
grand <a>foldl</a>; it applies a function to each element of a
grByteString, passing an accumulating parameter from left to right, and
grreturning a final value of this accumulator together with the new
grByteString.
mapAccumL :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)

-- | The <a>mapAccumR</a> function behaves like a combination of <a>map</a>
grand <a>foldr</a>; it applies a function to each element of a
grByteString, passing an accumulating parameter from right to left, and
grreturning a final value of this accumulator together with the new
grByteString.
mapAccumR :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)

-- | <tt><a>repeat</a> x</tt> is an infinite ByteString, with <tt>x</tt>
grthe value of every element.
repeat :: Word8 -> ByteString

-- | <i>O(n)</i> <tt><a>replicate</a> n x</tt> is a ByteString of length
gr<tt>n</tt> with <tt>x</tt> the value of every element.
replicate :: Int64 -> Word8 -> ByteString

-- | <a>cycle</a> ties a finite ByteString into a circular one, or
grequivalently, the infinite repetition of the original ByteString.
cycle :: ByteString -> ByteString

-- | <tt><a>iterate</a> f x</tt> returns an infinite ByteString of repeated
grapplications of <tt>f</tt> to <tt>x</tt>:
gr
gr<pre>
griterate f x == [x, f x, f (f x), ...]
gr</pre>
iterate :: (Word8 -> Word8) -> Word8 -> ByteString

-- | <i>O(n)</i> The <a>unfoldr</a> function is analogous to the List
gr'unfoldr'. <a>unfoldr</a> builds a ByteString from a seed value. The
grfunction takes the element and returns <a>Nothing</a> if it is done
grproducing the ByteString or returns <a>Just</a> <tt>(a,b)</tt>, in
grwhich case, <tt>a</tt> is a prepending to the ByteString and
gr<tt>b</tt> is used as the next element in a recursive call.
unfoldr :: (a -> Maybe (Word8, a)) -> a -> ByteString

-- | <i>O(n/c)</i> <a>take</a> <tt>n</tt>, applied to a ByteString
gr<tt>xs</tt>, returns the prefix of <tt>xs</tt> of length <tt>n</tt>,
gror <tt>xs</tt> itself if <tt>n &gt; <a>length</a> xs</tt>.
take :: Int64 -> ByteString -> ByteString

-- | <i>O(n/c)</i> <a>drop</a> <tt>n xs</tt> returns the suffix of
gr<tt>xs</tt> after the first <tt>n</tt> elements, or <tt>[]</tt> if
gr<tt>n &gt; <a>length</a> xs</tt>.
drop :: Int64 -> ByteString -> ByteString

-- | <i>O(n/c)</i> <a>splitAt</a> <tt>n xs</tt> is equivalent to
gr<tt>(<a>take</a> n xs, <a>drop</a> n xs)</tt>.
splitAt :: Int64 -> ByteString -> (ByteString, ByteString)

-- | <a>takeWhile</a>, applied to a predicate <tt>p</tt> and a ByteString
gr<tt>xs</tt>, returns the longest prefix (possibly empty) of
gr<tt>xs</tt> of elements that satisfy <tt>p</tt>.
takeWhile :: (Word8 -> Bool) -> ByteString -> ByteString

-- | <a>dropWhile</a> <tt>p xs</tt> returns the suffix remaining after
gr<a>takeWhile</a> <tt>p xs</tt>.
dropWhile :: (Word8 -> Bool) -> ByteString -> ByteString

-- | <a>span</a> <tt>p xs</tt> breaks the ByteString into two segments. It
gris equivalent to <tt>(<a>takeWhile</a> p xs, <a>dropWhile</a> p
grxs)</tt>
span :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <a>break</a> <tt>p</tt> is equivalent to <tt><a>span</a> (<a>not</a> .
grp)</tt>.
break :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)

-- | The <a>group</a> function takes a ByteString and returns a list of
grByteStrings such that the concatenation of the result is equal to the
grargument. Moreover, each sublist in the result contains only equal
grelements. For example,
gr
gr<pre>
grgroup "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
gr</pre>
gr
grIt is a special case of <a>groupBy</a>, which allows the programmer to
grsupply their own equality test.
group :: ByteString -> [ByteString]

-- | The <a>groupBy</a> function is the non-overloaded version of
gr<a>group</a>.
groupBy :: (Word8 -> Word8 -> Bool) -> ByteString -> [ByteString]

-- | <i>O(n)</i> Return all initial segments of the given
gr<a>ByteString</a>, shortest first.
inits :: ByteString -> [ByteString]

-- | <i>O(n)</i> Return all final segments of the given <a>ByteString</a>,
grlongest first.
tails :: ByteString -> [ByteString]

-- | <i>O(n)</i> The <a>stripPrefix</a> function takes two ByteStrings and
grreturns <a>Just</a> the remainder of the second iff the first is its
grprefix, and otherwise <a>Nothing</a>.
stripPrefix :: ByteString -> ByteString -> Maybe ByteString

-- | <i>O(n)</i> The <a>stripSuffix</a> function takes two ByteStrings and
grreturns <a>Just</a> the remainder of the second iff the first is its
grsuffix, and otherwise <a>Nothing</a>.
stripSuffix :: ByteString -> ByteString -> Maybe ByteString

-- | <i>O(n)</i> Break a <a>ByteString</a> into pieces separated by the
grbyte argument, consuming the delimiter. I.e.
gr
gr<pre>
grsplit '\n' "a\nb\nd\ne" == ["a","b","d","e"]
grsplit 'a'  "aXaXaXa"    == ["","X","X","X",""]
grsplit 'x'  "x"          == ["",""]
gr</pre>
gr
grand
gr
gr<pre>
grintercalate [c] . split c == id
grsplit == splitWith . (==)
gr</pre>
gr
grAs for all splitting functions in this library, this function does not
grcopy the substrings, it just constructs new <tt>ByteStrings</tt> that
grare slices of the original.
split :: Word8 -> ByteString -> [ByteString]

-- | <i>O(n)</i> Splits a <a>ByteString</a> into components delimited by
grseparators, where the predicate returns True for a separator element.
grThe resulting components do not contain the separators. Two adjacent
grseparators result in an empty component in the output. eg.
gr
gr<pre>
grsplitWith (=='a') "aabbaca" == ["","","bb","c",""]
grsplitWith (=='a') []        == []
gr</pre>
splitWith :: (Word8 -> Bool) -> ByteString -> [ByteString]

-- | <i>O(n)</i> The <a>isPrefixOf</a> function takes two ByteStrings and
grreturns <a>True</a> iff the first is a prefix of the second.
isPrefixOf :: ByteString -> ByteString -> Bool

-- | <i>O(n)</i> The <a>isSuffixOf</a> function takes two ByteStrings and
grreturns <a>True</a> iff the first is a suffix of the second.
gr
grThe following holds:
gr
gr<pre>
grisSuffixOf x y == reverse x `isPrefixOf` reverse y
gr</pre>
isSuffixOf :: ByteString -> ByteString -> Bool

-- | <i>O(n)</i> <a>elem</a> is the <a>ByteString</a> membership predicate.
elem :: Word8 -> ByteString -> Bool

-- | <i>O(n)</i> <a>notElem</a> is the inverse of <a>elem</a>
notElem :: Word8 -> ByteString -> Bool

-- | <i>O(n)</i> The <a>find</a> function takes a predicate and a
grByteString, and returns the first element in matching the predicate,
gror <a>Nothing</a> if there is no such element.
gr
gr<pre>
grfind f p = case findIndex f p of Just n -&gt; Just (p ! n) ; _ -&gt; Nothing
gr</pre>
find :: (Word8 -> Bool) -> ByteString -> Maybe Word8

-- | <i>O(n)</i> <a>filter</a>, applied to a predicate and a ByteString,
grreturns a ByteString containing those characters that satisfy the
grpredicate.
filter :: (Word8 -> Bool) -> ByteString -> ByteString

-- | <i>O(n)</i> The <a>partition</a> function takes a predicate a
grByteString and returns the pair of ByteStrings with elements which do
grand do not satisfy the predicate, respectively; i.e.,
gr
gr<pre>
grpartition p bs == (filter p xs, filter (not . p) xs)
gr</pre>
partition :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <i>O(c)</i> <a>ByteString</a> index (subscript) operator, starting
grfrom 0.
index :: ByteString -> Int64 -> Word8

-- | <i>O(n)</i> The <a>elemIndex</a> function returns the index of the
grfirst element in the given <a>ByteString</a> which is equal to the
grquery element, or <a>Nothing</a> if there is no such element. This
grimplementation uses memchr(3).
elemIndex :: Word8 -> ByteString -> Maybe Int64

-- | <i>O(n)</i> The <a>elemIndexEnd</a> function returns the last index of
grthe element in the given <a>ByteString</a> which is equal to the query
grelement, or <a>Nothing</a> if there is no such element. The following
grholds:
gr
gr<pre>
grelemIndexEnd c xs ==
gr(-) (length xs - 1) `fmap` elemIndex c (reverse xs)
gr</pre>
elemIndexEnd :: Word8 -> ByteString -> Maybe Int64

-- | <i>O(n)</i> The <a>elemIndices</a> function extends <a>elemIndex</a>,
grby returning the indices of all elements equal to the query element,
grin ascending order. This implementation uses memchr(3).
elemIndices :: Word8 -> ByteString -> [Int64]

-- | The <a>findIndex</a> function takes a predicate and a
gr<a>ByteString</a> and returns the index of the first element in the
grByteString satisfying the predicate.
findIndex :: (Word8 -> Bool) -> ByteString -> Maybe Int64

-- | The <a>findIndices</a> function extends <a>findIndex</a>, by returning
grthe indices of all elements satisfying the predicate, in ascending
grorder.
findIndices :: (Word8 -> Bool) -> ByteString -> [Int64]

-- | count returns the number of times its argument appears in the
grByteString
gr
gr<pre>
grcount = length . elemIndices
gr</pre>
gr
grBut more efficiently than using length on the intermediate list.
count :: Word8 -> ByteString -> Int64

-- | <i>O(n)</i> <a>zip</a> takes two ByteStrings and returns a list of
grcorresponding pairs of bytes. If one input ByteString is short, excess
grelements of the longer ByteString are discarded. This is equivalent to
gra pair of <a>unpack</a> operations.
zip :: ByteString -> ByteString -> [(Word8, Word8)]

-- | <a>zipWith</a> generalises <a>zip</a> by zipping with the function
grgiven as the first argument, instead of a tupling function. For
grexample, <tt><a>zipWith</a> (+)</tt> is applied to two ByteStrings to
grproduce the list of corresponding sums.
zipWith :: (Word8 -> Word8 -> a) -> ByteString -> ByteString -> [a]

-- | <i>O(n)</i> <a>unzip</a> transforms a list of pairs of bytes into a
grpair of ByteStrings. Note that this performs two <a>pack</a>
groperations.
unzip :: [(Word8, Word8)] -> (ByteString, ByteString)

-- | <i>O(n)</i> Make a copy of the <a>ByteString</a> with its own storage.
grThis is mainly useful to allow the rest of the data pointed to by the
gr<a>ByteString</a> to be garbage collected, for example if a large
grstring has been read in, and only a small part of it is needed in the
grrest of the program.
copy :: ByteString -> ByteString

-- | getContents. Equivalent to hGetContents stdin. Will read <i>lazily</i>
getContents :: IO ByteString

-- | Write a ByteString to stdout
putStr :: ByteString -> IO ()

-- | Write a ByteString to stdout, appending a newline byte

-- | <i>Deprecated: Use Data.ByteString.Lazy.Char8.putStrLn instead.
gr(Functions that rely on ASCII encodings belong in
grData.ByteString.Lazy.Char8)</i>
putStrLn :: ByteString -> IO ()

-- | The interact function takes a function of type <tt>ByteString -&gt;
grByteString</tt> as its argument. The entire input from the standard
grinput device is passed to this function as its argument, and the
grresulting string is output on the standard output device.
interact :: (ByteString -> ByteString) -> IO ()

-- | Read an entire file <i>lazily</i> into a <a>ByteString</a>. The Handle
grwill be held open until EOF is encountered.
readFile :: FilePath -> IO ByteString

-- | Write a <a>ByteString</a> to a file.
writeFile :: FilePath -> ByteString -> IO ()

-- | Append a <a>ByteString</a> to a file.
appendFile :: FilePath -> ByteString -> IO ()

-- | Read entire handle contents <i>lazily</i> into a <a>ByteString</a>.
grChunks are read on demand, using the default chunk size.
gr
grOnce EOF is encountered, the Handle is closed.
gr
grNote: the <a>Handle</a> should be placed in binary mode with
gr<a>hSetBinaryMode</a> for <a>hGetContents</a> to work correctly.
hGetContents :: Handle -> IO ByteString

-- | Read <tt>n</tt> bytes into a <a>ByteString</a>, directly from the
grspecified <a>Handle</a>.
hGet :: Handle -> Int -> IO ByteString

-- | hGetNonBlocking is similar to <a>hGet</a>, except that it will never
grblock waiting for data to become available, instead it returns only
grwhatever data is available. If there is no data available to be read,
gr<a>hGetNonBlocking</a> returns <a>empty</a>.
gr
grNote: on Windows and with Haskell implementation other than GHC, this
grfunction does not work correctly; it behaves identically to
gr<a>hGet</a>.
hGetNonBlocking :: Handle -> Int -> IO ByteString

-- | Outputs a <a>ByteString</a> to the specified <a>Handle</a>. The chunks
grwill be written one at a time. Other threads might write to the
gr<a>Handle</a> between the writes, and hence <a>hPut</a> alone might
grnot be suitable for concurrent writes.
hPut :: Handle -> ByteString -> IO ()

-- | Similar to <a>hPut</a> except that it will never block. Instead it
grreturns any tail that did not get written. This tail may be
gr<a>empty</a> in the case that the whole string was written, or the
grwhole original string if nothing was written. Partial writes are also
grpossible.
gr
grNote: on Windows and with Haskell implementation other than GHC, this
grfunction does not work correctly; it behaves identically to
gr<a>hPut</a>.
hPutNonBlocking :: Handle -> ByteString -> IO ByteString

-- | A synonym for <tt>hPut</tt>, for compatibility
hPutStr :: Handle -> ByteString -> IO ()


-- | Manipulate <i>lazy</i> <a>ByteString</a>s using <a>Char</a>
groperations. All Chars will be truncated to 8 bits. It can be expected
grthat these functions will run at identical speeds to their
gr<a>Word8</a> equivalents in <a>Data.ByteString.Lazy</a>.
gr
grThis module is intended to be imported <tt>qualified</tt>, to avoid
grname clashes with <a>Prelude</a> functions. eg.
gr
gr<pre>
grimport qualified Data.ByteString.Lazy.Char8 as C
gr</pre>
gr
grThe Char8 interface to bytestrings provides an instance of IsString
grfor the ByteString type, enabling you to use string literals, and have
grthem implicitly packed to ByteStrings. Use <tt>{-# LANGUAGE
grOverloadedStrings #-}</tt> to enable this.
module Data.ByteString.Lazy.Char8

-- | A space-efficient representation of a <a>Word8</a> vector, supporting
grmany efficient operations.
gr
grA lazy <a>ByteString</a> contains 8-bit bytes, or by using the
groperations from <a>Data.ByteString.Lazy.Char8</a> it can be
grinterpreted as containing 8-bit characters.
data ByteString

-- | <i>O(1)</i> The empty <a>ByteString</a>
empty :: ByteString

-- | <i>O(1)</i> Convert a <a>Char</a> into a <a>ByteString</a>
singleton :: Char -> ByteString

-- | <i>O(n)</i> Convert a <a>String</a> into a <a>ByteString</a>.
pack :: [Char] -> ByteString

-- | <i>O(n)</i> Converts a <a>ByteString</a> to a <a>String</a>.
unpack :: ByteString -> [Char]

-- | <i>O(c)</i> Convert a list of strict <a>ByteString</a> into a lazy
gr<a>ByteString</a>
fromChunks :: [ByteString] -> ByteString

-- | <i>O(c)</i> Convert a lazy <a>ByteString</a> into a list of strict
gr<a>ByteString</a>
toChunks :: ByteString -> [ByteString]

-- | <i>O(1)</i> Convert a strict <a>ByteString</a> into a lazy
gr<a>ByteString</a>.
fromStrict :: ByteString -> ByteString

-- | <i>O(n)</i> Convert a lazy <a>ByteString</a> into a strict
gr<a>ByteString</a>.
gr
grNote that this is an <i>expensive</i> operation that forces the whole
grlazy ByteString into memory and then copies all the data. If possible,
grtry to avoid converting back and forth between strict and lazy
grbytestrings.
toStrict :: ByteString -> ByteString

-- | <i>O(1)</i> <a>cons</a> is analogous to '(:)' for lists.
cons :: Char -> ByteString -> ByteString
infixr 5 `cons`

-- | <i>O(1)</i> Unlike <a>cons</a>, 'cons\'' is strict in the ByteString
grthat we are consing onto. More precisely, it forces the head and the
grfirst chunk. It does this because, for space efficiency, it may
grcoalesce the new byte onto the first 'chunk' rather than starting a
grnew 'chunk'.
gr
grSo that means you can't use a lazy recursive contruction like this:
gr
gr<pre>
grlet xs = cons\' c xs in xs
gr</pre>
gr
grYou can however use <a>cons</a>, as well as <a>repeat</a> and
gr<a>cycle</a>, to build infinite lazy ByteStrings.
cons' :: Char -> ByteString -> ByteString
infixr 5 `cons'`

-- | <i>O(n)</i> Append a Char to the end of a <a>ByteString</a>. Similar
grto <a>cons</a>, this function performs a memcpy.
snoc :: ByteString -> Char -> ByteString
infixl 5 `snoc`

-- | <i>O(n/c)</i> Append two ByteStrings
append :: ByteString -> ByteString -> ByteString

-- | <i>O(1)</i> Extract the first element of a ByteString, which must be
grnon-empty.
head :: ByteString -> Char

-- | <i>O(1)</i> Extract the head and tail of a ByteString, returning
grNothing if it is empty.
uncons :: ByteString -> Maybe (Char, ByteString)

-- | <i>O(1)</i> Extract the last element of a packed string, which must be
grnon-empty.
last :: ByteString -> Char

-- | <i>O(1)</i> Extract the elements after the head of a ByteString, which
grmust be non-empty.
tail :: ByteString -> ByteString

-- | <i>O(n/c)</i> Extract the <a>init</a> and <a>last</a> of a ByteString,
grreturning Nothing if it is empty.
unsnoc :: ByteString -> Maybe (ByteString, Char)

-- | <i>O(n/c)</i> Return all the elements of a <a>ByteString</a> except
grthe last one.
init :: ByteString -> ByteString

-- | <i>O(1)</i> Test whether a ByteString is empty.
null :: ByteString -> Bool

-- | <i>O(n/c)</i> <a>length</a> returns the length of a ByteString as an
gr<a>Int64</a>
length :: ByteString -> Int64

-- | <i>O(n)</i> <a>map</a> <tt>f xs</tt> is the ByteString obtained by
grapplying <tt>f</tt> to each element of <tt>xs</tt>
map :: (Char -> Char) -> ByteString -> ByteString

-- | <i>O(n)</i> <a>reverse</a> <tt>xs</tt> returns the elements of
gr<tt>xs</tt> in reverse order.
reverse :: ByteString -> ByteString

-- | <i>O(n)</i> The <a>intersperse</a> function takes a Char and a
gr<a>ByteString</a> and `intersperses' that Char between the elements of
grthe <a>ByteString</a>. It is analogous to the intersperse function on
grLists.
intersperse :: Char -> ByteString -> ByteString

-- | <i>O(n)</i> The <a>intercalate</a> function takes a <a>ByteString</a>
grand a list of <a>ByteString</a>s and concatenates the list after
grinterspersing the first argument between each element of the list.
intercalate :: ByteString -> [ByteString] -> ByteString

-- | The <a>transpose</a> function transposes the rows and columns of its
gr<a>ByteString</a> argument.
transpose :: [ByteString] -> [ByteString]

-- | <a>foldl</a>, applied to a binary operator, a starting value
gr(typically the left-identity of the operator), and a ByteString,
grreduces the ByteString using the binary operator, from left to right.
foldl :: (a -> Char -> a) -> a -> ByteString -> a

-- | 'foldl\'' is like foldl, but strict in the accumulator.
foldl' :: (a -> Char -> a) -> a -> ByteString -> a

-- | <a>foldl1</a> is a variant of <a>foldl</a> that has no starting value
grargument, and thus must be applied to non-empty <tt>ByteStrings</tt>.
foldl1 :: (Char -> Char -> Char) -> ByteString -> Char

-- | 'foldl1\'' is like <a>foldl1</a>, but strict in the accumulator.
foldl1' :: (Char -> Char -> Char) -> ByteString -> Char

-- | <a>foldr</a>, applied to a binary operator, a starting value
gr(typically the right-identity of the operator), and a packed string,
grreduces the packed string using the binary operator, from right to
grleft.
foldr :: (Char -> a -> a) -> a -> ByteString -> a

-- | <a>foldr1</a> is a variant of <a>foldr</a> that has no starting value
grargument, and thus must be applied to non-empty <a>ByteString</a>s
foldr1 :: (Char -> Char -> Char) -> ByteString -> Char

-- | <i>O(n)</i> Concatenate a list of ByteStrings.
concat :: [ByteString] -> ByteString

-- | Map a function over a <a>ByteString</a> and concatenate the results
concatMap :: (Char -> ByteString) -> ByteString -> ByteString

-- | Applied to a predicate and a ByteString, <a>any</a> determines if any
grelement of the <a>ByteString</a> satisfies the predicate.
any :: (Char -> Bool) -> ByteString -> Bool

-- | Applied to a predicate and a <a>ByteString</a>, <a>all</a> determines
grif all elements of the <a>ByteString</a> satisfy the predicate.
all :: (Char -> Bool) -> ByteString -> Bool

-- | <a>maximum</a> returns the maximum value from a <a>ByteString</a>
maximum :: ByteString -> Char

-- | <a>minimum</a> returns the minimum value from a <a>ByteString</a>
minimum :: ByteString -> Char

-- | <a>scanl</a> is similar to <a>foldl</a>, but returns a list of
grsuccessive reduced values from the left. This function will fuse.
gr
gr<pre>
grscanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
gr</pre>
gr
grNote that
gr
gr<pre>
grlast (scanl f z xs) == foldl f z xs.
gr</pre>
scanl :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString

-- | The <a>mapAccumL</a> function behaves like a combination of <a>map</a>
grand <a>foldl</a>; it applies a function to each element of a
grByteString, passing an accumulating parameter from left to right, and
grreturning a final value of this accumulator together with the new
grByteString.
mapAccumL :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)

-- | The <a>mapAccumR</a> function behaves like a combination of <a>map</a>
grand <a>foldr</a>; it applies a function to each element of a
grByteString, passing an accumulating parameter from right to left, and
grreturning a final value of this accumulator together with the new
grByteString.
mapAccumR :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)

-- | <tt><a>repeat</a> x</tt> is an infinite ByteString, with <tt>x</tt>
grthe value of every element.
repeat :: Char -> ByteString

-- | <i>O(n)</i> <tt><a>replicate</a> n x</tt> is a ByteString of length
gr<tt>n</tt> with <tt>x</tt> the value of every element.
replicate :: Int64 -> Char -> ByteString

-- | <a>cycle</a> ties a finite ByteString into a circular one, or
grequivalently, the infinite repetition of the original ByteString.
cycle :: ByteString -> ByteString

-- | <tt><a>iterate</a> f x</tt> returns an infinite ByteString of repeated
grapplications of <tt>f</tt> to <tt>x</tt>:
gr
gr<pre>
griterate f x == [x, f x, f (f x), ...]
gr</pre>
iterate :: (Char -> Char) -> Char -> ByteString

-- | <i>O(n)</i> The <a>unfoldr</a> function is analogous to the List
gr'unfoldr'. <a>unfoldr</a> builds a ByteString from a seed value. The
grfunction takes the element and returns <a>Nothing</a> if it is done
grproducing the ByteString or returns <a>Just</a> <tt>(a,b)</tt>, in
grwhich case, <tt>a</tt> is a prepending to the ByteString and
gr<tt>b</tt> is used as the next element in a recursive call.
unfoldr :: (a -> Maybe (Char, a)) -> a -> ByteString

-- | <i>O(n/c)</i> <a>take</a> <tt>n</tt>, applied to a ByteString
gr<tt>xs</tt>, returns the prefix of <tt>xs</tt> of length <tt>n</tt>,
gror <tt>xs</tt> itself if <tt>n &gt; <a>length</a> xs</tt>.
take :: Int64 -> ByteString -> ByteString

-- | <i>O(n/c)</i> <a>drop</a> <tt>n xs</tt> returns the suffix of
gr<tt>xs</tt> after the first <tt>n</tt> elements, or <tt>[]</tt> if
gr<tt>n &gt; <a>length</a> xs</tt>.
drop :: Int64 -> ByteString -> ByteString

-- | <i>O(n/c)</i> <a>splitAt</a> <tt>n xs</tt> is equivalent to
gr<tt>(<a>take</a> n xs, <a>drop</a> n xs)</tt>.
splitAt :: Int64 -> ByteString -> (ByteString, ByteString)

-- | <a>takeWhile</a>, applied to a predicate <tt>p</tt> and a ByteString
gr<tt>xs</tt>, returns the longest prefix (possibly empty) of
gr<tt>xs</tt> of elements that satisfy <tt>p</tt>.
takeWhile :: (Char -> Bool) -> ByteString -> ByteString

-- | <a>dropWhile</a> <tt>p xs</tt> returns the suffix remaining after
gr<a>takeWhile</a> <tt>p xs</tt>.
dropWhile :: (Char -> Bool) -> ByteString -> ByteString

-- | <a>span</a> <tt>p xs</tt> breaks the ByteString into two segments. It
gris equivalent to <tt>(<a>takeWhile</a> p xs, <a>dropWhile</a> p
grxs)</tt>
span :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <a>break</a> <tt>p</tt> is equivalent to <tt><a>span</a> (<a>not</a> .
grp)</tt>.
break :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)

-- | The <a>group</a> function takes a ByteString and returns a list of
grByteStrings such that the concatenation of the result is equal to the
grargument. Moreover, each sublist in the result contains only equal
grelements. For example,
gr
gr<pre>
grgroup "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
gr</pre>
gr
grIt is a special case of <a>groupBy</a>, which allows the programmer to
grsupply their own equality test.
group :: ByteString -> [ByteString]

-- | The <a>groupBy</a> function is the non-overloaded version of
gr<a>group</a>.
groupBy :: (Char -> Char -> Bool) -> ByteString -> [ByteString]

-- | <i>O(n)</i> Return all initial segments of the given
gr<a>ByteString</a>, shortest first.
inits :: ByteString -> [ByteString]

-- | <i>O(n)</i> Return all final segments of the given <a>ByteString</a>,
grlongest first.
tails :: ByteString -> [ByteString]

-- | <i>O(n)</i> The <a>stripPrefix</a> function takes two ByteStrings and
grreturns <a>Just</a> the remainder of the second iff the first is its
grprefix, and otherwise <a>Nothing</a>.
stripPrefix :: ByteString -> ByteString -> Maybe ByteString

-- | <i>O(n)</i> The <a>stripSuffix</a> function takes two ByteStrings and
grreturns <a>Just</a> the remainder of the second iff the first is its
grsuffix, and otherwise <a>Nothing</a>.
stripSuffix :: ByteString -> ByteString -> Maybe ByteString

-- | <i>O(n)</i> Break a <a>ByteString</a> into pieces separated by the
grbyte argument, consuming the delimiter. I.e.
gr
gr<pre>
grsplit '\n' "a\nb\nd\ne" == ["a","b","d","e"]
grsplit 'a'  "aXaXaXa"    == ["","X","X","X"]
grsplit 'x'  "x"          == ["",""]
gr</pre>
gr
grand
gr
gr<pre>
grintercalate [c] . split c == id
grsplit == splitWith . (==)
gr</pre>
gr
grAs for all splitting functions in this library, this function does not
grcopy the substrings, it just constructs new <tt>ByteStrings</tt> that
grare slices of the original.
split :: Char -> ByteString -> [ByteString]

-- | <i>O(n)</i> Splits a <a>ByteString</a> into components delimited by
grseparators, where the predicate returns True for a separator element.
grThe resulting components do not contain the separators. Two adjacent
grseparators result in an empty component in the output. eg.
gr
gr<pre>
grsplitWith (=='a') "aabbaca" == ["","","bb","c",""]
gr</pre>
splitWith :: (Char -> Bool) -> ByteString -> [ByteString]

-- | <a>lines</a> breaks a ByteString up into a list of ByteStrings at
grnewline Chars. The resulting strings do not contain newlines.
gr
grAs of bytestring 0.9.0.3, this function is stricter than its list
grcousin.
lines :: ByteString -> [ByteString]

-- | <a>words</a> breaks a ByteString up into a list of words, which were
grdelimited by Chars representing white space. And
gr
gr<pre>
grtokens isSpace = words
gr</pre>
words :: ByteString -> [ByteString]

-- | <a>unlines</a> is an inverse operation to <a>lines</a>. It joins
grlines, after appending a terminating newline to each.
unlines :: [ByteString] -> ByteString

-- | The <a>unwords</a> function is analogous to the <a>unlines</a>
grfunction, on words.
unwords :: [ByteString] -> ByteString

-- | <i>O(n)</i> The <a>isPrefixOf</a> function takes two ByteStrings and
grreturns <a>True</a> iff the first is a prefix of the second.
isPrefixOf :: ByteString -> ByteString -> Bool

-- | <i>O(n)</i> The <a>isSuffixOf</a> function takes two ByteStrings and
grreturns <a>True</a> iff the first is a suffix of the second.
gr
grThe following holds:
gr
gr<pre>
grisSuffixOf x y == reverse x `isPrefixOf` reverse y
gr</pre>
isSuffixOf :: ByteString -> ByteString -> Bool

-- | <i>O(n)</i> <a>elem</a> is the <a>ByteString</a> membership predicate.
grThis implementation uses <tt>memchr(3)</tt>.
elem :: Char -> ByteString -> Bool

-- | <i>O(n)</i> <a>notElem</a> is the inverse of <a>elem</a>
notElem :: Char -> ByteString -> Bool

-- | <i>O(n)</i> The <a>find</a> function takes a predicate and a
grByteString, and returns the first element in matching the predicate,
gror <a>Nothing</a> if there is no such element.
find :: (Char -> Bool) -> ByteString -> Maybe Char

-- | <i>O(n)</i> <a>filter</a>, applied to a predicate and a ByteString,
grreturns a ByteString containing those characters that satisfy the
grpredicate.
filter :: (Char -> Bool) -> ByteString -> ByteString

-- | <i>O(1)</i> <a>ByteString</a> index (subscript) operator, starting
grfrom 0.
index :: ByteString -> Int64 -> Char

-- | <i>O(n)</i> The <a>elemIndex</a> function returns the index of the
grfirst element in the given <a>ByteString</a> which is equal (by
grmemchr) to the query element, or <a>Nothing</a> if there is no such
grelement.
elemIndex :: Char -> ByteString -> Maybe Int64

-- | <i>O(n)</i> The <a>elemIndices</a> function extends <a>elemIndex</a>,
grby returning the indices of all elements equal to the query element,
grin ascending order.
elemIndices :: Char -> ByteString -> [Int64]

-- | The <a>findIndex</a> function takes a predicate and a
gr<a>ByteString</a> and returns the index of the first element in the
grByteString satisfying the predicate.
findIndex :: (Char -> Bool) -> ByteString -> Maybe Int64

-- | The <a>findIndices</a> function extends <a>findIndex</a>, by returning
grthe indices of all elements satisfying the predicate, in ascending
grorder.
findIndices :: (Char -> Bool) -> ByteString -> [Int64]

-- | count returns the number of times its argument appears in the
grByteString
gr
gr<pre>
grcount      == length . elemIndices
grcount '\n' == length . lines
gr</pre>
gr
grBut more efficiently than using length on the intermediate list.
count :: Char -> ByteString -> Int64

-- | <i>O(n)</i> <a>zip</a> takes two ByteStrings and returns a list of
grcorresponding pairs of Chars. If one input ByteString is short, excess
grelements of the longer ByteString are discarded. This is equivalent to
gra pair of <a>unpack</a> operations, and so space usage may be large
grfor multi-megabyte ByteStrings
zip :: ByteString -> ByteString -> [(Char, Char)]

-- | <a>zipWith</a> generalises <a>zip</a> by zipping with the function
grgiven as the first argument, instead of a tupling function. For
grexample, <tt><a>zipWith</a> (+)</tt> is applied to two ByteStrings to
grproduce the list of corresponding sums.
zipWith :: (Char -> Char -> a) -> ByteString -> ByteString -> [a]

-- | <i>O(n)</i> Make a copy of the <a>ByteString</a> with its own storage.
grThis is mainly useful to allow the rest of the data pointed to by the
gr<a>ByteString</a> to be garbage collected, for example if a large
grstring has been read in, and only a small part of it is needed in the
grrest of the program.
copy :: ByteString -> ByteString

-- | readInt reads an Int from the beginning of the ByteString. If there is
grno integer at the beginning of the string, it returns Nothing,
grotherwise it just returns the int read, and the rest of the string.
readInt :: ByteString -> Maybe (Int, ByteString)

-- | readInteger reads an Integer from the beginning of the ByteString. If
grthere is no integer at the beginning of the string, it returns
grNothing, otherwise it just returns the int read, and the rest of the
grstring.
readInteger :: ByteString -> Maybe (Integer, ByteString)

-- | getContents. Equivalent to hGetContents stdin. Will read <i>lazily</i>
getContents :: IO ByteString

-- | Write a ByteString to stdout
putStr :: ByteString -> IO ()

-- | Write a ByteString to stdout, appending a newline byte
putStrLn :: ByteString -> IO ()

-- | The interact function takes a function of type <tt>ByteString -&gt;
grByteString</tt> as its argument. The entire input from the standard
grinput device is passed to this function as its argument, and the
grresulting string is output on the standard output device.
interact :: (ByteString -> ByteString) -> IO ()

-- | Read an entire file <i>lazily</i> into a <a>ByteString</a>. The Handle
grwill be held open until EOF is encountered.
readFile :: FilePath -> IO ByteString

-- | Write a <a>ByteString</a> to a file.
writeFile :: FilePath -> ByteString -> IO ()

-- | Append a <a>ByteString</a> to a file.
appendFile :: FilePath -> ByteString -> IO ()

-- | Read entire handle contents <i>lazily</i> into a <a>ByteString</a>.
grChunks are read on demand, using the default chunk size.
gr
grOnce EOF is encountered, the Handle is closed.
gr
grNote: the <a>Handle</a> should be placed in binary mode with
gr<a>hSetBinaryMode</a> for <a>hGetContents</a> to work correctly.
hGetContents :: Handle -> IO ByteString

-- | Read <tt>n</tt> bytes into a <a>ByteString</a>, directly from the
grspecified <a>Handle</a>.
hGet :: Handle -> Int -> IO ByteString

-- | hGetNonBlocking is similar to <a>hGet</a>, except that it will never
grblock waiting for data to become available, instead it returns only
grwhatever data is available. If there is no data available to be read,
gr<a>hGetNonBlocking</a> returns <a>empty</a>.
gr
grNote: on Windows and with Haskell implementation other than GHC, this
grfunction does not work correctly; it behaves identically to
gr<a>hGet</a>.
hGetNonBlocking :: Handle -> Int -> IO ByteString

-- | Outputs a <a>ByteString</a> to the specified <a>Handle</a>. The chunks
grwill be written one at a time. Other threads might write to the
gr<a>Handle</a> between the writes, and hence <a>hPut</a> alone might
grnot be suitable for concurrent writes.
hPut :: Handle -> ByteString -> IO ()

-- | Similar to <a>hPut</a> except that it will never block. Instead it
grreturns any tail that did not get written. This tail may be
gr<a>empty</a> in the case that the whole string was written, or the
grwhole original string if nothing was written. Partial writes are also
grpossible.
gr
grNote: on Windows and with Haskell implementation other than GHC, this
grfunction does not work correctly; it behaves identically to
gr<a>hPut</a>.
hPutNonBlocking :: Handle -> ByteString -> IO ByteString

-- | A synonym for <tt>hPut</tt>, for compatibility
hPutStr :: Handle -> ByteString -> IO ()

-- | Write a ByteString to a handle, appending a newline byte
hPutStrLn :: Handle -> ByteString -> IO ()


-- | Manipulate <a>ByteString</a>s using <a>Char</a> operations. All Chars
grwill be truncated to 8 bits. It can be expected that these functions
grwill run at identical speeds to their <a>Word8</a> equivalents in
gr<a>Data.ByteString</a>.
gr
grMore specifically these byte strings are taken to be in the subset of
grUnicode covered by code points 0-255. This covers Unicode Basic Latin,
grLatin-1 Supplement and C0+C1 Controls.
gr
grSee:
gr
gr<ul>
gr<li><a>http://www.unicode.org/charts/</a></li>
gr<li><a>http://www.unicode.org/charts/PDF/U0000.pdf</a></li>
gr<li><a>http://www.unicode.org/charts/PDF/U0080.pdf</a></li>
gr</ul>
gr
grThis module is intended to be imported <tt>qualified</tt>, to avoid
grname clashes with <a>Prelude</a> functions. eg.
gr
gr<pre>
grimport qualified Data.ByteString.Char8 as C
gr</pre>
gr
grThe Char8 interface to bytestrings provides an instance of IsString
grfor the ByteString type, enabling you to use string literals, and have
grthem implicitly packed to ByteStrings. Use <tt>{-# LANGUAGE
grOverloadedStrings #-}</tt> to enable this.
module Data.ByteString.Char8

-- | A space-efficient representation of a <a>Word8</a> vector, supporting
grmany efficient operations.
gr
grA <a>ByteString</a> contains 8-bit bytes, or by using the operations
grfrom <a>Data.ByteString.Char8</a> it can be interpreted as containing
gr8-bit characters.
data ByteString

-- | <i>O(1)</i> The empty <a>ByteString</a>
empty :: ByteString

-- | <i>O(1)</i> Convert a <a>Char</a> into a <a>ByteString</a>
singleton :: Char -> ByteString

-- | <i>O(n)</i> Convert a <a>String</a> into a <a>ByteString</a>
gr
grFor applications with large numbers of string literals, pack can be a
grbottleneck.
pack :: String -> ByteString

-- | <i>O(n)</i> Converts a <a>ByteString</a> to a <a>String</a>.
unpack :: ByteString -> [Char]

-- | <i>O(n)</i> <a>cons</a> is analogous to (:) for lists, but of
grdifferent complexity, as it requires a memcpy.
cons :: Char -> ByteString -> ByteString
infixr 5 `cons`

-- | <i>O(n)</i> Append a Char to the end of a <a>ByteString</a>. Similar
grto <a>cons</a>, this function performs a memcpy.
snoc :: ByteString -> Char -> ByteString
infixl 5 `snoc`

-- | <i>O(n)</i> Append two ByteStrings
append :: ByteString -> ByteString -> ByteString

-- | <i>O(1)</i> Extract the first element of a ByteString, which must be
grnon-empty.
head :: ByteString -> Char

-- | <i>O(1)</i> Extract the head and tail of a ByteString, returning
grNothing if it is empty.
uncons :: ByteString -> Maybe (Char, ByteString)

-- | <i>O(1)</i> Extract the <a>init</a> and <a>last</a> of a ByteString,
grreturning Nothing if it is empty.
unsnoc :: ByteString -> Maybe (ByteString, Char)

-- | <i>O(1)</i> Extract the last element of a packed string, which must be
grnon-empty.
last :: ByteString -> Char

-- | <i>O(1)</i> Extract the elements after the head of a ByteString, which
grmust be non-empty. An exception will be thrown in the case of an empty
grByteString.
tail :: ByteString -> ByteString

-- | <i>O(1)</i> Return all the elements of a <a>ByteString</a> except the
grlast one. An exception will be thrown in the case of an empty
grByteString.
init :: ByteString -> ByteString

-- | <i>O(1)</i> Test whether a ByteString is empty.
null :: ByteString -> Bool

-- | <i>O(1)</i> <a>length</a> returns the length of a ByteString as an
gr<a>Int</a>.
length :: ByteString -> Int

-- | <i>O(n)</i> <a>map</a> <tt>f xs</tt> is the ByteString obtained by
grapplying <tt>f</tt> to each element of <tt>xs</tt>
map :: (Char -> Char) -> ByteString -> ByteString

-- | <i>O(n)</i> <a>reverse</a> <tt>xs</tt> efficiently returns the
grelements of <tt>xs</tt> in reverse order.
reverse :: ByteString -> ByteString

-- | <i>O(n)</i> The <a>intersperse</a> function takes a Char and a
gr<a>ByteString</a> and `intersperses' that Char between the elements of
grthe <a>ByteString</a>. It is analogous to the intersperse function on
grLists.
intersperse :: Char -> ByteString -> ByteString

-- | <i>O(n)</i> The <a>intercalate</a> function takes a <a>ByteString</a>
grand a list of <a>ByteString</a>s and concatenates the list after
grinterspersing the first argument between each element of the list.
intercalate :: ByteString -> [ByteString] -> ByteString

-- | The <a>transpose</a> function transposes the rows and columns of its
gr<a>ByteString</a> argument.
transpose :: [ByteString] -> [ByteString]

-- | <a>foldl</a>, applied to a binary operator, a starting value
gr(typically the left-identity of the operator), and a ByteString,
grreduces the ByteString using the binary operator, from left to right.
foldl :: (a -> Char -> a) -> a -> ByteString -> a

-- | 'foldl\'' is like foldl, but strict in the accumulator.
foldl' :: (a -> Char -> a) -> a -> ByteString -> a

-- | <a>foldl1</a> is a variant of <a>foldl</a> that has no starting value
grargument, and thus must be applied to non-empty <tt>ByteStrings</tt>.
foldl1 :: (Char -> Char -> Char) -> ByteString -> Char

-- | A strict version of <a>foldl1</a>
foldl1' :: (Char -> Char -> Char) -> ByteString -> Char

-- | <a>foldr</a>, applied to a binary operator, a starting value
gr(typically the right-identity of the operator), and a packed string,
grreduces the packed string using the binary operator, from right to
grleft.
foldr :: (Char -> a -> a) -> a -> ByteString -> a

-- | 'foldr\'' is a strict variant of foldr
foldr' :: (Char -> a -> a) -> a -> ByteString -> a

-- | <a>foldr1</a> is a variant of <a>foldr</a> that has no starting value
grargument, and thus must be applied to non-empty <a>ByteString</a>s
foldr1 :: (Char -> Char -> Char) -> ByteString -> Char

-- | A strict variant of foldr1
foldr1' :: (Char -> Char -> Char) -> ByteString -> Char

-- | <i>O(n)</i> Concatenate a list of ByteStrings.
concat :: [ByteString] -> ByteString

-- | Map a function over a <a>ByteString</a> and concatenate the results
concatMap :: (Char -> ByteString) -> ByteString -> ByteString

-- | Applied to a predicate and a ByteString, <a>any</a> determines if any
grelement of the <a>ByteString</a> satisfies the predicate.
any :: (Char -> Bool) -> ByteString -> Bool

-- | Applied to a predicate and a <a>ByteString</a>, <a>all</a> determines
grif all elements of the <a>ByteString</a> satisfy the predicate.
all :: (Char -> Bool) -> ByteString -> Bool

-- | <a>maximum</a> returns the maximum value from a <a>ByteString</a>
maximum :: ByteString -> Char

-- | <a>minimum</a> returns the minimum value from a <a>ByteString</a>
minimum :: ByteString -> Char

-- | <a>scanl</a> is similar to <a>foldl</a>, but returns a list of
grsuccessive reduced values from the left:
gr
gr<pre>
grscanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
gr</pre>
gr
grNote that
gr
gr<pre>
grlast (scanl f z xs) == foldl f z xs.
gr</pre>
scanl :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString

-- | <a>scanl1</a> is a variant of <a>scanl</a> that has no starting value
grargument:
gr
gr<pre>
grscanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
gr</pre>
scanl1 :: (Char -> Char -> Char) -> ByteString -> ByteString

-- | scanr is the right-to-left dual of scanl.
scanr :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString

-- | <a>scanr1</a> is a variant of <a>scanr</a> that has no starting value
grargument.
scanr1 :: (Char -> Char -> Char) -> ByteString -> ByteString

-- | The <a>mapAccumL</a> function behaves like a combination of <a>map</a>
grand <a>foldl</a>; it applies a function to each element of a
grByteString, passing an accumulating parameter from left to right, and
grreturning a final value of this accumulator together with the new
grlist.
mapAccumL :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)

-- | The <a>mapAccumR</a> function behaves like a combination of <a>map</a>
grand <a>foldr</a>; it applies a function to each element of a
grByteString, passing an accumulating parameter from right to left, and
grreturning a final value of this accumulator together with the new
grByteString.
mapAccumR :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)

-- | <i>O(n)</i> <a>replicate</a> <tt>n x</tt> is a ByteString of length
gr<tt>n</tt> with <tt>x</tt> the value of every element. The following
grholds:
gr
gr<pre>
grreplicate w c = unfoldr w (\u -&gt; Just (u,u)) c
gr</pre>
gr
grThis implemenation uses <tt>memset(3)</tt>
replicate :: Int -> Char -> ByteString

-- | <i>O(n)</i>, where <i>n</i> is the length of the result. The
gr<a>unfoldr</a> function is analogous to the List 'unfoldr'.
gr<a>unfoldr</a> builds a ByteString from a seed value. The function
grtakes the element and returns <a>Nothing</a> if it is done producing
grthe ByteString or returns <a>Just</a> <tt>(a,b)</tt>, in which case,
gr<tt>a</tt> is the next character in the string, and <tt>b</tt> is the
grseed value for further production.
gr
grExamples:
gr
gr<pre>
grunfoldr (\x -&gt; if x &lt;= '9' then Just (x, succ x) else Nothing) '0' == "0123456789"
gr</pre>
unfoldr :: (a -> Maybe (Char, a)) -> a -> ByteString

-- | <i>O(n)</i> Like <a>unfoldr</a>, <a>unfoldrN</a> builds a ByteString
grfrom a seed value. However, the length of the result is limited by the
grfirst argument to <a>unfoldrN</a>. This function is more efficient
grthan <a>unfoldr</a> when the maximum length of the result is known.
gr
grThe following equation relates <a>unfoldrN</a> and <a>unfoldr</a>:
gr
gr<pre>
grunfoldrN n f s == take n (unfoldr f s)
gr</pre>
unfoldrN :: Int -> (a -> Maybe (Char, a)) -> a -> (ByteString, Maybe a)

-- | <i>O(1)</i> <a>take</a> <tt>n</tt>, applied to a ByteString
gr<tt>xs</tt>, returns the prefix of <tt>xs</tt> of length <tt>n</tt>,
gror <tt>xs</tt> itself if <tt>n &gt; <a>length</a> xs</tt>.
take :: Int -> ByteString -> ByteString

-- | <i>O(1)</i> <a>drop</a> <tt>n xs</tt> returns the suffix of
gr<tt>xs</tt> after the first <tt>n</tt> elements, or <tt>[]</tt> if
gr<tt>n &gt; <a>length</a> xs</tt>.
drop :: Int -> ByteString -> ByteString

-- | <i>O(1)</i> <a>splitAt</a> <tt>n xs</tt> is equivalent to
gr<tt>(<a>take</a> n xs, <a>drop</a> n xs)</tt>.
splitAt :: Int -> ByteString -> (ByteString, ByteString)

-- | <a>takeWhile</a>, applied to a predicate <tt>p</tt> and a ByteString
gr<tt>xs</tt>, returns the longest prefix (possibly empty) of
gr<tt>xs</tt> of elements that satisfy <tt>p</tt>.
takeWhile :: (Char -> Bool) -> ByteString -> ByteString

-- | <a>dropWhile</a> <tt>p xs</tt> returns the suffix remaining after
gr<a>takeWhile</a> <tt>p xs</tt>.
dropWhile :: (Char -> Bool) -> ByteString -> ByteString

-- | <a>span</a> <tt>p xs</tt> breaks the ByteString into two segments. It
gris equivalent to <tt>(<a>takeWhile</a> p xs, <a>dropWhile</a> p
grxs)</tt>
span :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <a>spanEnd</a> behaves like <a>span</a> but from the end of the
gr<a>ByteString</a>. We have
gr
gr<pre>
grspanEnd (not.isSpace) "x y z" == ("x y ","z")
gr</pre>
gr
grand
gr
gr<pre>
grspanEnd (not . isSpace) ps
gr   ==
grlet (x,y) = span (not.isSpace) (reverse ps) in (reverse y, reverse x)
gr</pre>
spanEnd :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <a>break</a> <tt>p</tt> is equivalent to <tt><a>span</a> (<a>not</a> .
grp)</tt>.
break :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)

-- | <a>breakEnd</a> behaves like <a>break</a> but from the end of the
gr<a>ByteString</a>
gr
grbreakEnd p == spanEnd (not.p)
breakEnd :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)

-- | The <a>group</a> function takes a ByteString and returns a list of
grByteStrings such that the concatenation of the result is equal to the
grargument. Moreover, each sublist in the result contains only equal
grelements. For example,
gr
gr<pre>
grgroup "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
gr</pre>
gr
grIt is a special case of <a>groupBy</a>, which allows the programmer to
grsupply their own equality test. It is about 40% faster than <i>groupBy
gr(==)</i>
group :: ByteString -> [ByteString]

-- | The <a>groupBy</a> function is the non-overloaded version of
gr<a>group</a>.
groupBy :: (Char -> Char -> Bool) -> ByteString -> [ByteString]

-- | <i>O(n)</i> Return all initial segments of the given
gr<a>ByteString</a>, shortest first.
inits :: ByteString -> [ByteString]

-- | <i>O(n)</i> Return all final segments of the given <a>ByteString</a>,
grlongest first.
tails :: ByteString -> [ByteString]

-- | <i>O(n)</i> The <a>stripPrefix</a> function takes two ByteStrings and
grreturns <a>Just</a> the remainder of the second iff the first is its
grprefix, and otherwise <a>Nothing</a>.
stripPrefix :: ByteString -> ByteString -> Maybe ByteString

-- | <i>O(n)</i> The <a>stripSuffix</a> function takes two ByteStrings and
grreturns <a>Just</a> the remainder of the second iff the first is its
grsuffix, and otherwise <a>Nothing</a>.
stripSuffix :: ByteString -> ByteString -> Maybe ByteString

-- | <i>O(n)</i> Break a <a>ByteString</a> into pieces separated by the
grbyte argument, consuming the delimiter. I.e.
gr
gr<pre>
grsplit '\n' "a\nb\nd\ne" == ["a","b","d","e"]
grsplit 'a'  "aXaXaXa"    == ["","X","X","X",""]
grsplit 'x'  "x"          == ["",""]
gr</pre>
gr
grand
gr
gr<pre>
grintercalate [c] . split c == id
grsplit == splitWith . (==)
gr</pre>
gr
grAs for all splitting functions in this library, this function does not
grcopy the substrings, it just constructs new <tt>ByteStrings</tt> that
grare slices of the original.
split :: Char -> ByteString -> [ByteString]

-- | <i>O(n)</i> Splits a <a>ByteString</a> into components delimited by
grseparators, where the predicate returns True for a separator element.
grThe resulting components do not contain the separators. Two adjacent
grseparators result in an empty component in the output. eg.
gr
gr<pre>
grsplitWith (=='a') "aabbaca" == ["","","bb","c",""]
gr</pre>
splitWith :: (Char -> Bool) -> ByteString -> [ByteString]

-- | <a>lines</a> breaks a ByteString up into a list of ByteStrings at
grnewline Chars. The resulting strings do not contain newlines.
lines :: ByteString -> [ByteString]

-- | <a>words</a> breaks a ByteString up into a list of words, which were
grdelimited by Chars representing white space.
words :: ByteString -> [ByteString]

-- | <a>unlines</a> is an inverse operation to <a>lines</a>. It joins
grlines, after appending a terminating newline to each.
unlines :: [ByteString] -> ByteString

-- | The <a>unwords</a> function is analogous to the <a>unlines</a>
grfunction, on words.
unwords :: [ByteString] -> ByteString

-- | <i>O(n)</i> The <a>isPrefixOf</a> function takes two ByteStrings and
grreturns <a>True</a> if the first is a prefix of the second.
isPrefixOf :: ByteString -> ByteString -> Bool

-- | <i>O(n)</i> The <a>isSuffixOf</a> function takes two ByteStrings and
grreturns <a>True</a> iff the first is a suffix of the second.
gr
grThe following holds:
gr
gr<pre>
grisSuffixOf x y == reverse x `isPrefixOf` reverse y
gr</pre>
gr
grHowever, the real implemenation uses memcmp to compare the end of the
grstring only, with no reverse required..
isSuffixOf :: ByteString -> ByteString -> Bool

-- | Check whether one string is a substring of another. <tt>isInfixOf p
grs</tt> is equivalent to <tt>not (null (findSubstrings p s))</tt>.
isInfixOf :: ByteString -> ByteString -> Bool

-- | Break a string on a substring, returning a pair of the part of the
grstring prior to the match, and the rest of the string.
gr
grThe following relationships hold:
gr
gr<pre>
grbreak (== c) l == breakSubstring (singleton c) l
gr</pre>
gr
grand:
gr
gr<pre>
grfindSubstring s l ==
gr   if null s then Just 0
gr             else case breakSubstring s l of
gr                      (x,y) | null y    -&gt; Nothing
gr                            | otherwise -&gt; Just (length x)
gr</pre>
gr
grFor example, to tokenise a string, dropping delimiters:
gr
gr<pre>
grtokenise x y = h : if null t then [] else tokenise x (drop (length x) t)
gr    where (h,t) = breakSubstring x y
gr</pre>
gr
grTo skip to the first occurence of a string:
gr
gr<pre>
grsnd (breakSubstring x y)
gr</pre>
gr
grTo take the parts of a string before a delimiter:
gr
gr<pre>
grfst (breakSubstring x y)
gr</pre>
gr
grNote that calling `breakSubstring x` does some preprocessing work, so
gryou should avoid unnecessarily duplicating breakSubstring calls with
grthe same pattern.
breakSubstring :: ByteString -> ByteString -> (ByteString, ByteString)

-- | Get the first index of a substring in another string, or
gr<a>Nothing</a> if the string is not found. <tt>findSubstring p s</tt>
gris equivalent to <tt>listToMaybe (findSubstrings p s)</tt>.

-- | <i>Deprecated: findSubstring is deprecated in favour of
grbreakSubstring.</i>
findSubstring :: ByteString -> ByteString -> Maybe Int

-- | Find the indexes of all (possibly overlapping) occurances of a
grsubstring in a string.

-- | <i>Deprecated: findSubstrings is deprecated in favour of
grbreakSubstring.</i>
findSubstrings :: ByteString -> ByteString -> [Int]

-- | <i>O(n)</i> <a>elem</a> is the <a>ByteString</a> membership predicate.
grThis implementation uses <tt>memchr(3)</tt>.
elem :: Char -> ByteString -> Bool

-- | <i>O(n)</i> <a>notElem</a> is the inverse of <a>elem</a>
notElem :: Char -> ByteString -> Bool

-- | <i>O(n)</i> The <a>find</a> function takes a predicate and a
grByteString, and returns the first element in matching the predicate,
gror <a>Nothing</a> if there is no such element.
find :: (Char -> Bool) -> ByteString -> Maybe Char

-- | <i>O(n)</i> <a>filter</a>, applied to a predicate and a ByteString,
grreturns a ByteString containing those characters that satisfy the
grpredicate.
filter :: (Char -> Bool) -> ByteString -> ByteString

-- | <i>O(1)</i> <a>ByteString</a> index (subscript) operator, starting
grfrom 0.
index :: ByteString -> Int -> Char

-- | <i>O(n)</i> The <a>elemIndex</a> function returns the index of the
grfirst element in the given <a>ByteString</a> which is equal (by
grmemchr) to the query element, or <a>Nothing</a> if there is no such
grelement.
elemIndex :: Char -> ByteString -> Maybe Int

-- | <i>O(n)</i> The <a>elemIndices</a> function extends <a>elemIndex</a>,
grby returning the indices of all elements equal to the query element,
grin ascending order.
elemIndices :: Char -> ByteString -> [Int]

-- | <i>O(n)</i> The <a>elemIndexEnd</a> function returns the last index of
grthe element in the given <a>ByteString</a> which is equal to the query
grelement, or <a>Nothing</a> if there is no such element. The following
grholds:
gr
gr<pre>
grelemIndexEnd c xs ==
gr(-) (length xs - 1) `fmap` elemIndex c (reverse xs)
gr</pre>
elemIndexEnd :: Char -> ByteString -> Maybe Int

-- | The <a>findIndex</a> function takes a predicate and a
gr<a>ByteString</a> and returns the index of the first element in the
grByteString satisfying the predicate.
findIndex :: (Char -> Bool) -> ByteString -> Maybe Int

-- | The <a>findIndices</a> function extends <a>findIndex</a>, by returning
grthe indices of all elements satisfying the predicate, in ascending
grorder.
findIndices :: (Char -> Bool) -> ByteString -> [Int]

-- | count returns the number of times its argument appears in the
grByteString
gr
gr<pre>
grcount = length . elemIndices
gr</pre>
gr
grAlso
gr
gr<pre>
grcount '\n' == length . lines
gr</pre>
gr
grBut more efficiently than using length on the intermediate list.
count :: Char -> ByteString -> Int

-- | <i>O(n)</i> <a>zip</a> takes two ByteStrings and returns a list of
grcorresponding pairs of Chars. If one input ByteString is short, excess
grelements of the longer ByteString are discarded. This is equivalent to
gra pair of <a>unpack</a> operations, and so space usage may be large
grfor multi-megabyte ByteStrings
zip :: ByteString -> ByteString -> [(Char, Char)]

-- | <a>zipWith</a> generalises <a>zip</a> by zipping with the function
grgiven as the first argument, instead of a tupling function. For
grexample, <tt><a>zipWith</a> (+)</tt> is applied to two ByteStrings to
grproduce the list of corresponding sums.
zipWith :: (Char -> Char -> a) -> ByteString -> ByteString -> [a]

-- | <a>unzip</a> transforms a list of pairs of Chars into a pair of
grByteStrings. Note that this performs two <a>pack</a> operations.
unzip :: [(Char, Char)] -> (ByteString, ByteString)

-- | <i>O(n)</i> Sort a ByteString efficiently, using counting sort.
sort :: ByteString -> ByteString

-- | readInt reads an Int from the beginning of the ByteString. If there is
grno integer at the beginning of the string, it returns Nothing,
grotherwise it just returns the int read, and the rest of the string.
readInt :: ByteString -> Maybe (Int, ByteString)

-- | readInteger reads an Integer from the beginning of the ByteString. If
grthere is no integer at the beginning of the string, it returns
grNothing, otherwise it just returns the int read, and the rest of the
grstring.
readInteger :: ByteString -> Maybe (Integer, ByteString)

-- | <i>O(n)</i> Make a copy of the <a>ByteString</a> with its own storage.
grThis is mainly useful to allow the rest of the data pointed to by the
gr<a>ByteString</a> to be garbage collected, for example if a large
grstring has been read in, and only a small part of it is needed in the
grrest of the program.
copy :: ByteString -> ByteString

-- | <i>O(n).</i> Construct a new <tt>ByteString</tt> from a
gr<tt>CString</tt>. The resulting <tt>ByteString</tt> is an immutable
grcopy of the original <tt>CString</tt>, and is managed on the Haskell
grheap. The original <tt>CString</tt> must be null terminated.
packCString :: CString -> IO ByteString

-- | <i>O(n).</i> Construct a new <tt>ByteString</tt> from a
gr<tt>CStringLen</tt>. The resulting <tt>ByteString</tt> is an immutable
grcopy of the original <tt>CStringLen</tt>. The <tt>ByteString</tt> is a
grnormal Haskell value and will be managed on the Haskell heap.
packCStringLen :: CStringLen -> IO ByteString

-- | <i>O(n) construction</i> Use a <tt>ByteString</tt> with a function
grrequiring a null-terminated <tt>CString</tt>. The <tt>CString</tt> is
gra copy and will be freed automatically; it must not be stored or used
grafter the subcomputation finishes.
useAsCString :: ByteString -> (CString -> IO a) -> IO a

-- | <i>O(n) construction</i> Use a <tt>ByteString</tt> with a function
grrequiring a <tt>CStringLen</tt>. As for <tt>useAsCString</tt> this
grfunction makes a copy of the original <tt>ByteString</tt>. It must not
grbe stored or used after the subcomputation finishes.
useAsCStringLen :: ByteString -> (CStringLen -> IO a) -> IO a

-- | Read a line from stdin.
getLine :: IO ByteString

-- | getContents. Read stdin strictly. Equivalent to hGetContents stdin The
gr<a>Handle</a> is closed after the contents have been read.
getContents :: IO ByteString

-- | Write a ByteString to stdout
putStr :: ByteString -> IO ()

-- | Write a ByteString to stdout, appending a newline byte
putStrLn :: ByteString -> IO ()

-- | The interact function takes a function of type <tt>ByteString -&gt;
grByteString</tt> as its argument. The entire input from the standard
grinput device is passed to this function as its argument, and the
grresulting string is output on the standard output device.
interact :: (ByteString -> ByteString) -> IO ()

-- | Read an entire file strictly into a <a>ByteString</a>.
readFile :: FilePath -> IO ByteString

-- | Write a <a>ByteString</a> to a file.
writeFile :: FilePath -> ByteString -> IO ()

-- | Append a <a>ByteString</a> to a file.
appendFile :: FilePath -> ByteString -> IO ()

-- | Read a line from a handle
hGetLine :: Handle -> IO ByteString

-- | Read a handle's entire contents strictly into a <a>ByteString</a>.
gr
grThis function reads chunks at a time, increasing the chunk size on
greach read. The final string is then realloced to the appropriate size.
grFor files &gt; half of available memory, this may lead to memory
grexhaustion. Consider using <a>readFile</a> in this case.
gr
grThe Handle is closed once the contents have been read, or if an
grexception is thrown.
hGetContents :: Handle -> IO ByteString

-- | Read a <a>ByteString</a> directly from the specified <a>Handle</a>.
grThis is far more efficient than reading the characters into a
gr<a>String</a> and then using <a>pack</a>. First argument is the Handle
grto read from, and the second is the number of bytes to read. It
grreturns the bytes read, up to n, or <a>empty</a> if EOF has been
grreached.
gr
gr<a>hGet</a> is implemented in terms of <a>hGetBuf</a>.
gr
grIf the handle is a pipe or socket, and the writing end is closed,
gr<a>hGet</a> will behave as if EOF was reached.
hGet :: Handle -> Int -> IO ByteString

-- | Like <a>hGet</a>, except that a shorter <a>ByteString</a> may be
grreturned if there are not enough bytes immediately available to
grsatisfy the whole request. <a>hGetSome</a> only blocks if there is no
grdata available, and EOF has not yet been reached.
hGetSome :: Handle -> Int -> IO ByteString

-- | hGetNonBlocking is similar to <a>hGet</a>, except that it will never
grblock waiting for data to become available, instead it returns only
grwhatever data is available. If there is no data available to be read,
gr<a>hGetNonBlocking</a> returns <a>empty</a>.
gr
grNote: on Windows and with Haskell implementation other than GHC, this
grfunction does not work correctly; it behaves identically to
gr<a>hGet</a>.
hGetNonBlocking :: Handle -> Int -> IO ByteString

-- | Outputs a <a>ByteString</a> to the specified <a>Handle</a>.
hPut :: Handle -> ByteString -> IO ()

-- | Similar to <a>hPut</a> except that it will never block. Instead it
grreturns any tail that did not get written. This tail may be
gr<a>empty</a> in the case that the whole string was written, or the
grwhole original string if nothing was written. Partial writes are also
grpossible.
gr
grNote: on Windows and with Haskell implementation other than GHC, this
grfunction does not work correctly; it behaves identically to
gr<a>hPut</a>.
hPutNonBlocking :: Handle -> ByteString -> IO ByteString

-- | A synonym for <tt>hPut</tt>, for compatibility
hPutStr :: Handle -> ByteString -> IO ()

-- | Write a ByteString to a handle, appending a newline byte
hPutStrLn :: Handle -> ByteString -> IO ()


-- | This module provides <a>Builder</a> <i>primitives</i>, which are lower
grlevel building blocks for constructing <a>Builder</a>s. You don't need
grto go down to this level but it can be slightly faster.
gr
grMorally, builder primitives are like functions <tt>a -&gt;
grBuilder</tt>, that is they take a value and encode it as a sequence of
grbytes, represented as a <a>Builder</a>. Of course their implementation
gris a bit more specialised.
gr
grBuilder primitives come in two forms: fixed-size and bounded-size.
gr
gr<ul>
gr<li><i>Fixed(-size) primitives</i> are builder primitives that always
grresult in a sequence of bytes of a fixed length. That is, the length
gris independent of the value that is encoded. An example of a fixed
grsize primitive is the big-endian encoding of a <a>Word64</a>, which
gralways results in exactly 8 bytes.</li>
gr<li><i>Bounded(-size) primitives</i> are builder primitives that
gralways result in a sequence of bytes that is no larger than a
grpredetermined bound. That is, the bound is independent of the value
grthat is encoded but the actual length will depend on the value. An
grexample for a bounded primitive is the UTF-8 encoding of a
gr<a>Char</a>, which can be 1,2,3 or 4 bytes long, so the bound is 4
grbytes.</li>
gr</ul>
gr
grNote that fixed primitives can be considered as a special case of
grbounded primitives, and we can lift from fixed to bounded.
gr
grBecause bounded primitives are the more general case, in this
grdocumentation we only refer to fixed size primitives where it matters
grthat the resulting sequence of bytes is of a fixed length. Otherwise,
grwe just refer to bounded size primitives.
gr
grThe purpose of using builder primitives is to improve the performance
grof <a>Builder</a>s. These improvements stem from making the two most
grcommon steps performed by a <a>Builder</a> more efficient. We explain
grthese two steps in turn.
gr
grThe first most common step is the concatenation of two
gr<a>Builder</a>s. Internally, concatenation corresponds to function
grcomposition. (Note that <a>Builder</a>s can be seen as
grdifference-lists of buffer-filling functions; cf.
gr<a>http://hackage.haskell.org/cgi-bin/hackage-scripts/package/dlist</a>.
gr) Function composition is a fast <i>O(1)</i> operation. However, we
grcan use bounded primitives to remove some of these function
grcompositions altogether, which is more efficient.
gr
grThe second most common step performed by a <a>Builder</a> is to fill a
grbuffer using a bounded primitives, which works as follows. The
gr<a>Builder</a> checks whether there is enough space left to execute
grthe bounded primitive. If there is, then the <a>Builder</a> executes
grthe bounded primitive and calls the next <a>Builder</a> with the
grupdated buffer. Otherwise, the <a>Builder</a> signals its driver that
grit requires a new buffer. This buffer must be at least as large as the
grbound of the primitive. We can use bounded primitives to reduce the
grnumber of buffer-free checks by fusing the buffer-free checks of
grconsecutive <a>Builder</a>s. We can also use bounded primitives to
grsimplify the control flow for signalling that a buffer is full by
grensuring that we check first that there is enough space left and only
grthen decide on how to encode a given value.
gr
grLet us illustrate these improvements on the CSV-table rendering
grexample from <a>Data.ByteString.Builder</a>. Its "hot code" is the
grrendering of a table's cells, which we implement as follows using only
grthe functions from the <a>Builder</a> API.
gr
gr<pre>
grimport <a>Data.ByteString.Builder</a> as B
gr
grrenderCell :: Cell -&gt; Builder
grrenderCell (StringC cs) = renderString cs
grrenderCell (IntC i)     = B.intDec i
gr
grrenderString :: String -&gt; Builder
grrenderString cs = B.charUtf8 '"' &lt;&gt; foldMap escape cs &lt;&gt; B.charUtf8 '"'
gr  where
gr    escape '\\' = B.charUtf8 '\\' &lt;&gt; B.charUtf8 '\\'
gr    escape '\"' = B.charUtf8 '\\' &lt;&gt; B.charUtf8 '\"'
gr    escape c    = B.charUtf8 c
gr</pre>
gr
grEfficient encoding of <a>Int</a>s as decimal numbers is performed by
gr<tt>intDec</tt>. Optimization potential exists for the escaping of
gr<a>String</a>s. The above implementation has two optimization
gropportunities. First, the buffer-free checks of the <a>Builder</a>s
grfor escaping double quotes and backslashes can be fused. Second, the
grconcatenations performed by <a>foldMap</a> can be eliminated. The
grfollowing implementation exploits these optimizations.
gr
gr<pre>
grimport qualified Data.ByteString.Builder.Prim  as P
grimport           Data.ByteString.Builder.Prim
gr                 ( <a>condB</a>, <a>liftFixedToBounded</a>, (<a>&gt;*&lt;</a>), (<a>&gt;$&lt;</a>) )
gr
grrenderString :: String -&gt; Builder
grrenderString cs =
gr    B.charUtf8 '"' &lt;&gt; E.<tt>encodeListWithB</tt> escape cs &lt;&gt; B.charUtf8 '"'
gr  where
gr    escape :: E.<a>BoundedPrim</a> Char
gr    escape =
gr      <a>condB</a> (== '\\') (fixed2 ('\\', '\\')) $
gr      <a>condB</a> (== '\"') (fixed2 ('\\', '\"')) $
gr      E.<a>charUtf8</a>
gr     
gr    {-# INLINE fixed2 #-}
gr    fixed2 x = <a>liftFixedToBounded</a> $ const x <a>&gt;$&lt;</a> E.<a>char7</a> <a>&gt;*&lt;</a> E.<a>char7</a>
gr</pre>
gr
grThe code should be mostly self-explanatory. The slightly awkward
grsyntax is because the combinators are written such that the size-bound
grof the resulting <a>BoundedPrim</a> can be computed at compile time.
grWe also explicitly inline the <tt>fixed2</tt> primitive, which encodes
gra fixed tuple of characters, to ensure that the bound computation
grhappens at compile time. When encoding the following list of
gr<a>String</a>s, the optimized implementation of <tt>renderString</tt>
gris two times faster.
gr
gr<pre>
grmaxiStrings :: [String]
grmaxiStrings = take 1000 $ cycle ["hello", "\"1\"", "λ-wörld"]
gr</pre>
gr
grMost of the performance gain stems from using
gr<a>primMapListBounded</a>, which encodes a list of values from
grleft-to-right with a <a>BoundedPrim</a>. It exploits the
gr<a>Builder</a> internals to avoid unnecessary function compositions
gr(i.e., concatenations). In the future, we might expect the compiler to
grperform the optimizations implemented in <a>primMapListBounded</a>.
grHowever, it seems that the code is currently to complicated for the
grcompiler to see through. Therefore, we provide the <a>BoundedPrim</a>
grescape hatch, which allows data structures to provide very efficient
grencoding traversals, like <a>primMapListBounded</a> for lists.
gr
grNote that <a>BoundedPrim</a>s are a bit verbose, but quite versatile.
grHere is an example of a <a>BoundedPrim</a> for combined HTML escaping
grand UTF-8 encoding. It exploits that the escaped character with the
grmaximal Unicode codepoint is '&gt;'.
gr
gr<pre>
gr{-# INLINE charUtf8HtmlEscaped #-}
grcharUtf8HtmlEscaped :: E.BoundedPrim Char
grcharUtf8HtmlEscaped =
gr    <a>condB</a> (&gt;  '&gt;' ) E.<a>charUtf8</a> $
gr    <a>condB</a> (== '&lt;' ) (fixed4 ('&amp;',('l',('t',';')))) $        -- &amp;lt;
gr    <a>condB</a> (== '&gt;' ) (fixed4 ('&amp;',('g',('t',';')))) $        -- &amp;gt;
gr    <a>condB</a> (== '&amp;' ) (fixed5 ('&amp;',('a',('m',('p',';'))))) $  -- &amp;amp;
gr    <a>condB</a> (== '"' ) (fixed5 ('&amp;',('#',('3',('4',';'))))) $  -- &amp;#34;
gr    <a>condB</a> (== '\'') (fixed5 ('&amp;',('#',('3',('9',';'))))) $  -- &amp;#39;
gr    (<a>liftFixedToBounded</a> E.<a>char7</a>)         -- fallback for <a>Char</a>s smaller than '&gt;'
gr  where
gr    {-# INLINE fixed4 #-}
gr    fixed4 x = <a>liftFixedToBounded</a> $ const x <a>&gt;$&lt;</a>
gr      E.char7 <a>&gt;*&lt;</a> E.char7 <a>&gt;*&lt;</a> E.char7 <a>&gt;*&lt;</a> E.char7
gr     
gr    {-# INLINE fixed5 #-}
gr    fixed5 x = <a>liftFixedToBounded</a> $ const x <a>&gt;$&lt;</a>
gr      E.char7 <a>&gt;*&lt;</a> E.char7 <a>&gt;*&lt;</a> E.char7 <a>&gt;*&lt;</a> E.char7 <a>&gt;*&lt;</a> E.char7
gr</pre>
gr
grThis module currently does not expose functions that require the
grspecial properties of fixed-size primitives. They are useful for
grprefixing <a>Builder</a>s with their size or for implementing chunked
grencodings. We will expose the corresponding functions in future
grreleases of this library.
module Data.ByteString.Builder.Prim

-- | A builder primitive that always results in sequence of bytes that is
grno longer than a pre-determined bound.
data BoundedPrim a

-- | The <a>BoundedPrim</a> that always results in the zero-length
grsequence.
emptyB :: BoundedPrim a

-- | A pairing/concatenation operator for builder primitives, both bounded
grand fixed size.
gr
grFor example,
gr
gr<pre>
grtoLazyByteString (primFixed (char7 &gt;*&lt; char7) ('x','y')) = "xy"
gr</pre>
gr
grWe can combine multiple primitives using <a>&gt;*&lt;</a> multiple
grtimes.
gr
gr<pre>
grtoLazyByteString (primFixed (char7 &gt;*&lt; char7 &gt;*&lt; char7) ('x',('y','z'))) = "xyz"
gr</pre>
(>*<) :: Monoidal f => f a -> f b -> f (a, b)
infixr 5 >*<

-- | A fmap-like operator for builder primitives, both bounded and fixed
grsize.
gr
grBuilder primitives are contravariant so it's like the normal fmap, but
grbackwards (look at the type). (If it helps to remember, the operator
grsymbol is like (<a>$</a>) but backwards.)
gr
grWe can use it for example to prepend and/or append fixed values to an
grprimitive.
gr
gr<pre>
grshowEncoding ((\x -&gt; ('\'', (x, '\''))) &gt;$&lt; fixed3) 'x' = "'x'"
gr  where
gr    fixed3 = char7 &gt;*&lt; char7 &gt;*&lt; char7
gr</pre>
gr
grNote that the rather verbose syntax for composition stems from the
grrequirement to be able to compute the size / size bound at compile
grtime.
(>$<) :: Contravariant f => (b -> a) -> f a -> f b
infixl 4 >$<

-- | Encode an <a>Either</a> value using the first <a>BoundedPrim</a> for
gr<a>Left</a> values and the second <a>BoundedPrim</a> for <a>Right</a>
grvalues.
gr
grNote that the functions <a>eitherB</a>, <a>pairB</a>, and
gr<a>contramapB</a> (written below using <a>&gt;$&lt;</a>) suffice to
grconstruct <a>BoundedPrim</a>s for all non-recursive algebraic
grdatatypes. For example,
gr
gr<pre>
grmaybeB :: BoundedPrim () -&gt; BoundedPrim a -&gt; BoundedPrim (Maybe a)
grmaybeB nothing just = <a>maybe</a> (Left ()) Right <a>&gt;$&lt;</a> eitherB nothing just
gr 
gr</pre>
eitherB :: BoundedPrim a -> BoundedPrim b -> BoundedPrim (Either a b)

-- | Conditionally select a <a>BoundedPrim</a>. For example, we can
grimplement the ASCII primitive that drops characters with Unicode
grcodepoints above 127 as follows.
gr
gr<pre>
grcharASCIIDrop = <a>condB</a> (&lt; '\128') (<tt>fromF</tt> <tt>char7</tt>) <a>emptyB</a>
gr 
gr</pre>
condB :: (a -> Bool) -> BoundedPrim a -> BoundedPrim a -> BoundedPrim a

-- | Create a <a>Builder</a> that encodes values with the given
gr<a>BoundedPrim</a>.
gr
grWe rewrite consecutive uses of <a>primBounded</a> such that the
grbound-checks are fused. For example,
gr
gr<pre>
grprimBounded (word32 c1) `mappend` primBounded (word32 c2)
gr</pre>
gr
gris rewritten such that the resulting <a>Builder</a> checks only once,
grif ther are at 8 free bytes, instead of checking twice, if there are 4
grfree bytes. This optimization is not observationally equivalent in a
grstrict sense, as it influences the boundaries of the generated chunks.
grHowever, for a user of this library it is observationally equivalent,
gras chunk boundaries of a lazy <a>ByteString</a> can only be observed
grthrough the internal interface. Morevoer, we expect that all
grprimitives write much fewer than 4kb (the default short buffer size).
grHence, it is safe to ignore the additional memory spilled due to the
grmore agressive buffer wrapping introduced by this optimization.
primBounded :: BoundedPrim a -> (a -> Builder)

-- | Create a <a>Builder</a> that encodes a list of values consecutively
grusing a <a>BoundedPrim</a> for each element. This function is more
grefficient than the canonical
gr
gr<pre>
grfilter p =
gr B.toLazyByteString .
gr E.encodeLazyByteStringWithF (E.ifF p E.word8) E.emptyF)
gr</pre>
gr
gr<pre>
grmconcat . map (primBounded w)
gr</pre>
gr
gror
gr
gr<pre>
grfoldMap (primBounded w)
gr</pre>
gr
grbecause it moves several variables out of the inner loop.
primMapListBounded :: BoundedPrim a -> [a] -> Builder

-- | Create a <a>Builder</a> that encodes a sequence generated from a seed
grvalue using a <a>BoundedPrim</a> for each sequence element.
primUnfoldrBounded :: BoundedPrim b -> (a -> Maybe (b, a)) -> a -> Builder

-- | Create a <a>Builder</a> that encodes each <a>Word8</a> of a strict
gr<a>ByteString</a> using a <a>BoundedPrim</a>. For example, we can
grwrite a <a>Builder</a> that filters a strict <a>ByteString</a> as
grfollows.
gr
gr<pre>
grimport Data.ByteString.Builder.Primas P (word8, condB, emptyB)
gr</pre>
gr
gr<pre>
grfilterBS p = P.condB p P.word8 P.emptyB
gr</pre>
primMapByteStringBounded :: BoundedPrim Word8 -> ByteString -> Builder

-- | Chunk-wise application of <a>primMapByteStringBounded</a>.
primMapLazyByteStringBounded :: BoundedPrim Word8 -> ByteString -> Builder

-- | A builder primitive that always results in a sequence of bytes of a
grpre-determined, fixed size.
data FixedPrim a

-- | The <a>FixedPrim</a> that always results in the zero-length sequence.
emptyF :: FixedPrim a

-- | Lift a <a>FixedPrim</a> to a <a>BoundedPrim</a>.
liftFixedToBounded :: FixedPrim a -> BoundedPrim a

-- | Encode a value with a <a>FixedPrim</a>.
primFixed :: FixedPrim a -> (a -> Builder)

-- | Encode a list of values from left-to-right with a <a>FixedPrim</a>.
primMapListFixed :: FixedPrim a -> ([a] -> Builder)

-- | Encode a list of values represented as an <a>unfoldr</a> with a
gr<a>FixedPrim</a>.
primUnfoldrFixed :: FixedPrim b -> (a -> Maybe (b, a)) -> a -> Builder

-- | <i>Heavy inlining.</i> Encode all bytes of a strict <a>ByteString</a>
grfrom left-to-right with a <a>FixedPrim</a>. This function is quite
grversatile. For example, we can use it to construct a <a>Builder</a>
grthat maps every byte before copying it to the buffer to be filled.
gr
gr<pre>
grmapToBuilder :: (Word8 -&gt; Word8) -&gt; S.ByteString -&gt; Builder
grmapToBuilder f = encodeByteStringWithF (contramapF f word8)
gr</pre>
gr
grWe can also use it to hex-encode a strict <a>ByteString</a> as shown
grby the <tt>byteStringHex</tt> example above.
primMapByteStringFixed :: FixedPrim Word8 -> (ByteString -> Builder)

-- | <i>Heavy inlining.</i> Encode all bytes of a lazy <a>ByteString</a>
grfrom left-to-right with a <a>FixedPrim</a>.
primMapLazyByteStringFixed :: FixedPrim Word8 -> (ByteString -> Builder)

-- | Encoding single signed bytes as-is.
int8 :: FixedPrim Int8

-- | Encoding single unsigned bytes as-is.
word8 :: FixedPrim Word8

-- | Encoding <a>Int16</a>s in big endian format.
int16BE :: FixedPrim Int16

-- | Encoding <a>Int32</a>s in big endian format.
int32BE :: FixedPrim Int32

-- | Encoding <a>Int64</a>s in big endian format.
int64BE :: FixedPrim Int64

-- | Encoding <a>Word16</a>s in big endian format.
word16BE :: FixedPrim Word16

-- | Encoding <a>Word32</a>s in big endian format.
word32BE :: FixedPrim Word32

-- | Encoding <a>Word64</a>s in big endian format.
word64BE :: FixedPrim Word64

-- | Encode a <a>Float</a> in big endian format.
floatBE :: FixedPrim Float

-- | Encode a <a>Double</a> in big endian format.
doubleBE :: FixedPrim Double

-- | Encoding <a>Int16</a>s in little endian format.
int16LE :: FixedPrim Int16

-- | Encoding <a>Int32</a>s in little endian format.
int32LE :: FixedPrim Int32

-- | Encoding <a>Int64</a>s in little endian format.
int64LE :: FixedPrim Int64

-- | Encoding <a>Word16</a>s in little endian format.
word16LE :: FixedPrim Word16

-- | Encoding <a>Word32</a>s in little endian format.
word32LE :: FixedPrim Word32

-- | Encoding <a>Word64</a>s in little endian format.
word64LE :: FixedPrim Word64

-- | Encode a <a>Float</a> in little endian format.
floatLE :: FixedPrim Float

-- | Encode a <a>Double</a> in little endian format.
doubleLE :: FixedPrim Double

-- | Encode a single native machine <a>Int</a>. The <a>Int</a>s is encoded
grin host order, host endian form, for the machine you are on. On a 64
grbit machine the <a>Int</a> is an 8 byte value, on a 32 bit machine, 4
grbytes. Values encoded this way are not portable to different endian or
grinteger sized machines, without conversion.
intHost :: FixedPrim Int

-- | Encoding <a>Int16</a>s in native host order and host endianness.
int16Host :: FixedPrim Int16

-- | Encoding <a>Int32</a>s in native host order and host endianness.
int32Host :: FixedPrim Int32

-- | Encoding <a>Int64</a>s in native host order and host endianness.
int64Host :: FixedPrim Int64

-- | Encode a single native machine <a>Word</a>. The <a>Word</a>s is
grencoded in host order, host endian form, for the machine you are on.
grOn a 64 bit machine the <a>Word</a> is an 8 byte value, on a 32 bit
grmachine, 4 bytes. Values encoded this way are not portable to
grdifferent endian or word sized machines, without conversion.
wordHost :: FixedPrim Word

-- | Encoding <a>Word16</a>s in native host order and host endianness.
word16Host :: FixedPrim Word16

-- | Encoding <a>Word32</a>s in native host order and host endianness.
word32Host :: FixedPrim Word32

-- | Encoding <a>Word64</a>s in native host order and host endianness.
word64Host :: FixedPrim Word64

-- | Encode a <a>Float</a> in native host order and host endianness. Values
grwritten this way are not portable to different endian machines,
grwithout conversion.
floatHost :: FixedPrim Float

-- | Encode a <a>Double</a> in native host order and host endianness.
doubleHost :: FixedPrim Double

-- | Encode the least 7-bits of a <a>Char</a> using the ASCII encoding.
char7 :: FixedPrim Char

-- | Decimal encoding of an <a>Int8</a>.
int8Dec :: BoundedPrim Int8

-- | Decimal encoding of an <a>Int16</a>.
int16Dec :: BoundedPrim Int16

-- | Decimal encoding of an <a>Int32</a>.
int32Dec :: BoundedPrim Int32

-- | Decimal encoding of an <a>Int64</a>.
int64Dec :: BoundedPrim Int64

-- | Decimal encoding of an <a>Int</a>.
intDec :: BoundedPrim Int

-- | Decimal encoding of a <a>Word8</a>.
word8Dec :: BoundedPrim Word8

-- | Decimal encoding of a <a>Word16</a>.
word16Dec :: BoundedPrim Word16

-- | Decimal encoding of a <a>Word32</a>.
word32Dec :: BoundedPrim Word32

-- | Decimal encoding of a <a>Word64</a>.
word64Dec :: BoundedPrim Word64

-- | Decimal encoding of a <a>Word</a>.
wordDec :: BoundedPrim Word

-- | Hexadecimal encoding of a <a>Word8</a>.
word8Hex :: BoundedPrim Word8

-- | Hexadecimal encoding of a <a>Word16</a>.
word16Hex :: BoundedPrim Word16

-- | Hexadecimal encoding of a <a>Word32</a>.
word32Hex :: BoundedPrim Word32

-- | Hexadecimal encoding of a <a>Word64</a>.
word64Hex :: BoundedPrim Word64

-- | Hexadecimal encoding of a <a>Word</a>.
wordHex :: BoundedPrim Word

-- | Encode a <a>Int8</a> using 2 nibbles (hexadecimal digits).
int8HexFixed :: FixedPrim Int8

-- | Encode a <a>Int16</a> using 4 nibbles.
int16HexFixed :: FixedPrim Int16

-- | Encode a <a>Int32</a> using 8 nibbles.
int32HexFixed :: FixedPrim Int32

-- | Encode a <a>Int64</a> using 16 nibbles.
int64HexFixed :: FixedPrim Int64

-- | Encode a <a>Word8</a> using 2 nibbles (hexadecimal digits).
word8HexFixed :: FixedPrim Word8

-- | Encode a <a>Word16</a> using 4 nibbles.
word16HexFixed :: FixedPrim Word16

-- | Encode a <a>Word32</a> using 8 nibbles.
word32HexFixed :: FixedPrim Word32

-- | Encode a <a>Word64</a> using 16 nibbles.
word64HexFixed :: FixedPrim Word64

-- | Encode an IEEE <a>Float</a> using 8 nibbles.
floatHexFixed :: FixedPrim Float

-- | Encode an IEEE <a>Double</a> using 16 nibbles.
doubleHexFixed :: FixedPrim Double

-- | Char8 encode a <a>Char</a>.
char8 :: FixedPrim Char

-- | UTF-8 encode a <a>Char</a>.
charUtf8 :: BoundedPrim Char


-- | Extra functions for creating and executing <a>Builder</a>s. They are
grintended for application-specific fine-tuning the performance of
gr<a>Builder</a>s.
module Data.ByteString.Builder.Extra

-- | <i>Heavy inlining.</i> Execute a <a>Builder</a> with custom execution
grparameters.
gr
grThis function is inlined despite its heavy code-size to allow fusing
grwith the allocation strategy. For example, the default <a>Builder</a>
grexecution function <tt>toLazyByteString</tt> is defined as follows.
gr
gr<pre>
gr{-# NOINLINE toLazyByteString #-}
grtoLazyByteString =
gr  toLazyByteStringWith (<a>safeStrategy</a> <a>smallChunkSize</a> <a>defaultChunkSize</a>) L.empty
gr</pre>
gr
grwhere <tt>L.empty</tt> is the zero-length lazy <a>ByteString</a>.
gr
grIn most cases, the parameters used by <tt>toLazyByteString</tt> give
grgood performance. A sub-performing case of <tt>toLazyByteString</tt>
gris executing short (&lt;128 bytes) <a>Builder</a>s. In this case, the
grallocation overhead for the first 4kb buffer and the trimming cost
grdominate the cost of executing the <a>Builder</a>. You can avoid this
grproblem using
gr
gr<pre>
grtoLazyByteStringWith (safeStrategy 128 smallChunkSize) L.empty
gr</pre>
gr
grThis reduces the allocation and trimming overhead, as all generated
gr<a>ByteString</a>s fit into the first buffer and there is no trimming
grrequired, if more than 64 bytes and less than 128 bytes are written.
toLazyByteStringWith :: AllocationStrategy -> ByteString -> Builder -> ByteString

-- | A buffer allocation strategy for executing <a>Builder</a>s.
data AllocationStrategy

-- | Use this strategy for generating lazy <a>ByteString</a>s whose chunks
grare likely to survive one garbage collection. This strategy trims
grbuffers that are filled less than half in order to avoid spilling too
grmuch memory.
safeStrategy :: Int -> Int -> AllocationStrategy

-- | Use this strategy for generating lazy <a>ByteString</a>s whose chunks
grare discarded right after they are generated. For example, if you just
grgenerate them to write them to a network socket.
untrimmedStrategy :: Int -> Int -> AllocationStrategy

-- | The recommended chunk size. Currently set to 4k, less the memory
grmanagement overhead
smallChunkSize :: Int

-- | The chunk size used for I/O. Currently set to 32k, less the memory
grmanagement overhead
defaultChunkSize :: Int

-- | Construct a <a>Builder</a> that copies the strict <a>ByteString</a>.
gr
grUse this function to create <a>Builder</a>s from smallish (<tt>&lt;=
gr4kb</tt>) <a>ByteString</a>s or if you need to guarantee that the
gr<a>ByteString</a> is not shared with the chunks generated by the
gr<a>Builder</a>.
byteStringCopy :: ByteString -> Builder

-- | Construct a <a>Builder</a> that always inserts the strict
gr<a>ByteString</a> directly as a chunk.
gr
grThis implies flushing the output buffer, even if it contains just a
grsingle byte. You should therefore use <a>byteStringInsert</a> only for
grlarge (<tt>&gt; 8kb</tt>) <a>ByteString</a>s. Otherwise, the generated
grchunks are too fragmented to be processed efficiently afterwards.
byteStringInsert :: ByteString -> Builder

-- | Construct a <a>Builder</a> that copies the strict <a>ByteString</a>s,
grif it is smaller than the treshold, and inserts it directly otherwise.
gr
grFor example, <tt>byteStringThreshold 1024</tt> copies strict
gr<a>ByteString</a>s whose size is less or equal to 1kb, and inserts
grthem directly otherwise. This implies that the average chunk-size of
grthe generated lazy <a>ByteString</a> may be as low as 513 bytes, as
grthere could always be just a single byte between the directly inserted
gr1025 byte, strict <a>ByteString</a>s.
byteStringThreshold :: Int -> ByteString -> Builder

-- | Construct a <a>Builder</a> that copies the lazy <a>ByteString</a>.
lazyByteStringCopy :: ByteString -> Builder

-- | Construct a <a>Builder</a> that inserts all chunks of the lazy
gr<a>ByteString</a> directly.
lazyByteStringInsert :: ByteString -> Builder

-- | Construct a <a>Builder</a> that uses the thresholding strategy of
gr<a>byteStringThreshold</a> for each chunk of the lazy
gr<a>ByteString</a>.
lazyByteStringThreshold :: Int -> ByteString -> Builder

-- | Flush the current buffer. This introduces a chunk boundary.
flush :: Builder

-- | A <a>BufferWriter</a> represents the result of running a
gr<a>Builder</a>. It unfolds as a sequence of chunks of data. These
grchunks come in two forms:
gr
gr<ul>
gr<li>an IO action for writing the Builder's data into a user-supplied
grmemory buffer.</li>
gr<li>a pre-existing chunks of data represented by a strict
gr<tt>ByteString</tt></li>
gr</ul>
gr
grWhile this is rather low level, it provides you with full flexibility
grin how the data is written out.
gr
grThe <a>BufferWriter</a> itself is an IO action: you supply it with a
grbuffer (as a pointer and length) and it will write data into the
grbuffer. It returns a number indicating how many bytes were actually
grwritten (which can be <tt>0</tt>). It also returns a <a>Next</a> which
grdescribes what comes next.
type BufferWriter = Ptr Word8 -> Int -> IO (Int, Next)

-- | After running a <a>BufferWriter</a> action there are three
grpossibilities for what comes next:
data Next

-- | This means we're all done. All the builder data has now been written.
Done :: Next

-- | This indicates that there may be more data to write. It gives you the
grnext <a>BufferWriter</a> action. You should call that action with an
grappropriate buffer. The int indicates the <i>minimum</i> buffer size
grrequired by the next <a>BufferWriter</a> action. That is, if you call
grthe next action you <i>must</i> supply it with a buffer length of at
grleast this size.
More :: !Int -> BufferWriter -> Next

-- | In addition to the data that has just been written into your buffer by
grthe <a>BufferWriter</a> action, it gives you a pre-existing chunk of
grdata as a <a>ByteString</a>. It also gives you the following
gr<a>BufferWriter</a> action. It is safe to run this following action
grusing a buffer with as much free space as was left by the previous run
graction.
Chunk :: !ByteString -> BufferWriter -> Next

-- | Turn a <a>Builder</a> into its initial <a>BufferWriter</a> action.
runBuilder :: Builder -> BufferWriter

-- | Encode a single native machine <a>Int</a>. The <a>Int</a> is encoded
grin host order, host endian form, for the machine you're on. On a 64
grbit machine the <a>Int</a> is an 8 byte value, on a 32 bit machine, 4
grbytes. Values encoded this way are not portable to different endian or
grint sized machines, without conversion.
intHost :: Int -> Builder

-- | Encode a <a>Int16</a> in native host order and host endianness.
int16Host :: Int16 -> Builder

-- | Encode a <a>Int32</a> in native host order and host endianness.
int32Host :: Int32 -> Builder

-- | Encode a <a>Int64</a> in native host order and host endianness.
int64Host :: Int64 -> Builder

-- | Encode a single native machine <a>Word</a>. The <a>Word</a> is encoded
grin host order, host endian form, for the machine you're on. On a 64
grbit machine the <a>Word</a> is an 8 byte value, on a 32 bit machine, 4
grbytes. Values encoded this way are not portable to different endian or
grword sized machines, without conversion.
wordHost :: Word -> Builder

-- | Encode a <a>Word16</a> in native host order and host endianness.
word16Host :: Word16 -> Builder

-- | Encode a <a>Word32</a> in native host order and host endianness.
word32Host :: Word32 -> Builder

-- | Encode a <a>Word64</a> in native host order and host endianness.
word64Host :: Word64 -> Builder

-- | Encode a <a>Float</a> in native host order. Values encoded this way
grare not portable to different endian machines, without conversion.
floatHost :: Float -> Builder

-- | Encode a <a>Double</a> in native host order.
doubleHost :: Double -> Builder


-- | We decided to rename the Builder modules. Sorry about that.
gr
grThe old names will hang about for at least once release cycle before
grwe deprecate them and then later remove them.
module Data.ByteString.Lazy.Builder.Extras


-- | <a>Builder</a>s are used to efficiently construct sequences of bytes
grfrom smaller parts. Typically, such a construction is part of the
grimplementation of an <i>encoding</i>, i.e., a function for converting
grHaskell values to sequences of bytes. Examples of encodings are the
grgeneration of the sequence of bytes representing a HTML document to be
grsent in a HTTP response by a web application or the serialization of a
grHaskell value using a fixed binary format.
gr
grFor an <i>efficient implementation of an encoding</i>, it is important
grthat (a) little time is spent on converting the Haskell values to the
grresulting sequence of bytes <i>and</i> (b) that the representation of
grthe resulting sequence is such that it can be consumed efficiently.
gr<a>Builder</a>s support (a) by providing an <i>O(1)</i> concatentation
groperation and efficient implementations of basic encodings for
gr<a>Char</a>s, <a>Int</a>s, and other standard Haskell values. They
grsupport (b) by providing their result as a lazy <a>ByteString</a>,
grwhich is internally just a linked list of pointers to <i>chunks</i> of
grconsecutive raw memory. Lazy <a>ByteString</a>s can be efficiently
grconsumed by functions that write them to a file or send them over a
grnetwork socket. Note that each chunk boundary incurs expensive extra
grwork (e.g., a system call) that must be amortized over the work spent
gron consuming the chunk body. <a>Builder</a>s therefore take special
grcare to ensure that the average chunk size is large enough. The
grprecise meaning of large enough is application dependent. The current
grimplementation is tuned for an average chunk size between 4kb and
gr32kb, which should suit most applications.
gr
grAs a simple example of an encoding implementation, we show how to
grefficiently convert the following representation of mixed-data tables
grto an UTF-8 encoded Comma-Separated-Values (CSV) table.
gr
gr<pre>
grdata Cell = StringC String
gr          | IntC Int
gr          deriving( Eq, Ord, Show )
gr
grtype Row   = [Cell]
grtype Table = [Row]
gr</pre>
gr
grWe use the following imports and abbreviate <a>mappend</a> to simplify
grreading.
gr
gr<pre>
grimport qualified <a>Data.ByteString.Lazy</a>               as L
grimport           <a>Data.ByteString.Builder</a>
grimport           Data.Monoid
grimport           Data.Foldable                        (<a>foldMap</a>)
grimport           Data.List                            (<a>intersperse</a>)
gr
grinfixr 4 &lt;&gt;
gr(&lt;&gt;) :: <a>Monoid</a> m =&gt; m -&gt; m -&gt; m
gr(&lt;&gt;) = <a>mappend</a>
gr</pre>
gr
grCSV is a character-based representation of tables. For maximal
grmodularity, we could first render <tt>Table</tt>s as <a>String</a>s
grand then encode this <a>String</a> using some Unicode character
grencoding. However, this sacrifices performance due to the intermediate
gr<a>String</a> representation being built and thrown away right
grafterwards. We get rid of this intermediate <a>String</a>
grrepresentation by fixing the character encoding to UTF-8 and using
gr<a>Builder</a>s to convert <tt>Table</tt>s directly to UTF-8 encoded
grCSV tables represented as lazy <a>ByteString</a>s.
gr
gr<pre>
grencodeUtf8CSV :: Table -&gt; L.ByteString
grencodeUtf8CSV = <a>toLazyByteString</a> . renderTable
gr
grrenderTable :: Table -&gt; Builder
grrenderTable rs = <a>mconcat</a> [renderRow r &lt;&gt; <a>charUtf8</a> '\n' | r &lt;- rs]
gr
grrenderRow :: Row -&gt; Builder
grrenderRow []     = <a>mempty</a>
grrenderRow (c:cs) =
gr    renderCell c &lt;&gt; mconcat [ charUtf8 ',' &lt;&gt; renderCell c' | c' &lt;- cs ]
gr
grrenderCell :: Cell -&gt; Builder
grrenderCell (StringC cs) = renderString cs
grrenderCell (IntC i)     = <a>intDec</a> i
gr
grrenderString :: String -&gt; Builder
grrenderString cs = charUtf8 '"' &lt;&gt; foldMap escape cs &lt;&gt; charUtf8 '"'
gr  where
gr    escape '\\' = charUtf8 '\\' &lt;&gt; charUtf8 '\\'
gr    escape '\"' = charUtf8 '\\' &lt;&gt; charUtf8 '\"'
gr    escape c    = charUtf8 c
gr</pre>
gr
grNote that the ASCII encoding is a subset of the UTF-8 encoding, which
gris why we can use the optimized function <a>intDec</a> to encode an
gr<a>Int</a> as a decimal number with UTF-8 encoded digits. Using
gr<a>intDec</a> is more efficient than <tt><a>stringUtf8</a> .
gr<a>show</a></tt>, as it avoids constructing an intermediate
gr<a>String</a>. Avoiding this intermediate data structure significantly
grimproves performance because encoding <tt>Cell</tt>s is the core
groperation for rendering CSV-tables. See
gr<a>Data.ByteString.Builder.Prim</a> for further information on how to
grimprove the performance of <tt>renderString</tt>.
gr
grWe demonstrate our UTF-8 CSV encoding function on the following table.
gr
gr<pre>
grstrings :: [String]
grstrings =  ["hello", "\"1\"", "λ-wörld"]
gr
grtable :: Table
grtable = [map StringC strings, map IntC [-3..3]]
gr</pre>
gr
grThe expression <tt>encodeUtf8CSV table</tt> results in the following
grlazy <a>ByteString</a>.
gr
gr<pre>
grChunk "\"hello\",\"\\\"1\\\"\",\"\206\187-w\195\182rld\"\n-3,-2,-1,0,1,2,3\n" Empty
gr</pre>
gr
grWe can clearly see that we are converting to a <i>binary</i> format.
grThe 'λ' and 'ö' characters, which have a Unicode codepoint above 127,
grare expanded to their corresponding UTF-8 multi-byte representation.
gr
grWe use the <tt>criterion</tt> library
gr(<a>http://hackage.haskell.org/package/criterion</a>) to benchmark the
grefficiency of our encoding function on the following table.
gr
gr<pre>
grimport Criterion.Main     -- add this import to the ones above
gr
grmaxiTable :: Table
grmaxiTable = take 1000 $ cycle table
gr
grmain :: IO ()
grmain = defaultMain
gr  [ bench "encodeUtf8CSV maxiTable (original)" $
gr      whnf (L.length . encodeUtf8CSV) maxiTable
gr  ]
gr</pre>
gr
grOn a Core2 Duo 2.20GHz on a 32-bit Linux, the above code takes 1ms to
grgenerate the 22'500 bytes long lazy <a>ByteString</a>. Looking again
grat the definitions above, we see that we took care to avoid
grintermediate data structures, as otherwise we would sacrifice
grperformance. For example, the following (arguably simpler) definition
grof <tt>renderRow</tt> is about 20% slower.
gr
gr<pre>
grrenderRow :: Row -&gt; Builder
grrenderRow  = mconcat . intersperse (charUtf8 ',') . map renderCell
gr</pre>
gr
grSimilarly, using <i>O(n)</i> concatentations like <a>++</a> or the
grequivalent <a>concat</a> operations on strict and lazy
gr<a>ByteString</a>s should be avoided. The following definition of
gr<tt>renderString</tt> is also about 20% slower.
gr
gr<pre>
grrenderString :: String -&gt; Builder
grrenderString cs = charUtf8 $ "\"" ++ concatMap escape cs ++ "\""
gr  where
gr    escape '\\' = "\\"
gr    escape '\"' = "\\\""
gr    escape c    = return c
gr</pre>
gr
grApart from removing intermediate data-structures, encodings can be
groptimized further by fine-tuning their execution parameters using the
grfunctions in <a>Data.ByteString.Builder.Extra</a> and their "inner
grloops" using the functions in <a>Data.ByteString.Builder.Prim</a>.
module Data.ByteString.Builder

-- | <a>Builder</a>s denote sequences of bytes. They are <a>Monoid</a>s
grwhere <a>mempty</a> is the zero-length sequence and <a>mappend</a> is
grconcatenation, which runs in <i>O(1)</i>.
data Builder

-- | Execute a <a>Builder</a> and return the generated chunks as a lazy
gr<a>ByteString</a>. The work is performed lazy, i.e., only when a chunk
grof the lazy <a>ByteString</a> is forced.
toLazyByteString :: Builder -> ByteString

-- | Output a <a>Builder</a> to a <a>Handle</a>. The <a>Builder</a> is
grexecuted directly on the buffer of the <a>Handle</a>. If the buffer is
grtoo small (or not present), then it is replaced with a large enough
grbuffer.
gr
grIt is recommended that the <a>Handle</a> is set to binary and
gr<tt>BlockBuffering</tt> mode. See <tt>hSetBinaryMode</tt> and
gr<tt>hSetBuffering</tt>.
gr
grThis function is more efficient than <tt>hPut .
gr<a>toLazyByteString</a></tt> because in many cases no buffer
grallocation has to be done. Moreover, the results of several executions
grof short <a>Builder</a>s are concatenated in the <a>Handle</a>s
grbuffer, therefore avoiding unnecessary buffer flushes.
hPutBuilder :: Handle -> Builder -> IO ()

-- | Create a <a>Builder</a> denoting the same sequence of bytes as a
grstrict <a>ByteString</a>. The <a>Builder</a> inserts large
gr<a>ByteString</a>s directly, but copies small ones to ensure that the
grgenerated chunks are large on average.
byteString :: ByteString -> Builder

-- | Create a <a>Builder</a> denoting the same sequence of bytes as a lazy
gr<a>ByteString</a>. The <a>Builder</a> inserts large chunks of the lazy
gr<a>ByteString</a> directly, but copies small ones to ensure that the
grgenerated chunks are large on average.
lazyByteString :: ByteString -> Builder

-- | Construct a <a>Builder</a> that copies the <a>ShortByteString</a>.
shortByteString :: ShortByteString -> Builder

-- | Encode a single signed byte as-is.
int8 :: Int8 -> Builder

-- | Encode a single unsigned byte as-is.
word8 :: Word8 -> Builder

-- | Encode an <a>Int16</a> in big endian format.
int16BE :: Int16 -> Builder

-- | Encode an <a>Int32</a> in big endian format.
int32BE :: Int32 -> Builder

-- | Encode an <a>Int64</a> in big endian format.
int64BE :: Int64 -> Builder

-- | Encode a <a>Word16</a> in big endian format.
word16BE :: Word16 -> Builder

-- | Encode a <a>Word32</a> in big endian format.
word32BE :: Word32 -> Builder

-- | Encode a <a>Word64</a> in big endian format.
word64BE :: Word64 -> Builder

-- | Encode a <a>Float</a> in big endian format.
floatBE :: Float -> Builder

-- | Encode a <a>Double</a> in big endian format.
doubleBE :: Double -> Builder

-- | Encode an <a>Int16</a> in little endian format.
int16LE :: Int16 -> Builder

-- | Encode an <a>Int32</a> in little endian format.
int32LE :: Int32 -> Builder

-- | Encode an <a>Int64</a> in little endian format.
int64LE :: Int64 -> Builder

-- | Encode a <a>Word16</a> in little endian format.
word16LE :: Word16 -> Builder

-- | Encode a <a>Word32</a> in little endian format.
word32LE :: Word32 -> Builder

-- | Encode a <a>Word64</a> in little endian format.
word64LE :: Word64 -> Builder

-- | Encode a <a>Float</a> in little endian format.
floatLE :: Float -> Builder

-- | Encode a <a>Double</a> in little endian format.
doubleLE :: Double -> Builder

-- | Char7 encode a <a>Char</a>.
char7 :: Char -> Builder

-- | Char7 encode a <a>String</a>.
string7 :: String -> Builder

-- | Char8 encode a <a>Char</a>.
char8 :: Char -> Builder

-- | Char8 encode a <a>String</a>.
string8 :: String -> Builder

-- | UTF-8 encode a <a>Char</a>.
charUtf8 :: Char -> Builder

-- | UTF-8 encode a <a>String</a>.
stringUtf8 :: String -> Builder

-- | Decimal encoding of an <a>Int8</a> using the ASCII digits.
gr
gre.g.
gr
gr<pre>
grtoLazyByteString (int8Dec 42)   = "42"
grtoLazyByteString (int8Dec (-1)) = "-1"
gr</pre>
int8Dec :: Int8 -> Builder

-- | Decimal encoding of an <a>Int16</a> using the ASCII digits.
int16Dec :: Int16 -> Builder

-- | Decimal encoding of an <a>Int32</a> using the ASCII digits.
int32Dec :: Int32 -> Builder

-- | Decimal encoding of an <a>Int64</a> using the ASCII digits.
int64Dec :: Int64 -> Builder

-- | Decimal encoding of an <a>Int</a> using the ASCII digits.
intDec :: Int -> Builder

-- | Decimal encoding of an <a>Integer</a> using the ASCII digits.
integerDec :: Integer -> Builder

-- | Decimal encoding of a <a>Word8</a> using the ASCII digits.
word8Dec :: Word8 -> Builder

-- | Decimal encoding of a <a>Word16</a> using the ASCII digits.
word16Dec :: Word16 -> Builder

-- | Decimal encoding of a <a>Word32</a> using the ASCII digits.
word32Dec :: Word32 -> Builder

-- | Decimal encoding of a <a>Word64</a> using the ASCII digits.
word64Dec :: Word64 -> Builder

-- | Decimal encoding of a <a>Word</a> using the ASCII digits.
wordDec :: Word -> Builder

-- | <i>Currently slow.</i> Decimal encoding of an IEEE <a>Float</a>.
floatDec :: Float -> Builder

-- | <i>Currently slow.</i> Decimal encoding of an IEEE <a>Double</a>.
doubleDec :: Double -> Builder

-- | Shortest hexadecimal encoding of a <a>Word8</a> using lower-case
grcharacters.
word8Hex :: Word8 -> Builder

-- | Shortest hexadecimal encoding of a <a>Word16</a> using lower-case
grcharacters.
word16Hex :: Word16 -> Builder

-- | Shortest hexadecimal encoding of a <a>Word32</a> using lower-case
grcharacters.
word32Hex :: Word32 -> Builder

-- | Shortest hexadecimal encoding of a <a>Word64</a> using lower-case
grcharacters.
word64Hex :: Word64 -> Builder

-- | Shortest hexadecimal encoding of a <a>Word</a> using lower-case
grcharacters.
wordHex :: Word -> Builder

-- | Encode a <a>Int8</a> using 2 nibbles (hexadecimal digits).
int8HexFixed :: Int8 -> Builder

-- | Encode a <a>Int16</a> using 4 nibbles.
int16HexFixed :: Int16 -> Builder

-- | Encode a <a>Int32</a> using 8 nibbles.
int32HexFixed :: Int32 -> Builder

-- | Encode a <a>Int64</a> using 16 nibbles.
int64HexFixed :: Int64 -> Builder

-- | Encode a <a>Word8</a> using 2 nibbles (hexadecimal digits).
word8HexFixed :: Word8 -> Builder

-- | Encode a <a>Word16</a> using 4 nibbles.
word16HexFixed :: Word16 -> Builder

-- | Encode a <a>Word32</a> using 8 nibbles.
word32HexFixed :: Word32 -> Builder

-- | Encode a <a>Word64</a> using 16 nibbles.
word64HexFixed :: Word64 -> Builder

-- | Encode an IEEE <a>Float</a> using 8 nibbles.
floatHexFixed :: Float -> Builder

-- | Encode an IEEE <a>Double</a> using 16 nibbles.
doubleHexFixed :: Double -> Builder

-- | Encode each byte of a <a>ByteString</a> using its fixed-width hex
grencoding.
byteStringHex :: ByteString -> Builder

-- | Encode each byte of a lazy <a>ByteString</a> using its fixed-width hex
grencoding.
lazyByteStringHex :: ByteString -> Builder
instance Data.String.IsString Data.ByteString.Builder.Internal.Builder


-- | We decided to rename the Builder modules. Sorry about that.
gr
grIn additon, the ASCII module has been merged into the main
gr<a>Data.ByteString.Builder</a> module.
gr
grThe old names will hang about for at least once release cycle before
grwe deprecate them and then later remove them.
module Data.ByteString.Lazy.Builder.ASCII
byteStringHexFixed :: ByteString -> Builder
lazyByteStringHexFixed :: ByteString -> Builder


-- | We decided to rename the Builder modules. Sorry about that.
gr
grThe old names will hang about for at least once release cycle before
grwe deprecate them and then later remove them.
module Data.ByteString.Lazy.Builder
