1 {-# OPTIONS_GHC -cpp -fno-warn-orphans #-}
3 -- Module : Data.ByteString.Lazy.Char8
4 -- Copyright : (c) Don Stewart 2006
7 -- Maintainer : dons@cse.unsw.edu.au
8 -- Stability : experimental
9 -- Portability : portable (tested with GHC>=6.4.1 and Hugs 2005)
13 -- | Manipulate /lazy/ 'ByteString's using 'Char' operations. All Chars will
14 -- be truncated to 8 bits. It can be expected that these functions will
15 -- run at identical speeds to their Word8 equivalents in
16 -- "Data.ByteString.Lazy".
18 -- This module is intended to be imported @qualified@, to avoid name
19 -- clashes with "Prelude" functions. eg.
21 -- > import qualified Data.ByteString.Lazy.Char8 as C
24 module Data.ByteString.Lazy.Char8 (
26 -- * The @ByteString@ type
27 ByteString, -- instances: Eq, Ord, Show, Read, Data, Typeable
29 -- * Introducing and eliminating 'ByteString's
30 empty, -- :: ByteString
31 singleton, -- :: Char -> ByteString
32 pack, -- :: String -> ByteString
33 unpack, -- :: ByteString -> String
34 fromChunks, -- :: [Strict.ByteString] -> ByteString
35 toChunks, -- :: ByteString -> [Strict.ByteString]
38 cons, -- :: Char -> ByteString -> ByteString
39 snoc, -- :: ByteString -> Char -> ByteString
40 append, -- :: ByteString -> ByteString -> ByteString
41 head, -- :: ByteString -> Char
42 last, -- :: ByteString -> Char
43 tail, -- :: ByteString -> ByteString
44 init, -- :: ByteString -> ByteString
45 null, -- :: ByteString -> Bool
46 length, -- :: ByteString -> Int64
48 -- * Transformating ByteStrings
49 map, -- :: (Char -> Char) -> ByteString -> ByteString
50 reverse, -- :: ByteString -> ByteString
51 -- intersperse, -- :: Char -> ByteString -> ByteString
52 transpose, -- :: [ByteString] -> [ByteString]
54 -- * Reducing 'ByteString's (folds)
55 foldl, -- :: (a -> Char -> a) -> a -> ByteString -> a
56 foldl', -- :: (a -> Char -> a) -> a -> ByteString -> a
57 foldl1, -- :: (Char -> Char -> Char) -> ByteString -> Char
58 foldl1', -- :: (Char -> Char -> Char) -> ByteString -> Char
59 foldr, -- :: (Char -> a -> a) -> a -> ByteString -> a
60 foldr1, -- :: (Char -> Char -> Char) -> ByteString -> Char
63 concat, -- :: [ByteString] -> ByteString
64 concatMap, -- :: (Char -> ByteString) -> ByteString -> ByteString
65 any, -- :: (Char -> Bool) -> ByteString -> Bool
66 all, -- :: (Char -> Bool) -> ByteString -> Bool
67 maximum, -- :: ByteString -> Char
68 minimum, -- :: ByteString -> Char
70 -- * Building ByteStrings
72 scanl, -- :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString
73 -- scanl1, -- :: (Char -> Char -> Char) -> ByteString -> ByteString
74 -- scanr, -- :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString
75 -- scanr1, -- :: (Char -> Char -> Char) -> ByteString -> ByteString
77 -- ** Accumulating maps
78 mapAccumL, -- :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)
79 mapIndexed, -- :: (Int64 -> Char -> Char) -> ByteString -> ByteString
81 -- ** Infinite ByteStrings
82 repeat, -- :: Char -> ByteString
83 replicate, -- :: Int64 -> Char -> ByteString
84 cycle, -- :: ByteString -> ByteString
85 iterate, -- :: (Char -> Char) -> Char -> ByteString
88 unfoldr, -- :: (a -> Maybe (Char, a)) -> a -> ByteString
92 -- ** Breaking strings
93 take, -- :: Int64 -> ByteString -> ByteString
94 drop, -- :: Int64 -> ByteString -> ByteString
95 splitAt, -- :: Int64 -> ByteString -> (ByteString, ByteString)
96 takeWhile, -- :: (Char -> Bool) -> ByteString -> ByteString
97 dropWhile, -- :: (Char -> Bool) -> ByteString -> ByteString
98 span, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
99 break, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
100 group, -- :: ByteString -> [ByteString]
101 groupBy, -- :: (Char -> Char -> Bool) -> ByteString -> [ByteString]
102 inits, -- :: ByteString -> [ByteString]
103 tails, -- :: ByteString -> [ByteString]
105 -- ** Breaking into many substrings
106 split, -- :: Char -> ByteString -> [ByteString]
107 splitWith, -- :: (Char -> Bool) -> ByteString -> [ByteString]
109 -- ** Breaking into lines and words
110 lines, -- :: ByteString -> [ByteString]
111 words, -- :: ByteString -> [ByteString]
112 unlines, -- :: [ByteString] -> ByteString
113 unwords, -- :: ByteString -> [ByteString]
115 -- ** Joining strings
116 join, -- :: ByteString -> [ByteString] -> ByteString
119 isPrefixOf, -- :: ByteString -> ByteString -> Bool
120 -- isSuffixOf, -- :: ByteString -> ByteString -> Bool
122 -- * Searching ByteStrings
124 -- ** Searching by equality
125 elem, -- :: Char -> ByteString -> Bool
126 notElem, -- :: Char -> ByteString -> Bool
128 -- ** Searching with a predicate
129 find, -- :: (Char -> Bool) -> ByteString -> Maybe Char
130 filter, -- :: (Char -> Bool) -> ByteString -> ByteString
131 -- partition -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
133 -- * Indexing ByteStrings
134 index, -- :: ByteString -> Int64 -> Char
135 elemIndex, -- :: Char -> ByteString -> Maybe Int64
136 elemIndices, -- :: Char -> ByteString -> [Int64]
137 findIndex, -- :: (Char -> Bool) -> ByteString -> Maybe Int64
138 findIndices, -- :: (Char -> Bool) -> ByteString -> [Int64]
139 count, -- :: Char -> ByteString -> Int64
141 -- * Zipping and unzipping ByteStrings
142 zip, -- :: ByteString -> ByteString -> [(Char,Char)]
143 zipWith, -- :: (Char -> Char -> c) -> ByteString -> ByteString -> [c]
144 -- unzip, -- :: [(Char,Char)] -> (ByteString,ByteString)
146 -- * Ordered ByteStrings
147 -- sort, -- :: ByteString -> ByteString
149 copy, -- :: ByteString -> ByteString
151 -- * Reading from ByteStrings
155 -- * I\/O with 'ByteString's
157 -- ** Standard input and output
158 getContents, -- :: IO ByteString
159 putStr, -- :: ByteString -> IO ()
160 putStrLn, -- :: ByteString -> IO ()
161 interact, -- :: (ByteString -> ByteString) -> IO ()
164 readFile, -- :: FilePath -> IO ByteString
165 writeFile, -- :: FilePath -> ByteString -> IO ()
166 appendFile, -- :: FilePath -> ByteString -> IO ()
168 -- ** I\/O with Handles
169 hGetContents, -- :: Handle -> IO ByteString
170 hGet, -- :: Handle -> Int64 -> IO ByteString
171 hPut, -- :: Handle -> ByteString -> IO ()
172 hGetNonBlocking, -- :: Handle -> IO ByteString
174 -- hGetN, -- :: Int -> Handle -> Int64 -> IO ByteString
175 -- hGetContentsN, -- :: Int -> Handle -> IO ByteString
176 -- hGetNonBlockingN, -- :: Int -> Handle -> IO ByteString
179 -- Functions transparently exported
180 import Data.ByteString.Lazy
181 (ByteString, fromChunks, toChunks
182 ,empty,null,length,tail,init,append,reverse,transpose
183 ,concat,take,drop,splitAt,join,isPrefixOf,group,inits,tails,copy
184 ,hGetContents, hGet, hPut, getContents
186 ,putStr, putStrLn, interact)
188 -- Functions we need to wrap.
189 import qualified Data.ByteString.Lazy as L
190 import qualified Data.ByteString as B
191 import qualified Data.ByteString.Base as B
192 import Data.ByteString.Base (LazyByteString(LPS))
194 import Data.ByteString.Base (w2c, c2w, isSpaceWord8)
196 import Data.Int (Int64)
197 import qualified Data.List as List (intersperse)
199 import qualified Prelude as P
200 import Prelude hiding
201 (reverse,head,tail,last,init,null,length,map,lines,foldl,foldr,unlines
202 ,concat,any,take,drop,splitAt,takeWhile,dropWhile,span,break,elem,filter
203 ,unwords,words,maximum,minimum,all,concatMap,scanl,scanl1,foldl1,foldr1
204 ,readFile,writeFile,appendFile,replicate,getContents,getLine,putStr,putStrLn
205 ,zip,zipWith,unzip,notElem,repeat,iterate,interact)
207 import System.IO (hClose,openFile,IOMode(..))
208 import Control.Exception (bracket)
210 #define STRICT1(f) f a | a `seq` False = undefined
211 #define STRICT2(f) f a b | a `seq` b `seq` False = undefined
212 #define STRICT3(f) f a b c | a `seq` b `seq` c `seq` False = undefined
213 #define STRICT4(f) f a b c d | a `seq` b `seq` c `seq` d `seq` False = undefined
214 #define STRICT5(f) f a b c d e | a `seq` b `seq` c `seq` d `seq` e `seq` False = undefined
216 ------------------------------------------------------------------------
218 -- | /O(1)/ Convert a 'Char' into a 'ByteString'
219 singleton :: Char -> ByteString
220 singleton = L.singleton . c2w
221 {-# INLINE singleton #-}
223 -- | /O(n)/ Convert a 'String' into a 'ByteString'.
224 pack :: [Char] -> ByteString
225 pack = L.pack. P.map c2w
227 -- | /O(n)/ Converts a 'ByteString' to a 'String'.
228 unpack :: ByteString -> [Char]
229 unpack = P.map w2c . L.unpack
230 {-# INLINE unpack #-}
232 -- | /O(n)/ 'cons' is analogous to (:) for lists, but of different
233 -- complexity, as it requires a memcpy.
234 cons :: Char -> ByteString -> ByteString
238 -- | /O(n)/ Append a Char to the end of a 'ByteString'. Similar to
239 -- 'cons', this function performs a memcpy.
240 snoc :: ByteString -> Char -> ByteString
241 snoc p = L.snoc p . c2w
244 -- | /O(1)/ Extract the first element of a ByteString, which must be non-empty.
245 head :: ByteString -> Char
249 -- | /O(1)/ Extract the last element of a packed string, which must be non-empty.
250 last :: ByteString -> Char
254 -- | /O(n)/ 'map' @f xs@ is the ByteString obtained by applying @f@ to each element of @xs@
255 map :: (Char -> Char) -> ByteString -> ByteString
256 map f = L.map (c2w . f . w2c)
259 -- | 'foldl', applied to a binary operator, a starting value (typically
260 -- the left-identity of the operator), and a ByteString, reduces the
261 -- ByteString using the binary operator, from left to right.
262 foldl :: (a -> Char -> a) -> a -> ByteString -> a
263 foldl f = L.foldl (\a c -> f a (w2c c))
266 -- | 'foldl\'' is like foldl, but strict in the accumulator.
267 foldl' :: (a -> Char -> a) -> a -> ByteString -> a
268 foldl' f = L.foldl' (\a c -> f a (w2c c))
269 {-# INLINE foldl' #-}
271 -- | 'foldr', applied to a binary operator, a starting value
272 -- (typically the right-identity of the operator), and a packed string,
273 -- reduces the packed string using the binary operator, from right to left.
274 foldr :: (Char -> a -> a) -> a -> ByteString -> a
275 foldr f = L.foldr (\c a -> f (w2c c) a)
278 -- | 'foldl1' is a variant of 'foldl' that has no starting value
279 -- argument, and thus must be applied to non-empty 'ByteStrings'.
280 foldl1 :: (Char -> Char -> Char) -> ByteString -> Char
281 foldl1 f ps = w2c (L.foldl1 (\x y -> c2w (f (w2c x) (w2c y))) ps)
282 {-# INLINE foldl1 #-}
284 -- | 'foldl1\'' is like 'foldl1', but strict in the accumulator.
285 foldl1' :: (Char -> Char -> Char) -> ByteString -> Char
286 foldl1' f ps = w2c (L.foldl1' (\x y -> c2w (f (w2c x) (w2c y))) ps)
288 -- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
289 -- and thus must be applied to non-empty 'ByteString's
290 foldr1 :: (Char -> Char -> Char) -> ByteString -> Char
291 foldr1 f ps = w2c (L.foldr1 (\x y -> c2w (f (w2c x) (w2c y))) ps)
292 {-# INLINE foldr1 #-}
294 -- | Map a function over a 'ByteString' and concatenate the results
295 concatMap :: (Char -> ByteString) -> ByteString -> ByteString
296 concatMap f = L.concatMap (f . w2c)
297 {-# INLINE concatMap #-}
299 -- | Applied to a predicate and a ByteString, 'any' determines if
300 -- any element of the 'ByteString' satisfies the predicate.
301 any :: (Char -> Bool) -> ByteString -> Bool
302 any f = L.any (f . w2c)
305 -- | Applied to a predicate and a 'ByteString', 'all' determines if
306 -- all elements of the 'ByteString' satisfy the predicate.
307 all :: (Char -> Bool) -> ByteString -> Bool
308 all f = L.all (f . w2c)
311 -- | 'maximum' returns the maximum value from a 'ByteString'
312 maximum :: ByteString -> Char
313 maximum = w2c . L.maximum
314 {-# INLINE maximum #-}
316 -- | 'minimum' returns the minimum value from a 'ByteString'
317 minimum :: ByteString -> Char
318 minimum = w2c . L.minimum
319 {-# INLINE minimum #-}
321 -- ---------------------------------------------------------------------
322 -- Building ByteStrings
324 -- | 'scanl' is similar to 'foldl', but returns a list of successive
325 -- reduced values from the left. This function will fuse.
327 -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
331 -- > last (scanl f z xs) == foldl f z xs.
332 scanl :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString
333 scanl f z = L.scanl (\a b -> c2w (f (w2c a) (w2c b))) (c2w z)
335 -- | The 'mapAccumL' function behaves like a combination of 'map' and
336 -- 'foldl'; it applies a function to each element of a ByteString,
337 -- passing an accumulating parameter from left to right, and returning a
338 -- final value of this accumulator together with the new ByteString.
339 mapAccumL :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)
340 mapAccumL f = L.mapAccumL (\a w -> case f a (w2c w) of (a',c) -> (a', c2w c))
342 -- | /O(n)/ map Char functions, provided with the index at each position
343 mapIndexed :: (Int -> Char -> Char) -> ByteString -> ByteString
344 mapIndexed f = L.mapIndexed (\i w -> c2w (f i (w2c w)))
346 ------------------------------------------------------------------------
347 -- Generating and unfolding ByteStrings
349 -- | @'iterate' f x@ returns an infinite ByteString of repeated applications
352 -- > iterate f x == [x, f x, f (f x), ...]
354 iterate :: (Char -> Char) -> Char -> ByteString
355 iterate f = L.iterate (c2w . f . w2c) . c2w
357 -- | @'repeat' x@ is an infinite ByteString, with @x@ the value of every
360 repeat :: Char -> ByteString
361 repeat = L.repeat . c2w
363 -- | /O(n)/ @'replicate' n x@ is a ByteString of length @n@ with @x@
364 -- the value of every element.
366 replicate :: Int64 -> Char -> ByteString
367 replicate w c = L.replicate w (c2w c)
369 -- | /O(n)/ The 'unfoldr' function is analogous to the List \'unfoldr\'.
370 -- 'unfoldr' builds a ByteString from a seed value. The function takes
371 -- the element and returns 'Nothing' if it is done producing the
372 -- ByteString or returns 'Just' @(a,b)@, in which case, @a@ is a
373 -- prepending to the ByteString and @b@ is used as the next element in a
375 unfoldr :: (a -> Maybe (Char, a)) -> a -> ByteString
376 unfoldr f = L.unfoldr $ \a -> case f a of
378 Just (c, a') -> Just (c2w c, a')
380 ------------------------------------------------------------------------
382 -- | 'takeWhile', applied to a predicate @p@ and a ByteString @xs@,
383 -- returns the longest prefix (possibly empty) of @xs@ of elements that
385 takeWhile :: (Char -> Bool) -> ByteString -> ByteString
386 takeWhile f = L.takeWhile (f . w2c)
387 {-# INLINE takeWhile #-}
389 -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
390 dropWhile :: (Char -> Bool) -> ByteString -> ByteString
391 dropWhile f = L.dropWhile (f . w2c)
392 {-# INLINE dropWhile #-}
394 -- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
395 break :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
396 break f = L.break (f . w2c)
399 -- | 'span' @p xs@ breaks the ByteString into two segments. It is
400 -- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
401 span :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
402 span f = L.span (f . w2c)
406 -- | 'breakChar' breaks its ByteString argument at the first occurence
407 -- of the specified Char. It is more efficient than 'break' as it is
408 -- implemented with @memchr(3)@. I.e.
410 -- > break (=='c') "abcd" == breakChar 'c' "abcd"
412 breakChar :: Char -> ByteString -> (ByteString, ByteString)
413 breakChar = L.breakByte . c2w
414 {-# INLINE breakChar #-}
416 -- | 'spanChar' breaks its ByteString argument at the first
417 -- occurence of a Char other than its argument. It is more efficient
420 -- > span (=='c') "abcd" == spanByte 'c' "abcd"
422 spanChar :: Char -> ByteString -> (ByteString, ByteString)
423 spanChar = L.spanByte . c2w
424 {-# INLINE spanChar #-}
428 -- TODO, more rules for breakChar*
431 -- | /O(n)/ Break a 'ByteString' into pieces separated by the byte
432 -- argument, consuming the delimiter. I.e.
434 -- > split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
435 -- > split 'a' "aXaXaXa" == ["","X","X","X"]
436 -- > split 'x' "x" == ["",""]
440 -- > join [c] . split c == id
441 -- > split == splitWith . (==)
443 -- As for all splitting functions in this library, this function does
444 -- not copy the substrings, it just constructs new 'ByteStrings' that
445 -- are slices of the original.
447 split :: Char -> ByteString -> [ByteString]
448 split = L.split . c2w
451 -- | /O(n)/ Splits a 'ByteString' into components delimited by
452 -- separators, where the predicate returns True for a separator element.
453 -- The resulting components do not contain the separators. Two adjacent
454 -- separators result in an empty component in the output. eg.
456 -- > splitWith (=='a') "aabbaca" == ["","","bb","c",""]
458 splitWith :: (Char -> Bool) -> ByteString -> [ByteString]
459 splitWith f = L.splitWith (f . w2c)
460 {-# INLINE splitWith #-}
462 -- | The 'groupBy' function is the non-overloaded version of 'group'.
463 groupBy :: (Char -> Char -> Bool) -> ByteString -> [ByteString]
464 groupBy k = L.groupBy (\a b -> k (w2c a) (w2c b))
466 -- | /O(1)/ 'ByteString' index (subscript) operator, starting from 0.
467 index :: ByteString -> Int64 -> Char
468 index = (w2c .) . L.index
471 -- | /O(n)/ The 'elemIndex' function returns the index of the first
472 -- element in the given 'ByteString' which is equal (by memchr) to the
473 -- query element, or 'Nothing' if there is no such element.
474 elemIndex :: Char -> ByteString -> Maybe Int64
475 elemIndex = L.elemIndex . c2w
476 {-# INLINE elemIndex #-}
478 -- | /O(n)/ The 'elemIndices' function extends 'elemIndex', by returning
479 -- the indices of all elements equal to the query element, in ascending order.
480 elemIndices :: Char -> ByteString -> [Int64]
481 elemIndices = L.elemIndices . c2w
482 {-# INLINE elemIndices #-}
484 -- | The 'findIndex' function takes a predicate and a 'ByteString' and
485 -- returns the index of the first element in the ByteString satisfying the predicate.
486 findIndex :: (Char -> Bool) -> ByteString -> Maybe Int64
487 findIndex f = L.findIndex (f . w2c)
488 {-# INLINE findIndex #-}
490 -- | The 'findIndices' function extends 'findIndex', by returning the
491 -- indices of all elements satisfying the predicate, in ascending order.
492 findIndices :: (Char -> Bool) -> ByteString -> [Int64]
493 findIndices f = L.findIndices (f . w2c)
495 -- | count returns the number of times its argument appears in the ByteString
497 -- > count == length . elemIndices
498 -- > count '\n' == length . lines
500 -- But more efficiently than using length on the intermediate list.
501 count :: Char -> ByteString -> Int64
502 count c = L.count (c2w c)
504 -- | /O(n)/ 'elem' is the 'ByteString' membership predicate. This
505 -- implementation uses @memchr(3)@.
506 elem :: Char -> ByteString -> Bool
507 elem c = L.elem (c2w c)
510 -- | /O(n)/ 'notElem' is the inverse of 'elem'
511 notElem :: Char -> ByteString -> Bool
512 notElem c = L.notElem (c2w c)
513 {-# INLINE notElem #-}
515 -- | /O(n)/ 'filter', applied to a predicate and a ByteString,
516 -- returns a ByteString containing those characters that satisfy the
518 filter :: (Char -> Bool) -> ByteString -> ByteString
519 filter f = L.filter (f . w2c)
520 {-# INLINE filter #-}
522 -- | /O(n)/ The 'find' function takes a predicate and a ByteString,
523 -- and returns the first element in matching the predicate, or 'Nothing'
524 -- if there is no such element.
525 find :: (Char -> Bool) -> ByteString -> Maybe Char
526 find f ps = w2c `fmap` L.find (f . w2c) ps
530 -- | /O(n)/ A first order equivalent of /filter . (==)/, for the common
531 -- case of filtering a single Char. It is more efficient to use
532 -- filterChar in this case.
534 -- > filterChar == filter . (==)
536 -- filterChar is around 10x faster, and uses much less space, than its
539 filterChar :: Char -> ByteString -> ByteString
540 filterChar c = L.filterByte (c2w c)
541 {-# INLINE filterChar #-}
543 -- | /O(n)/ A first order equivalent of /filter . (\/=)/, for the common
544 -- case of filtering a single Char out of a list. It is more efficient
545 -- to use /filterNotChar/ in this case.
547 -- > filterNotChar == filter . (/=)
549 -- filterNotChar is around 3x faster, and uses much less space, than its
552 filterNotChar :: Char -> ByteString -> ByteString
553 filterNotChar c = L.filterNotByte (c2w c)
554 {-# INLINE filterNotChar #-}
557 -- | /O(n)/ 'zip' takes two ByteStrings and returns a list of
558 -- corresponding pairs of Chars. If one input ByteString is short,
559 -- excess elements of the longer ByteString are discarded. This is
560 -- equivalent to a pair of 'unpack' operations, and so space
561 -- usage may be large for multi-megabyte ByteStrings
562 zip :: ByteString -> ByteString -> [(Char,Char)]
564 | L.null ps || L.null qs = []
565 | otherwise = (head ps, head qs) : zip (L.tail ps) (L.tail qs)
567 -- | 'zipWith' generalises 'zip' by zipping with the function given as
568 -- the first argument, instead of a tupling function. For example,
569 -- @'zipWith' (+)@ is applied to two ByteStrings to produce the list
570 -- of corresponding sums.
571 zipWith :: (Char -> Char -> a) -> ByteString -> ByteString -> [a]
572 zipWith f = L.zipWith ((. w2c) . f . w2c)
574 -- | 'lines' breaks a ByteString up into a list of ByteStrings at
575 -- newline Chars. The resulting strings do not contain newlines.
577 lines :: ByteString -> [ByteString]
579 lines (LPS (x:xs)) = loop0 x xs
581 -- this is a really performance sensitive function but the
582 -- chunked representation makes the general case a bit expensive
583 -- however assuming a large chunk size and normalish line lengths
584 -- we will find line endings much more frequently than chunk
585 -- endings so it makes sense to optimise for that common case.
586 -- So we partition into two special cases depending on whether we
587 -- are keeping back a list of chunks that will eventually be output
588 -- once we get to the end of the current line.
590 -- the common special case where we have no existing chunks of
592 loop0 :: B.ByteString -> [B.ByteString] -> [ByteString]
595 case B.elemIndex (c2w '\n') ps of
596 Nothing -> case pss of
598 | otherwise -> LPS [ps] : []
600 | B.null ps -> loop0 ps' pss'
601 | otherwise -> loop ps' [ps] pss'
603 Just n | n /= 0 -> LPS [B.unsafeTake n ps]
604 : loop0 (B.unsafeDrop (n+1) ps) pss
605 | otherwise -> loop0 (B.unsafeTail ps) pss
607 -- the general case when we are building a list of chunks that are
608 -- part of the same line
609 loop :: B.ByteString -> [B.ByteString] -> [B.ByteString] -> [ByteString]
612 case B.elemIndex (c2w '\n') ps of
615 [] -> let ps' | B.null ps = P.reverse line
616 | otherwise = P.reverse (ps : line)
617 in ps' `seq` (LPS ps' : [])
620 | B.null ps -> loop ps' line pss'
621 | otherwise -> loop ps' (ps : line) pss'
624 let ps' | n == 0 = P.reverse line
625 | otherwise = P.reverse (B.unsafeTake n ps : line)
626 in ps' `seq` (LPS ps' : loop0 (B.unsafeDrop (n+1) ps) pss)
628 -- | 'unlines' is an inverse operation to 'lines'. It joins lines,
629 -- after appending a terminating newline to each.
630 unlines :: [ByteString] -> ByteString
632 unlines ss = (concat $ List.intersperse nl ss) `append` nl -- half as much space
633 where nl = singleton '\n'
635 -- | 'words' breaks a ByteString up into a list of words, which
636 -- were delimited by Chars representing white space. And
638 -- > tokens isSpace = words
640 words :: ByteString -> [ByteString]
641 words = P.filter (not . L.null) . L.splitWith isSpaceWord8
644 -- | The 'unwords' function is analogous to the 'unlines' function, on words.
645 unwords :: [ByteString] -> ByteString
646 unwords = join (singleton ' ')
647 {-# INLINE unwords #-}
649 -- | readInt reads an Int from the beginning of the ByteString. If
650 -- there is no integer at the beginning of the string, it returns
651 -- Nothing, otherwise it just returns the int read, and the rest of the
653 readInt :: ByteString -> Maybe (Int, ByteString)
654 readInt (LPS []) = Nothing
655 readInt (LPS (x:xs)) =
656 case w2c (B.unsafeHead x) of
657 '-' -> loop True 0 0 (B.unsafeTail x) xs
658 '+' -> loop False 0 0 (B.unsafeTail x) xs
659 _ -> loop False 0 0 x xs
661 where loop :: Bool -> Int -> Int -> B.ByteString -> [B.ByteString] -> Maybe (Int, ByteString)
664 | B.null ps = case pss of
665 [] -> end neg i n ps pss
666 (ps':pss') -> loop neg i n ps' pss'
668 case B.unsafeHead ps of
670 && w <= 0x39 -> loop neg (i+1)
671 (n * 10 + (fromIntegral w - 0x30))
672 (B.unsafeTail ps) pss
673 | otherwise -> end neg i n ps pss
675 end _ 0 _ _ _ = Nothing
676 end neg _ n ps pss = let n' | neg = negate n
678 ps' | B.null ps = pss
680 in n' `seq` ps' `seq` Just $! (n', LPS ps')
683 -- | readInteger reads an Integer from the beginning of the ByteString. If
684 -- there is no integer at the beginning of the string, it returns Nothing,
685 -- otherwise it just returns the int read, and the rest of the string.
686 readInteger :: ByteString -> Maybe (Integer, ByteString)
687 readInteger (LPS []) = Nothing
688 readInteger (LPS (x:xs)) =
689 case w2c (B.unsafeHead x) of
690 '-' -> first (B.unsafeTail x) xs >>= \(n, bs) -> return (-n, bs)
691 '+' -> first (B.unsafeTail x) xs
695 | B.null ps = case pss of
697 (ps':pss') -> first' ps' pss'
698 | otherwise = first' ps pss
700 first' ps pss = case B.unsafeHead ps of
701 w | w >= 0x30 && w <= 0x39 -> Just $
702 loop 1 (fromIntegral w - 0x30) [] (B.unsafeTail ps) pss
703 | otherwise -> Nothing
705 loop :: Int -> Int -> [Integer]
706 -> B.ByteString -> [B.ByteString] -> (Integer, ByteString)
709 | B.null ps = case pss of
710 [] -> combine d acc ns ps pss
711 (ps':pss') -> loop d acc ns ps' pss'
713 case B.unsafeHead ps of
714 w | w >= 0x30 && w <= 0x39 ->
715 if d < 9 then loop (d+1)
716 (10*acc + (fromIntegral w - 0x30))
717 ns (B.unsafeTail ps) pss
718 else loop 1 (fromIntegral w - 0x30)
719 (fromIntegral acc : ns)
720 (B.unsafeTail ps) pss
721 | otherwise -> combine d acc ns ps pss
723 combine _ acc [] ps pss = end (fromIntegral acc) ps pss
724 combine d acc ns ps pss =
725 end (10^d * combine1 1000000000 ns + fromIntegral acc) ps pss
728 combine1 b ns = combine1 (b*b) $ combine2 b ns
730 combine2 b (n:m:ns) = let t = n+m*b in t `seq` (t : combine2 b ns)
733 end n ps pss = let ps' | B.null ps = pss
735 in ps' `seq` (n, LPS ps')
737 -- | Read an entire file /lazily/ into a 'ByteString'. Use 'text mode'
738 -- on Windows to interpret newlines
739 readFile :: FilePath -> IO ByteString
740 readFile f = openFile f ReadMode >>= hGetContents
742 -- | Write a 'ByteString' to a file.
743 writeFile :: FilePath -> ByteString -> IO ()
744 writeFile f txt = bracket (openFile f WriteMode) hClose
745 (\hdl -> hPut hdl txt)
747 -- | Append a 'ByteString' to a file.
748 appendFile :: FilePath -> ByteString -> IO ()
749 appendFile f txt = bracket (openFile f AppendMode) hClose
750 (\hdl -> hPut hdl txt)