eaecb420607201de1c9aae528856872a37777c15
[packages/text.git] / Data / Text / Lazy.hs
1 {-# OPTIONS_GHC -fno-warn-orphans #-}
2 {-# LANGUAGE BangPatterns, MagicHash, CPP #-}
3 #if __GLASGOW_HASKELL__ >= 702
4 {-# LANGUAGE Trustworthy #-}
5 #endif
6 #if __GLASGOW_HASKELL__ >= 708
7 {-# LANGUAGE TypeFamilies #-}
8 #endif
9
10 -- |
11 -- Module : Data.Text.Lazy
12 -- Copyright : (c) 2009, 2010, 2012 Bryan O'Sullivan
13 --
14 -- License : BSD-style
15 -- Maintainer : bos@serpentine.com
16 -- Stability : experimental
17 -- Portability : GHC
18 --
19 -- A time and space-efficient implementation of Unicode text using
20 -- lists of packed arrays.
21 --
22 -- /Note/: Read below the synopsis for important notes on the use of
23 -- this module.
24 --
25 -- The representation used by this module is suitable for high
26 -- performance use and for streaming large quantities of data. It
27 -- provides a means to manipulate a large body of text without
28 -- requiring that the entire content be resident in memory.
29 --
30 -- Some operations, such as 'concat', 'append', 'reverse' and 'cons',
31 -- have better time complexity than their "Data.Text" equivalents, due
32 -- to the underlying representation being a list of chunks. For other
33 -- operations, lazy 'Text's are usually within a few percent of strict
34 -- ones, but often with better heap usage if used in a streaming
35 -- fashion. For data larger than available memory, or if you have
36 -- tight memory constraints, this module will be the only option.
37 --
38 -- This module is intended to be imported @qualified@, to avoid name
39 -- clashes with "Prelude" functions. eg.
40 --
41 -- > import qualified Data.Text.Lazy as L
42
43 module Data.Text.Lazy
44 (
45 -- * Fusion
46 -- $fusion
47
48 -- * Acceptable data
49 -- $replacement
50
51 -- * Types
52 Text
53
54 -- * Creation and elimination
55 , pack
56 , unpack
57 , singleton
58 , empty
59 , fromChunks
60 , toChunks
61 , toStrict
62 , fromStrict
63 , foldrChunks
64 , foldlChunks
65
66 -- * Basic interface
67 , cons
68 , snoc
69 , append
70 , uncons
71 , head
72 , last
73 , tail
74 , init
75 , null
76 , length
77 , compareLength
78
79 -- * Transformations
80 , map
81 , intercalate
82 , intersperse
83 , transpose
84 , reverse
85 , replace
86
87 -- ** Case conversion
88 -- $case
89 , toCaseFold
90 , toLower
91 , toUpper
92 , toTitle
93
94 -- ** Justification
95 , justifyLeft
96 , justifyRight
97 , center
98
99 -- * Folds
100 , foldl
101 , foldl'
102 , foldl1
103 , foldl1'
104 , foldr
105 , foldr1
106
107 -- ** Special folds
108 , concat
109 , concatMap
110 , any
111 , all
112 , maximum
113 , minimum
114
115 -- * Construction
116
117 -- ** Scans
118 , scanl
119 , scanl1
120 , scanr
121 , scanr1
122
123 -- ** Accumulating maps
124 , mapAccumL
125 , mapAccumR
126
127 -- ** Generation and unfolding
128 , replicate
129 , unfoldr
130 , unfoldrN
131
132 -- * Substrings
133
134 -- ** Breaking strings
135 , take
136 , takeEnd
137 , drop
138 , dropEnd
139 , takeWhile
140 , dropWhile
141 , dropWhileEnd
142 , dropAround
143 , strip
144 , stripStart
145 , stripEnd
146 , splitAt
147 , span
148 , breakOn
149 , breakOnEnd
150 , break
151 , group
152 , groupBy
153 , inits
154 , tails
155
156 -- ** Breaking into many substrings
157 -- $split
158 , splitOn
159 , split
160 , chunksOf
161 -- , breakSubstring
162
163 -- ** Breaking into lines and words
164 , lines
165 , words
166 , unlines
167 , unwords
168
169 -- * Predicates
170 , isPrefixOf
171 , isSuffixOf
172 , isInfixOf
173
174 -- ** View patterns
175 , stripPrefix
176 , stripSuffix
177 , commonPrefixes
178
179 -- * Searching
180 , filter
181 , find
182 , breakOnAll
183 , partition
184
185 -- , findSubstring
186
187 -- * Indexing
188 , index
189 , count
190
191 -- * Zipping and unzipping
192 , zip
193 , zipWith
194
195 -- -* Ordered text
196 -- , sort
197 ) where
198
199 import Prelude (Char, Bool(..), Maybe(..), String,
200 Eq(..), Ord(..), Ordering(..), Read(..), Show(..),
201 (&&), (||), (+), (-), (.), ($), (++),
202 error, flip, fmap, fromIntegral, not, otherwise, quot)
203 import qualified Prelude as P
204 #if defined(HAVE_DEEPSEQ)
205 import Control.DeepSeq (NFData(..))
206 #endif
207 import Data.Int (Int64)
208 import qualified Data.List as L
209 import Data.Char (isSpace)
210 import Data.Data (Data(gfoldl, toConstr, gunfold, dataTypeOf))
211 import Data.Data (mkNoRepType)
212 import Data.Monoid (Monoid(..))
213 import Data.String (IsString(..))
214 import qualified Data.Text as T
215 import qualified Data.Text.Internal as T
216 import qualified Data.Text.Internal.Fusion.Common as S
217 import qualified Data.Text.Unsafe as T
218 import qualified Data.Text.Internal.Lazy.Fusion as S
219 import Data.Text.Internal.Fusion.Types (PairS(..))
220 import Data.Text.Internal.Lazy.Fusion (stream, unstream)
221 import Data.Text.Internal.Lazy (Text(..), chunk, empty, foldlChunks, foldrChunks)
222 import Data.Text.Internal (firstf, safe, text)
223 import qualified Data.Text.Internal.Functions as F
224 import Data.Text.Internal.Lazy.Search (indices)
225 #if __GLASGOW_HASKELL__ >= 702
226 import qualified GHC.CString as GHC
227 #else
228 import qualified GHC.Base as GHC
229 #endif
230 #if __GLASGOW_HASKELL__ >= 708
231 import qualified GHC.Exts as Exts
232 #endif
233 import GHC.Prim (Addr#)
234
235 -- $fusion
236 --
237 -- Most of the functions in this module are subject to /fusion/,
238 -- meaning that a pipeline of such functions will usually allocate at
239 -- most one 'Text' value.
240 --
241 -- As an example, consider the following pipeline:
242 --
243 -- > import Data.Text.Lazy as T
244 -- > import Data.Text.Lazy.Encoding as E
245 -- > import Data.ByteString.Lazy (ByteString)
246 -- >
247 -- > countChars :: ByteString -> Int
248 -- > countChars = T.length . T.toUpper . E.decodeUtf8
249 --
250 -- From the type signatures involved, this looks like it should
251 -- allocate one 'ByteString' value, and two 'Text' values. However,
252 -- when a module is compiled with optimisation enabled under GHC, the
253 -- two intermediate 'Text' values will be optimised away, and the
254 -- function will be compiled down to a single loop over the source
255 -- 'ByteString'.
256 --
257 -- Functions that can be fused by the compiler are documented with the
258 -- phrase \"Subject to fusion\".
259
260 -- $replacement
261 --
262 -- A 'Text' value is a sequence of Unicode scalar values, as defined
263 -- in §3.9, definition D76 of the Unicode 5.2 standard:
264 -- <http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#page=35>. As
265 -- such, a 'Text' cannot contain values in the range U+D800 to U+DFFF
266 -- inclusive. Haskell implementations admit all Unicode code points
267 -- (&#xa7;3.4, definition D10) as 'Char' values, including code points
268 -- from this invalid range. This means that there are some 'Char'
269 -- values that are not valid Unicode scalar values, and the functions
270 -- in this module must handle those cases.
271 --
272 -- Within this module, many functions construct a 'Text' from one or
273 -- more 'Char' values. Those functions will substitute 'Char' values
274 -- that are not valid Unicode scalar values with the replacement
275 -- character \"&#xfffd;\" (U+FFFD). Functions that perform this
276 -- inspection and replacement are documented with the phrase
277 -- \"Performs replacement on invalid scalar values\".
278 --
279 -- (One reason for this policy of replacement is that internally, a
280 -- 'Text' value is represented as packed UTF-16 data. Values in the
281 -- range U+D800 through U+DFFF are used by UTF-16 to denote surrogate
282 -- code points, and so cannot be represented. The functions replace
283 -- invalid scalar values, instead of dropping them, as a security
284 -- measure. For details, see Unicode Technical Report 36, &#xa7;3.5:
285 -- <http://unicode.org/reports/tr36#Deletion_of_Noncharacters>)
286
287 equal :: Text -> Text -> Bool
288 equal Empty Empty = True
289 equal Empty _ = False
290 equal _ Empty = False
291 equal (Chunk a as) (Chunk b bs) =
292 case compare lenA lenB of
293 LT -> a == (T.takeWord16 lenA b) &&
294 as `equal` Chunk (T.dropWord16 lenA b) bs
295 EQ -> a == b && as `equal` bs
296 GT -> T.takeWord16 lenB a == b &&
297 Chunk (T.dropWord16 lenB a) as `equal` bs
298 where lenA = T.lengthWord16 a
299 lenB = T.lengthWord16 b
300
301 instance Eq Text where
302 (==) = equal
303 {-# INLINE (==) #-}
304
305 instance Ord Text where
306 compare = compareText
307
308 compareText :: Text -> Text -> Ordering
309 compareText Empty Empty = EQ
310 compareText Empty _ = LT
311 compareText _ Empty = GT
312 compareText (Chunk a0 as) (Chunk b0 bs) = outer a0 b0
313 where
314 outer ta@(T.Text arrA offA lenA) tb@(T.Text arrB offB lenB) = go 0 0
315 where
316 go !i !j
317 | i >= lenA = compareText as (chunk (T.Text arrB (offB+j) (lenB-j)) bs)
318 | j >= lenB = compareText (chunk (T.Text arrA (offA+i) (lenA-i)) as) bs
319 | a < b = LT
320 | a > b = GT
321 | otherwise = go (i+di) (j+dj)
322 where T.Iter a di = T.iter ta i
323 T.Iter b dj = T.iter tb j
324
325 instance Show Text where
326 showsPrec p ps r = showsPrec p (unpack ps) r
327
328 instance Read Text where
329 readsPrec p str = [(pack x,y) | (x,y) <- readsPrec p str]
330
331 instance Monoid Text where
332 mempty = empty
333 mappend = append
334 mconcat = concat
335
336 instance IsString Text where
337 fromString = pack
338
339 #if __GLASGOW_HASKELL__ >= 708
340 instance Exts.IsList Text where
341 type Item Text = Char
342 fromList = pack
343 toList = unpack
344 #endif
345
346 #if defined(HAVE_DEEPSEQ)
347 instance NFData Text where
348 rnf Empty = ()
349 rnf (Chunk _ ts) = rnf ts
350 #endif
351
352 instance Data Text where
353 gfoldl f z txt = z pack `f` (unpack txt)
354 toConstr _ = error "Data.Text.Lazy.Text.toConstr"
355 gunfold _ _ = error "Data.Text.Lazy.Text.gunfold"
356 dataTypeOf _ = mkNoRepType "Data.Text.Lazy.Text"
357
358 -- | /O(n)/ Convert a 'String' into a 'Text'.
359 --
360 -- Subject to fusion. Performs replacement on invalid scalar values.
361 pack :: String -> Text
362 pack = unstream . S.streamList . L.map safe
363 {-# INLINE [1] pack #-}
364
365 -- | /O(n)/ Convert a 'Text' into a 'String'.
366 -- Subject to fusion.
367 unpack :: Text -> String
368 unpack t = S.unstreamList (stream t)
369 {-# INLINE [1] unpack #-}
370
371 -- | /O(n)/ Convert a literal string into a Text.
372 unpackCString# :: Addr# -> Text
373 unpackCString# addr# = unstream (S.streamCString# addr#)
374 {-# NOINLINE unpackCString# #-}
375
376 {-# RULES "TEXT literal" forall a.
377 unstream (S.streamList (L.map safe (GHC.unpackCString# a)))
378 = unpackCString# a #-}
379
380 {-# RULES "TEXT literal UTF8" forall a.
381 unstream (S.streamList (L.map safe (GHC.unpackCStringUtf8# a)))
382 = unpackCString# a #-}
383
384 {-# RULES "LAZY TEXT empty literal"
385 unstream (S.streamList (L.map safe []))
386 = Empty #-}
387
388 {-# RULES "LAZY TEXT empty literal" forall a.
389 unstream (S.streamList (L.map safe [a]))
390 = Chunk (T.singleton a) Empty #-}
391
392 -- | /O(1)/ Convert a character into a Text. Subject to fusion.
393 -- Performs replacement on invalid scalar values.
394 singleton :: Char -> Text
395 singleton c = Chunk (T.singleton c) Empty
396 {-# INLINE [1] singleton #-}
397
398 {-# RULES
399 "LAZY TEXT singleton -> fused" [~1] forall c.
400 singleton c = unstream (S.singleton c)
401 "LAZY TEXT singleton -> unfused" [1] forall c.
402 unstream (S.singleton c) = singleton c
403 #-}
404
405 -- | /O(c)/ Convert a list of strict 'T.Text's into a lazy 'Text'.
406 fromChunks :: [T.Text] -> Text
407 fromChunks cs = L.foldr chunk Empty cs
408
409 -- | /O(n)/ Convert a lazy 'Text' into a list of strict 'T.Text's.
410 toChunks :: Text -> [T.Text]
411 toChunks cs = foldrChunks (:) [] cs
412
413 -- | /O(n)/ Convert a lazy 'Text' into a strict 'T.Text'.
414 toStrict :: Text -> T.Text
415 toStrict t = T.concat (toChunks t)
416 {-# INLINE [1] toStrict #-}
417
418 -- | /O(c)/ Convert a strict 'T.Text' into a lazy 'Text'.
419 fromStrict :: T.Text -> Text
420 fromStrict t = chunk t Empty
421 {-# INLINE [1] fromStrict #-}
422
423 -- -----------------------------------------------------------------------------
424 -- * Basic functions
425
426 -- | /O(n)/ Adds a character to the front of a 'Text'. This function
427 -- is more costly than its 'List' counterpart because it requires
428 -- copying a new array. Subject to fusion.
429 cons :: Char -> Text -> Text
430 cons c t = Chunk (T.singleton c) t
431 {-# INLINE [1] cons #-}
432
433 infixr 5 `cons`
434
435 {-# RULES
436 "LAZY TEXT cons -> fused" [~1] forall c t.
437 cons c t = unstream (S.cons c (stream t))
438 "LAZY TEXT cons -> unfused" [1] forall c t.
439 unstream (S.cons c (stream t)) = cons c t
440 #-}
441
442 -- | /O(n)/ Adds a character to the end of a 'Text'. This copies the
443 -- entire array in the process, unless fused. Subject to fusion.
444 snoc :: Text -> Char -> Text
445 snoc t c = foldrChunks Chunk (singleton c) t
446 {-# INLINE [1] snoc #-}
447
448 {-# RULES
449 "LAZY TEXT snoc -> fused" [~1] forall t c.
450 snoc t c = unstream (S.snoc (stream t) c)
451 "LAZY TEXT snoc -> unfused" [1] forall t c.
452 unstream (S.snoc (stream t) c) = snoc t c
453 #-}
454
455 -- | /O(n\/c)/ Appends one 'Text' to another. Subject to fusion.
456 append :: Text -> Text -> Text
457 append xs ys = foldrChunks Chunk ys xs
458 {-# INLINE [1] append #-}
459
460 {-# RULES
461 "LAZY TEXT append -> fused" [~1] forall t1 t2.
462 append t1 t2 = unstream (S.append (stream t1) (stream t2))
463 "LAZY TEXT append -> unfused" [1] forall t1 t2.
464 unstream (S.append (stream t1) (stream t2)) = append t1 t2
465 #-}
466
467 -- | /O(1)/ Returns the first character and rest of a 'Text', or
468 -- 'Nothing' if empty. Subject to fusion.
469 uncons :: Text -> Maybe (Char, Text)
470 uncons Empty = Nothing
471 uncons (Chunk t ts) = Just (T.unsafeHead t, ts')
472 where ts' | T.compareLength t 1 == EQ = ts
473 | otherwise = Chunk (T.unsafeTail t) ts
474 {-# INLINE uncons #-}
475
476 -- | /O(1)/ Returns the first character of a 'Text', which must be
477 -- non-empty. Subject to fusion.
478 head :: Text -> Char
479 head t = S.head (stream t)
480 {-# INLINE head #-}
481
482 -- | /O(1)/ Returns all characters after the head of a 'Text', which
483 -- must be non-empty. Subject to fusion.
484 tail :: Text -> Text
485 tail (Chunk t ts) = chunk (T.tail t) ts
486 tail Empty = emptyError "tail"
487 {-# INLINE [1] tail #-}
488
489 {-# RULES
490 "LAZY TEXT tail -> fused" [~1] forall t.
491 tail t = unstream (S.tail (stream t))
492 "LAZY TEXT tail -> unfused" [1] forall t.
493 unstream (S.tail (stream t)) = tail t
494 #-}
495
496 -- | /O(1)/ Returns all but the last character of a 'Text', which must
497 -- be non-empty. Subject to fusion.
498 init :: Text -> Text
499 init (Chunk t0 ts0) = go t0 ts0
500 where go t (Chunk t' ts) = Chunk t (go t' ts)
501 go t Empty = chunk (T.init t) Empty
502 init Empty = emptyError "init"
503 {-# INLINE [1] init #-}
504
505 {-# RULES
506 "LAZY TEXT init -> fused" [~1] forall t.
507 init t = unstream (S.init (stream t))
508 "LAZY TEXT init -> unfused" [1] forall t.
509 unstream (S.init (stream t)) = init t
510 #-}
511
512 -- | /O(1)/ Tests whether a 'Text' is empty or not. Subject to
513 -- fusion.
514 null :: Text -> Bool
515 null Empty = True
516 null _ = False
517 {-# INLINE [1] null #-}
518
519 {-# RULES
520 "LAZY TEXT null -> fused" [~1] forall t.
521 null t = S.null (stream t)
522 "LAZY TEXT null -> unfused" [1] forall t.
523 S.null (stream t) = null t
524 #-}
525
526 -- | /O(1)/ Tests whether a 'Text' contains exactly one character.
527 -- Subject to fusion.
528 isSingleton :: Text -> Bool
529 isSingleton = S.isSingleton . stream
530 {-# INLINE isSingleton #-}
531
532 -- | /O(1)/ Returns the last character of a 'Text', which must be
533 -- non-empty. Subject to fusion.
534 last :: Text -> Char
535 last Empty = emptyError "last"
536 last (Chunk t ts) = go t ts
537 where go _ (Chunk t' ts') = go t' ts'
538 go t' Empty = T.last t'
539 {-# INLINE [1] last #-}
540
541 {-# RULES
542 "LAZY TEXT last -> fused" [~1] forall t.
543 last t = S.last (stream t)
544 "LAZY TEXT last -> unfused" [1] forall t.
545 S.last (stream t) = last t
546 #-}
547
548 -- | /O(n)/ Returns the number of characters in a 'Text'.
549 -- Subject to fusion.
550 length :: Text -> Int64
551 length = foldlChunks go 0
552 where go l t = l + fromIntegral (T.length t)
553 {-# INLINE [1] length #-}
554
555 {-# RULES
556 "LAZY TEXT length -> fused" [~1] forall t.
557 length t = S.length (stream t)
558 "LAZY TEXT length -> unfused" [1] forall t.
559 S.length (stream t) = length t
560 #-}
561
562 -- | /O(n)/ Compare the count of characters in a 'Text' to a number.
563 -- Subject to fusion.
564 --
565 -- This function gives the same answer as comparing against the result
566 -- of 'length', but can short circuit if the count of characters is
567 -- greater than the number, and hence be more efficient.
568 compareLength :: Text -> Int64 -> Ordering
569 compareLength t n = S.compareLengthI (stream t) n
570 {-# INLINE [1] compareLength #-}
571
572 -- We don't apply those otherwise appealing length-to-compareLength
573 -- rewrite rules here, because they can change the strictness
574 -- properties of code.
575
576 -- | /O(n)/ 'map' @f@ @t@ is the 'Text' obtained by applying @f@ to
577 -- each element of @t@. Subject to fusion. Performs replacement on
578 -- invalid scalar values.
579 map :: (Char -> Char) -> Text -> Text
580 map f t = unstream (S.map (safe . f) (stream t))
581 {-# INLINE [1] map #-}
582
583 -- | /O(n)/ The 'intercalate' function takes a 'Text' and a list of
584 -- 'Text's and concatenates the list after interspersing the first
585 -- argument between each element of the list.
586 intercalate :: Text -> [Text] -> Text
587 intercalate t = concat . (F.intersperse t)
588 {-# INLINE intercalate #-}
589
590 -- | /O(n)/ The 'intersperse' function takes a character and places it
591 -- between the characters of a 'Text'. Subject to fusion. Performs
592 -- replacement on invalid scalar values.
593 intersperse :: Char -> Text -> Text
594 intersperse c t = unstream (S.intersperse (safe c) (stream t))
595 {-# INLINE intersperse #-}
596
597 -- | /O(n)/ Left-justify a string to the given length, using the
598 -- specified fill character on the right. Subject to fusion. Performs
599 -- replacement on invalid scalar values.
600 --
601 -- Examples:
602 --
603 -- > justifyLeft 7 'x' "foo" == "fooxxxx"
604 -- > justifyLeft 3 'x' "foobar" == "foobar"
605 justifyLeft :: Int64 -> Char -> Text -> Text
606 justifyLeft k c t
607 | len >= k = t
608 | otherwise = t `append` replicateChar (k-len) c
609 where len = length t
610 {-# INLINE [1] justifyLeft #-}
611
612 {-# RULES
613 "LAZY TEXT justifyLeft -> fused" [~1] forall k c t.
614 justifyLeft k c t = unstream (S.justifyLeftI k c (stream t))
615 "LAZY TEXT justifyLeft -> unfused" [1] forall k c t.
616 unstream (S.justifyLeftI k c (stream t)) = justifyLeft k c t
617 #-}
618
619 -- | /O(n)/ Right-justify a string to the given length, using the
620 -- specified fill character on the left. Performs replacement on
621 -- invalid scalar values.
622 --
623 -- Examples:
624 --
625 -- > justifyRight 7 'x' "bar" == "xxxxbar"
626 -- > justifyRight 3 'x' "foobar" == "foobar"
627 justifyRight :: Int64 -> Char -> Text -> Text
628 justifyRight k c t
629 | len >= k = t
630 | otherwise = replicateChar (k-len) c `append` t
631 where len = length t
632 {-# INLINE justifyRight #-}
633
634 -- | /O(n)/ Center a string to the given length, using the specified
635 -- fill character on either side. Performs replacement on invalid
636 -- scalar values.
637 --
638 -- Examples:
639 --
640 -- > center 8 'x' "HS" = "xxxHSxxx"
641 center :: Int64 -> Char -> Text -> Text
642 center k c t
643 | len >= k = t
644 | otherwise = replicateChar l c `append` t `append` replicateChar r c
645 where len = length t
646 d = k - len
647 r = d `quot` 2
648 l = d - r
649 {-# INLINE center #-}
650
651 -- | /O(n)/ The 'transpose' function transposes the rows and columns
652 -- of its 'Text' argument. Note that this function uses 'pack',
653 -- 'unpack', and the list version of transpose, and is thus not very
654 -- efficient.
655 transpose :: [Text] -> [Text]
656 transpose ts = L.map (\ss -> Chunk (T.pack ss) Empty)
657 (L.transpose (L.map unpack ts))
658 -- TODO: make this fast
659
660 -- | /O(n)/ 'reverse' @t@ returns the elements of @t@ in reverse order.
661 reverse :: Text -> Text
662 reverse = rev Empty
663 where rev a Empty = a
664 rev a (Chunk t ts) = rev (Chunk (T.reverse t) a) ts
665
666 -- | /O(m+n)/ Replace every occurrence of one substring with another.
667 --
668 -- In (unlikely) bad cases, this function's time complexity degrades
669 -- towards /O(n*m)/.
670 replace :: Text -- ^ Text to search for
671 -> Text -- ^ Replacement text
672 -> Text -- ^ Input text
673 -> Text
674 replace s d = intercalate d . splitOn s
675 {-# INLINE replace #-}
676
677 -- ----------------------------------------------------------------------------
678 -- ** Case conversions (folds)
679
680 -- $case
681 --
682 -- With Unicode text, it is incorrect to use combinators like @map
683 -- toUpper@ to case convert each character of a string individually.
684 -- Instead, use the whole-string case conversion functions from this
685 -- module. For correctness in different writing systems, these
686 -- functions may map one input character to two or three output
687 -- characters.
688
689 -- | /O(n)/ Convert a string to folded case. Subject to fusion.
690 --
691 -- This function is mainly useful for performing caseless (or case
692 -- insensitive) string comparisons.
693 --
694 -- A string @x@ is a caseless match for a string @y@ if and only if:
695 --
696 -- @toCaseFold x == toCaseFold y@
697 --
698 -- The result string may be longer than the input string, and may
699 -- differ from applying 'toLower' to the input string. For instance,
700 -- the Armenian small ligature men now (U+FB13) is case folded to the
701 -- bigram men now (U+0574 U+0576), while the micro sign (U+00B5) is
702 -- case folded to the Greek small letter letter mu (U+03BC) instead of
703 -- itself.
704 toCaseFold :: Text -> Text
705 toCaseFold t = unstream (S.toCaseFold (stream t))
706 {-# INLINE [0] toCaseFold #-}
707
708 -- | /O(n)/ Convert a string to lower case, using simple case
709 -- conversion. Subject to fusion.
710 --
711 -- The result string may be longer than the input string. For
712 -- instance, the Latin capital letter I with dot above (U+0130) maps
713 -- to the sequence Latin small letter i (U+0069) followed by combining
714 -- dot above (U+0307).
715 toLower :: Text -> Text
716 toLower t = unstream (S.toLower (stream t))
717 {-# INLINE toLower #-}
718
719 -- | /O(n)/ Convert a string to upper case, using simple case
720 -- conversion. Subject to fusion.
721 --
722 -- The result string may be longer than the input string. For
723 -- instance, the German eszett (U+00DF) maps to the two-letter
724 -- sequence SS.
725 toUpper :: Text -> Text
726 toUpper t = unstream (S.toUpper (stream t))
727 {-# INLINE toUpper #-}
728
729
730 -- | /O(n)/ Convert a string to title case, using simple case
731 -- conversion. Subject to fusion.
732 --
733 -- The first letter of the input is converted to title case, as is
734 -- every subsequent letter that immediately follows a non-letter.
735 -- Every letter that immediately follows another letter is converted
736 -- to lower case.
737 --
738 -- The result string may be longer than the input string. For example,
739 -- the Latin small ligature &#xfb02; (U+FB02) is converted to the
740 -- sequence Latin capital letter F (U+0046) followed by Latin small
741 -- letter l (U+006C).
742 --
743 -- /Note/: this function does not take language or culture specific
744 -- rules into account. For instance, in English, different style
745 -- guides disagree on whether the book name \"The Hill of the Red
746 -- Fox\" is correctly title cased&#x2014;but this function will
747 -- capitalize /every/ word.
748 toTitle :: Text -> Text
749 toTitle t = unstream (S.toTitle (stream t))
750 {-# INLINE toTitle #-}
751
752 -- | /O(n)/ 'foldl', applied to a binary operator, a starting value
753 -- (typically the left-identity of the operator), and a 'Text',
754 -- reduces the 'Text' using the binary operator, from left to right.
755 -- Subject to fusion.
756 foldl :: (a -> Char -> a) -> a -> Text -> a
757 foldl f z t = S.foldl f z (stream t)
758 {-# INLINE foldl #-}
759
760 -- | /O(n)/ A strict version of 'foldl'.
761 -- Subject to fusion.
762 foldl' :: (a -> Char -> a) -> a -> Text -> a
763 foldl' f z t = S.foldl' f z (stream t)
764 {-# INLINE foldl' #-}
765
766 -- | /O(n)/ A variant of 'foldl' that has no starting value argument,
767 -- and thus must be applied to a non-empty 'Text'. Subject to fusion.
768 foldl1 :: (Char -> Char -> Char) -> Text -> Char
769 foldl1 f t = S.foldl1 f (stream t)
770 {-# INLINE foldl1 #-}
771
772 -- | /O(n)/ A strict version of 'foldl1'. Subject to fusion.
773 foldl1' :: (Char -> Char -> Char) -> Text -> Char
774 foldl1' f t = S.foldl1' f (stream t)
775 {-# INLINE foldl1' #-}
776
777 -- | /O(n)/ 'foldr', applied to a binary operator, a starting value
778 -- (typically the right-identity of the operator), and a 'Text',
779 -- reduces the 'Text' using the binary operator, from right to left.
780 -- Subject to fusion.
781 foldr :: (Char -> a -> a) -> a -> Text -> a
782 foldr f z t = S.foldr f z (stream t)
783 {-# INLINE foldr #-}
784
785 -- | /O(n)/ A variant of 'foldr' that has no starting value argument,
786 -- and thus must be applied to a non-empty 'Text'. Subject to
787 -- fusion.
788 foldr1 :: (Char -> Char -> Char) -> Text -> Char
789 foldr1 f t = S.foldr1 f (stream t)
790 {-# INLINE foldr1 #-}
791
792 -- | /O(n)/ Concatenate a list of 'Text's.
793 concat :: [Text] -> Text
794 concat = to
795 where
796 go Empty css = to css
797 go (Chunk c cs) css = Chunk c (go cs css)
798 to [] = Empty
799 to (cs:css) = go cs css
800 {-# INLINE concat #-}
801
802 -- | /O(n)/ Map a function over a 'Text' that results in a 'Text', and
803 -- concatenate the results.
804 concatMap :: (Char -> Text) -> Text -> Text
805 concatMap f = concat . foldr ((:) . f) []
806 {-# INLINE concatMap #-}
807
808 -- | /O(n)/ 'any' @p@ @t@ determines whether any character in the
809 -- 'Text' @t@ satisifes the predicate @p@. Subject to fusion.
810 any :: (Char -> Bool) -> Text -> Bool
811 any p t = S.any p (stream t)
812 {-# INLINE any #-}
813
814 -- | /O(n)/ 'all' @p@ @t@ determines whether all characters in the
815 -- 'Text' @t@ satisify the predicate @p@. Subject to fusion.
816 all :: (Char -> Bool) -> Text -> Bool
817 all p t = S.all p (stream t)
818 {-# INLINE all #-}
819
820 -- | /O(n)/ 'maximum' returns the maximum value from a 'Text', which
821 -- must be non-empty. Subject to fusion.
822 maximum :: Text -> Char
823 maximum t = S.maximum (stream t)
824 {-# INLINE maximum #-}
825
826 -- | /O(n)/ 'minimum' returns the minimum value from a 'Text', which
827 -- must be non-empty. Subject to fusion.
828 minimum :: Text -> Char
829 minimum t = S.minimum (stream t)
830 {-# INLINE minimum #-}
831
832 -- | /O(n)/ 'scanl' is similar to 'foldl', but returns a list of
833 -- successive reduced values from the left. Subject to fusion.
834 -- Performs replacement on invalid scalar values.
835 --
836 -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
837 --
838 -- Note that
839 --
840 -- > last (scanl f z xs) == foldl f z xs.
841 scanl :: (Char -> Char -> Char) -> Char -> Text -> Text
842 scanl f z t = unstream (S.scanl g z (stream t))
843 where g a b = safe (f a b)
844 {-# INLINE scanl #-}
845
846 -- | /O(n)/ 'scanl1' is a variant of 'scanl' that has no starting
847 -- value argument. Subject to fusion. Performs replacement on
848 -- invalid scalar values.
849 --
850 -- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
851 scanl1 :: (Char -> Char -> Char) -> Text -> Text
852 scanl1 f t0 = case uncons t0 of
853 Nothing -> empty
854 Just (t,ts) -> scanl f t ts
855 {-# INLINE scanl1 #-}
856
857 -- | /O(n)/ 'scanr' is the right-to-left dual of 'scanl'. Performs
858 -- replacement on invalid scalar values.
859 --
860 -- > scanr f v == reverse . scanl (flip f) v . reverse
861 scanr :: (Char -> Char -> Char) -> Char -> Text -> Text
862 scanr f v = reverse . scanl g v . reverse
863 where g a b = safe (f b a)
864
865 -- | /O(n)/ 'scanr1' is a variant of 'scanr' that has no starting
866 -- value argument. Performs replacement on invalid scalar values.
867 scanr1 :: (Char -> Char -> Char) -> Text -> Text
868 scanr1 f t | null t = empty
869 | otherwise = scanr f (last t) (init t)
870
871 -- | /O(n)/ Like a combination of 'map' and 'foldl''. Applies a
872 -- function to each element of a 'Text', passing an accumulating
873 -- parameter from left to right, and returns a final 'Text'. Performs
874 -- replacement on invalid scalar values.
875 mapAccumL :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
876 mapAccumL f = go
877 where
878 go z (Chunk c cs) = (z'', Chunk c' cs')
879 where (z', c') = T.mapAccumL f z c
880 (z'', cs') = go z' cs
881 go z Empty = (z, Empty)
882 {-# INLINE mapAccumL #-}
883
884 -- | The 'mapAccumR' function behaves like a combination of 'map' and
885 -- a strict 'foldr'; it applies a function to each element of a
886 -- 'Text', passing an accumulating parameter from right to left, and
887 -- returning a final value of this accumulator together with the new
888 -- 'Text'. Performs replacement on invalid scalar values.
889 mapAccumR :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
890 mapAccumR f = go
891 where
892 go z (Chunk c cs) = (z'', Chunk c' cs')
893 where (z'', c') = T.mapAccumR f z' c
894 (z', cs') = go z cs
895 go z Empty = (z, Empty)
896 {-# INLINE mapAccumR #-}
897
898 -- | /O(n*m)/ 'replicate' @n@ @t@ is a 'Text' consisting of the input
899 -- @t@ repeated @n@ times.
900 replicate :: Int64 -> Text -> Text
901 replicate n t
902 | null t || n <= 0 = empty
903 | isSingleton t = replicateChar n (head t)
904 | otherwise = concat (rep 0)
905 where rep !i | i >= n = []
906 | otherwise = t : rep (i+1)
907 {-# INLINE [1] replicate #-}
908
909 -- | /O(n)/ 'replicateChar' @n@ @c@ is a 'Text' of length @n@ with @c@ the
910 -- value of every element. Subject to fusion.
911 replicateChar :: Int64 -> Char -> Text
912 replicateChar n c = unstream (S.replicateCharI n (safe c))
913 {-# INLINE replicateChar #-}
914
915 {-# RULES
916 "LAZY TEXT replicate/singleton -> replicateChar" [~1] forall n c.
917 replicate n (singleton c) = replicateChar n c
918 #-}
919
920 -- | /O(n)/, where @n@ is the length of the result. The 'unfoldr'
921 -- function is analogous to the List 'L.unfoldr'. 'unfoldr' builds a
922 -- 'Text' from a seed value. The function takes the element and
923 -- returns 'Nothing' if it is done producing the 'Text', otherwise
924 -- 'Just' @(a,b)@. In this case, @a@ is the next 'Char' in the
925 -- string, and @b@ is the seed value for further production. Performs
926 -- replacement on invalid scalar values.
927 unfoldr :: (a -> Maybe (Char,a)) -> a -> Text
928 unfoldr f s = unstream (S.unfoldr (firstf safe . f) s)
929 {-# INLINE unfoldr #-}
930
931 -- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a 'Text' from a seed
932 -- value. However, the length of the result should be limited by the
933 -- first argument to 'unfoldrN'. This function is more efficient than
934 -- 'unfoldr' when the maximum length of the result is known and
935 -- correct, otherwise its performance is similar to 'unfoldr'.
936 -- Performs replacement on invalid scalar values.
937 unfoldrN :: Int64 -> (a -> Maybe (Char,a)) -> a -> Text
938 unfoldrN n f s = unstream (S.unfoldrN n (firstf safe . f) s)
939 {-# INLINE unfoldrN #-}
940
941 -- | /O(n)/ 'take' @n@, applied to a 'Text', returns the prefix of the
942 -- 'Text' of length @n@, or the 'Text' itself if @n@ is greater than
943 -- the length of the Text. Subject to fusion.
944 take :: Int64 -> Text -> Text
945 take i _ | i <= 0 = Empty
946 take i t0 = take' i t0
947 where take' 0 _ = Empty
948 take' _ Empty = Empty
949 take' n (Chunk t ts)
950 | n < len = Chunk (T.take (fromIntegral n) t) Empty
951 | otherwise = Chunk t (take' (n - len) ts)
952 where len = fromIntegral (T.length t)
953 {-# INLINE [1] take #-}
954
955 {-# RULES
956 "LAZY TEXT take -> fused" [~1] forall n t.
957 take n t = unstream (S.take n (stream t))
958 "LAZY TEXT take -> unfused" [1] forall n t.
959 unstream (S.take n (stream t)) = take n t
960 #-}
961
962 -- | /O(n)/ 'takeEnd' @n@ @t@ returns the suffix remaining after
963 -- taking @n@ characters from the end of @t@.
964 --
965 -- Examples:
966 --
967 -- > takeEnd 3 "foobar" == "bar"
968 takeEnd :: Int64 -> Text -> Text
969 takeEnd n t0
970 | n <= 0 = empty
971 | otherwise = takeChunk n empty . L.reverse . toChunks $ t0
972 where takeChunk _ acc [] = acc
973 takeChunk i acc (t:ts)
974 | i <= l = chunk (T.takeEnd (fromIntegral i) t) acc
975 | otherwise = takeChunk (i-l) (Chunk t acc) ts
976 where l = fromIntegral (T.length t)
977
978 -- | /O(n)/ 'drop' @n@, applied to a 'Text', returns the suffix of the
979 -- 'Text' after the first @n@ characters, or the empty 'Text' if @n@
980 -- is greater than the length of the 'Text'. Subject to fusion.
981 drop :: Int64 -> Text -> Text
982 drop i t0
983 | i <= 0 = t0
984 | otherwise = drop' i t0
985 where drop' 0 ts = ts
986 drop' _ Empty = Empty
987 drop' n (Chunk t ts)
988 | n < len = Chunk (T.drop (fromIntegral n) t) ts
989 | otherwise = drop' (n - len) ts
990 where len = fromIntegral (T.length t)
991 {-# INLINE [1] drop #-}
992
993 {-# RULES
994 "LAZY TEXT drop -> fused" [~1] forall n t.
995 drop n t = unstream (S.drop n (stream t))
996 "LAZY TEXT drop -> unfused" [1] forall n t.
997 unstream (S.drop n (stream t)) = drop n t
998 #-}
999
1000 -- | /O(n)/ 'dropEnd' @n@ @t@ returns the prefix remaining after
1001 -- dropping @n@ characters from the end of @t@.
1002 --
1003 -- Examples:
1004 --
1005 -- > dropEnd 3 "foobar" == "foo"
1006 dropEnd :: Int64 -> Text -> Text
1007 dropEnd n t0
1008 | n <= 0 = t0
1009 | otherwise = dropChunk n . L.reverse . toChunks $ t0
1010 where dropChunk _ [] = empty
1011 dropChunk m (t:ts)
1012 | m >= l = dropChunk (m-l) ts
1013 | otherwise = fromChunks . L.reverse $
1014 T.dropEnd (fromIntegral m) t : ts
1015 where l = fromIntegral (T.length t)
1016
1017 -- | /O(n)/ 'dropWords' @n@ returns the suffix with @n@ 'Word16'
1018 -- values dropped, or the empty 'Text' if @n@ is greater than the
1019 -- number of 'Word16' values present.
1020 dropWords :: Int64 -> Text -> Text
1021 dropWords i t0
1022 | i <= 0 = t0
1023 | otherwise = drop' i t0
1024 where drop' 0 ts = ts
1025 drop' _ Empty = Empty
1026 drop' n (Chunk (T.Text arr off len) ts)
1027 | n < len' = chunk (text arr (off+n') (len-n')) ts
1028 | otherwise = drop' (n - len') ts
1029 where len' = fromIntegral len
1030 n' = fromIntegral n
1031
1032 -- | /O(n)/ 'takeWhile', applied to a predicate @p@ and a 'Text',
1033 -- returns the longest prefix (possibly empty) of elements that
1034 -- satisfy @p@. Subject to fusion.
1035 takeWhile :: (Char -> Bool) -> Text -> Text
1036 takeWhile p t0 = takeWhile' t0
1037 where takeWhile' Empty = Empty
1038 takeWhile' (Chunk t ts) =
1039 case T.findIndex (not . p) t of
1040 Just n | n > 0 -> Chunk (T.take n t) Empty
1041 | otherwise -> Empty
1042 Nothing -> Chunk t (takeWhile' ts)
1043 {-# INLINE [1] takeWhile #-}
1044
1045 {-# RULES
1046 "LAZY TEXT takeWhile -> fused" [~1] forall p t.
1047 takeWhile p t = unstream (S.takeWhile p (stream t))
1048 "LAZY TEXT takeWhile -> unfused" [1] forall p t.
1049 unstream (S.takeWhile p (stream t)) = takeWhile p t
1050 #-}
1051
1052 -- | /O(n)/ 'dropWhile' @p@ @t@ returns the suffix remaining after
1053 -- 'takeWhile' @p@ @t@. Subject to fusion.
1054 dropWhile :: (Char -> Bool) -> Text -> Text
1055 dropWhile p t0 = dropWhile' t0
1056 where dropWhile' Empty = Empty
1057 dropWhile' (Chunk t ts) =
1058 case T.findIndex (not . p) t of
1059 Just n -> Chunk (T.drop n t) ts
1060 Nothing -> dropWhile' ts
1061 {-# INLINE [1] dropWhile #-}
1062
1063 {-# RULES
1064 "LAZY TEXT dropWhile -> fused" [~1] forall p t.
1065 dropWhile p t = unstream (S.dropWhile p (stream t))
1066 "LAZY TEXT dropWhile -> unfused" [1] forall p t.
1067 unstream (S.dropWhile p (stream t)) = dropWhile p t
1068 #-}
1069 -- | /O(n)/ 'dropWhileEnd' @p@ @t@ returns the prefix remaining after
1070 -- dropping characters that fail the predicate @p@ from the end of
1071 -- @t@.
1072 -- Examples:
1073 --
1074 -- > dropWhileEnd (=='.') "foo..." == "foo"
1075 dropWhileEnd :: (Char -> Bool) -> Text -> Text
1076 dropWhileEnd p = go
1077 where go Empty = Empty
1078 go (Chunk t Empty) = if T.null t'
1079 then Empty
1080 else Chunk t' Empty
1081 where t' = T.dropWhileEnd p t
1082 go (Chunk t ts) = case go ts of
1083 Empty -> go (Chunk t Empty)
1084 ts' -> Chunk t ts'
1085 {-# INLINE dropWhileEnd #-}
1086
1087 -- | /O(n)/ 'dropAround' @p@ @t@ returns the substring remaining after
1088 -- dropping characters that fail the predicate @p@ from both the
1089 -- beginning and end of @t@. Subject to fusion.
1090 dropAround :: (Char -> Bool) -> Text -> Text
1091 dropAround p = dropWhile p . dropWhileEnd p
1092 {-# INLINE [1] dropAround #-}
1093
1094 -- | /O(n)/ Remove leading white space from a string. Equivalent to:
1095 --
1096 -- > dropWhile isSpace
1097 stripStart :: Text -> Text
1098 stripStart = dropWhile isSpace
1099 {-# INLINE [1] stripStart #-}
1100
1101 -- | /O(n)/ Remove trailing white space from a string. Equivalent to:
1102 --
1103 -- > dropWhileEnd isSpace
1104 stripEnd :: Text -> Text
1105 stripEnd = dropWhileEnd isSpace
1106 {-# INLINE [1] stripEnd #-}
1107
1108 -- | /O(n)/ Remove leading and trailing white space from a string.
1109 -- Equivalent to:
1110 --
1111 -- > dropAround isSpace
1112 strip :: Text -> Text
1113 strip = dropAround isSpace
1114 {-# INLINE [1] strip #-}
1115
1116 -- | /O(n)/ 'splitAt' @n t@ returns a pair whose first element is a
1117 -- prefix of @t@ of length @n@, and whose second is the remainder of
1118 -- the string. It is equivalent to @('take' n t, 'drop' n t)@.
1119 splitAt :: Int64 -> Text -> (Text, Text)
1120 splitAt = loop
1121 where loop _ Empty = (empty, empty)
1122 loop n t | n <= 0 = (empty, t)
1123 loop n (Chunk t ts)
1124 | n < len = let (t',t'') = T.splitAt (fromIntegral n) t
1125 in (Chunk t' Empty, Chunk t'' ts)
1126 | otherwise = let (ts',ts'') = loop (n - len) ts
1127 in (Chunk t ts', ts'')
1128 where len = fromIntegral (T.length t)
1129
1130 -- | /O(n)/ 'splitAtWord' @n t@ returns a strict pair whose first
1131 -- element is a prefix of @t@ whose chunks contain @n@ 'Word16'
1132 -- values, and whose second is the remainder of the string.
1133 splitAtWord :: Int64 -> Text -> PairS Text Text
1134 splitAtWord _ Empty = empty :*: empty
1135 splitAtWord x (Chunk c@(T.Text arr off len) cs)
1136 | y >= len = let h :*: t = splitAtWord (x-fromIntegral len) cs
1137 in Chunk c h :*: t
1138 | otherwise = chunk (text arr off y) empty :*:
1139 chunk (text arr (off+y) (len-y)) cs
1140 where y = fromIntegral x
1141
1142 -- | /O(n+m)/ Find the first instance of @needle@ (which must be
1143 -- non-'null') in @haystack@. The first element of the returned tuple
1144 -- is the prefix of @haystack@ before @needle@ is matched. The second
1145 -- is the remainder of @haystack@, starting with the match.
1146 --
1147 -- Examples:
1148 --
1149 -- > breakOn "::" "a::b::c" ==> ("a", "::b::c")
1150 -- > breakOn "/" "foobar" ==> ("foobar", "")
1151 --
1152 -- Laws:
1153 --
1154 -- > append prefix match == haystack
1155 -- > where (prefix, match) = breakOn needle haystack
1156 --
1157 -- If you need to break a string by a substring repeatedly (e.g. you
1158 -- want to break on every instance of a substring), use 'breakOnAll'
1159 -- instead, as it has lower startup overhead.
1160 --
1161 -- This function is strict in its first argument, and lazy in its
1162 -- second.
1163 --
1164 -- In (unlikely) bad cases, this function's time complexity degrades
1165 -- towards /O(n*m)/.
1166 breakOn :: Text -> Text -> (Text, Text)
1167 breakOn pat src
1168 | null pat = emptyError "breakOn"
1169 | otherwise = case indices pat src of
1170 [] -> (src, empty)
1171 (x:_) -> let h :*: t = splitAtWord x src
1172 in (h, t)
1173
1174 -- | /O(n+m)/ Similar to 'breakOn', but searches from the end of the string.
1175 --
1176 -- The first element of the returned tuple is the prefix of @haystack@
1177 -- up to and including the last match of @needle@. The second is the
1178 -- remainder of @haystack@, following the match.
1179 --
1180 -- > breakOnEnd "::" "a::b::c" ==> ("a::b::", "c")
1181 breakOnEnd :: Text -> Text -> (Text, Text)
1182 breakOnEnd pat src = let (a,b) = breakOn (reverse pat) (reverse src)
1183 in (reverse b, reverse a)
1184 {-# INLINE breakOnEnd #-}
1185
1186 -- | /O(n+m)/ Find all non-overlapping instances of @needle@ in
1187 -- @haystack@. Each element of the returned list consists of a pair:
1188 --
1189 -- * The entire string prior to the /k/th match (i.e. the prefix)
1190 --
1191 -- * The /k/th match, followed by the remainder of the string
1192 --
1193 -- Examples:
1194 --
1195 -- > breakOnAll "::" ""
1196 -- > ==> []
1197 -- > breakOnAll "/" "a/b/c/"
1198 -- > ==> [("a", "/b/c/"), ("a/b", "/c/"), ("a/b/c", "/")]
1199 --
1200 -- This function is strict in its first argument, and lazy in its
1201 -- second.
1202 --
1203 -- In (unlikely) bad cases, this function's time complexity degrades
1204 -- towards /O(n*m)/.
1205 --
1206 -- The @needle@ parameter may not be empty.
1207 breakOnAll :: Text -- ^ @needle@ to search for
1208 -> Text -- ^ @haystack@ in which to search
1209 -> [(Text, Text)]
1210 breakOnAll pat src
1211 | null pat = emptyError "breakOnAll"
1212 | otherwise = go 0 empty src (indices pat src)
1213 where
1214 go !n p s (x:xs) = let h :*: t = splitAtWord (x-n) s
1215 h' = append p h
1216 in (h',t) : go x h' t xs
1217 go _ _ _ _ = []
1218
1219 -- | /O(n)/ 'break' is like 'span', but the prefix returned is over
1220 -- elements that fail the predicate @p@.
1221 break :: (Char -> Bool) -> Text -> (Text, Text)
1222 break p t0 = break' t0
1223 where break' Empty = (empty, empty)
1224 break' c@(Chunk t ts) =
1225 case T.findIndex p t of
1226 Nothing -> let (ts', ts'') = break' ts
1227 in (Chunk t ts', ts'')
1228 Just n | n == 0 -> (Empty, c)
1229 | otherwise -> let (a,b) = T.splitAt n t
1230 in (Chunk a Empty, Chunk b ts)
1231
1232 -- | /O(n)/ 'span', applied to a predicate @p@ and text @t@, returns
1233 -- a pair whose first element is the longest prefix (possibly empty)
1234 -- of @t@ of elements that satisfy @p@, and whose second is the
1235 -- remainder of the list.
1236 span :: (Char -> Bool) -> Text -> (Text, Text)
1237 span p = break (not . p)
1238 {-# INLINE span #-}
1239
1240 -- | The 'group' function takes a 'Text' and returns a list of 'Text's
1241 -- such that the concatenation of the result is equal to the argument.
1242 -- Moreover, each sublist in the result contains only equal elements.
1243 -- For example,
1244 --
1245 -- > group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
1246 --
1247 -- It is a special case of 'groupBy', which allows the programmer to
1248 -- supply their own equality test.
1249 group :: Text -> [Text]
1250 group = groupBy (==)
1251 {-# INLINE group #-}
1252
1253 -- | The 'groupBy' function is the non-overloaded version of 'group'.
1254 groupBy :: (Char -> Char -> Bool) -> Text -> [Text]
1255 groupBy _ Empty = []
1256 groupBy eq (Chunk t ts) = cons x ys : groupBy eq zs
1257 where (ys,zs) = span (eq x) xs
1258 x = T.unsafeHead t
1259 xs = chunk (T.unsafeTail t) ts
1260
1261 -- | /O(n)/ Return all initial segments of the given 'Text',
1262 -- shortest first.
1263 inits :: Text -> [Text]
1264 inits = (Empty :) . inits'
1265 where inits' Empty = []
1266 inits' (Chunk t ts) = L.map (\t' -> Chunk t' Empty) (L.tail (T.inits t))
1267 ++ L.map (Chunk t) (inits' ts)
1268
1269 -- | /O(n)/ Return all final segments of the given 'Text', longest
1270 -- first.
1271 tails :: Text -> [Text]
1272 tails Empty = Empty : []
1273 tails ts@(Chunk t ts')
1274 | T.length t == 1 = ts : tails ts'
1275 | otherwise = ts : tails (Chunk (T.unsafeTail t) ts')
1276
1277 -- $split
1278 --
1279 -- Splitting functions in this library do not perform character-wise
1280 -- copies to create substrings; they just construct new 'Text's that
1281 -- are slices of the original.
1282
1283 -- | /O(m+n)/ Break a 'Text' into pieces separated by the first
1284 -- 'Text' argument, consuming the delimiter. An empty delimiter is
1285 -- invalid, and will cause an error to be raised.
1286 --
1287 -- Examples:
1288 --
1289 -- > splitOn "\r\n" "a\r\nb\r\nd\r\ne" == ["a","b","d","e"]
1290 -- > splitOn "aaa" "aaaXaaaXaaaXaaa" == ["","X","X","X",""]
1291 -- > splitOn "x" "x" == ["",""]
1292 --
1293 -- and
1294 --
1295 -- > intercalate s . splitOn s == id
1296 -- > splitOn (singleton c) == split (==c)
1297 --
1298 -- This function is strict in its first argument, and lazy in its
1299 -- second.
1300 --
1301 -- In (unlikely) bad cases, this function's time complexity degrades
1302 -- towards /O(n*m)/.
1303 splitOn :: Text -- ^ Text to split on
1304 -> Text -- ^ Input text
1305 -> [Text]
1306 splitOn pat src
1307 | null pat = emptyError "splitOn"
1308 | isSingleton pat = split (== head pat) src
1309 | otherwise = go 0 (indices pat src) src
1310 where
1311 go _ [] cs = [cs]
1312 go !i (x:xs) cs = let h :*: t = splitAtWord (x-i) cs
1313 in h : go (x+l) xs (dropWords l t)
1314 l = foldlChunks (\a (T.Text _ _ b) -> a + fromIntegral b) 0 pat
1315 {-# INLINE [1] splitOn #-}
1316
1317 {-# RULES
1318 "LAZY TEXT splitOn/singleton -> split/==" [~1] forall c t.
1319 splitOn (singleton c) t = split (==c) t
1320 #-}
1321
1322 -- | /O(n)/ Splits a 'Text' into components delimited by separators,
1323 -- where the predicate returns True for a separator element. The
1324 -- resulting components do not contain the separators. Two adjacent
1325 -- separators result in an empty component in the output. eg.
1326 --
1327 -- > split (=='a') "aabbaca" == ["","","bb","c",""]
1328 -- > split (=='a') [] == [""]
1329 split :: (Char -> Bool) -> Text -> [Text]
1330 split _ Empty = [Empty]
1331 split p (Chunk t0 ts0) = comb [] (T.split p t0) ts0
1332 where comb acc (s:[]) Empty = revChunks (s:acc) : []
1333 comb acc (s:[]) (Chunk t ts) = comb (s:acc) (T.split p t) ts
1334 comb acc (s:ss) ts = revChunks (s:acc) : comb [] ss ts
1335 comb _ [] _ = impossibleError "split"
1336 {-# INLINE split #-}
1337
1338 -- | /O(n)/ Splits a 'Text' into components of length @k@. The last
1339 -- element may be shorter than the other chunks, depending on the
1340 -- length of the input. Examples:
1341 --
1342 -- > chunksOf 3 "foobarbaz" == ["foo","bar","baz"]
1343 -- > chunksOf 4 "haskell.org" == ["hask","ell.","org"]
1344 chunksOf :: Int64 -> Text -> [Text]
1345 chunksOf k = go
1346 where
1347 go t = case splitAt k t of
1348 (a,b) | null a -> []
1349 | otherwise -> a : go b
1350 {-# INLINE chunksOf #-}
1351
1352 -- | /O(n)/ Breaks a 'Text' up into a list of 'Text's at
1353 -- newline 'Char's. The resulting strings do not contain newlines.
1354 lines :: Text -> [Text]
1355 lines Empty = []
1356 lines t = let (l,t') = break ((==) '\n') t
1357 in l : if null t' then []
1358 else lines (tail t')
1359
1360 -- | /O(n)/ Breaks a 'Text' up into a list of words, delimited by 'Char's
1361 -- representing white space.
1362 words :: Text -> [Text]
1363 words = L.filter (not . null) . split isSpace
1364 {-# INLINE words #-}
1365
1366 -- | /O(n)/ Joins lines, after appending a terminating newline to
1367 -- each.
1368 unlines :: [Text] -> Text
1369 unlines = concat . L.map (`snoc` '\n')
1370 {-# INLINE unlines #-}
1371
1372 -- | /O(n)/ Joins words using single space characters.
1373 unwords :: [Text] -> Text
1374 unwords = intercalate (singleton ' ')
1375 {-# INLINE unwords #-}
1376
1377 -- | /O(n)/ The 'isPrefixOf' function takes two 'Text's and returns
1378 -- 'True' iff the first is a prefix of the second. Subject to fusion.
1379 isPrefixOf :: Text -> Text -> Bool
1380 isPrefixOf Empty _ = True
1381 isPrefixOf _ Empty = False
1382 isPrefixOf (Chunk x xs) (Chunk y ys)
1383 | lx == ly = x == y && isPrefixOf xs ys
1384 | lx < ly = x == yh && isPrefixOf xs (Chunk yt ys)
1385 | otherwise = xh == y && isPrefixOf (Chunk xt xs) ys
1386 where (xh,xt) = T.splitAt ly x
1387 (yh,yt) = T.splitAt lx y
1388 lx = T.length x
1389 ly = T.length y
1390 {-# INLINE [1] isPrefixOf #-}
1391
1392 {-# RULES
1393 "LAZY TEXT isPrefixOf -> fused" [~1] forall s t.
1394 isPrefixOf s t = S.isPrefixOf (stream s) (stream t)
1395 "LAZY TEXT isPrefixOf -> unfused" [1] forall s t.
1396 S.isPrefixOf (stream s) (stream t) = isPrefixOf s t
1397 #-}
1398
1399 -- | /O(n)/ The 'isSuffixOf' function takes two 'Text's and returns
1400 -- 'True' iff the first is a suffix of the second.
1401 isSuffixOf :: Text -> Text -> Bool
1402 isSuffixOf x y = reverse x `isPrefixOf` reverse y
1403 {-# INLINE isSuffixOf #-}
1404 -- TODO: a better implementation
1405
1406 -- | /O(n+m)/ The 'isInfixOf' function takes two 'Text's and returns
1407 -- 'True' iff the first is contained, wholly and intact, anywhere
1408 -- within the second.
1409 --
1410 -- This function is strict in its first argument, and lazy in its
1411 -- second.
1412 --
1413 -- In (unlikely) bad cases, this function's time complexity degrades
1414 -- towards /O(n*m)/.
1415 isInfixOf :: Text -> Text -> Bool
1416 isInfixOf needle haystack
1417 | null needle = True
1418 | isSingleton needle = S.elem (head needle) . S.stream $ haystack
1419 | otherwise = not . L.null . indices needle $ haystack
1420 {-# INLINE [1] isInfixOf #-}
1421
1422 {-# RULES
1423 "LAZY TEXT isInfixOf/singleton -> S.elem/S.stream" [~1] forall n h.
1424 isInfixOf (singleton n) h = S.elem n (S.stream h)
1425 #-}
1426
1427 -------------------------------------------------------------------------------
1428 -- * View patterns
1429
1430 -- | /O(n)/ Return the suffix of the second string if its prefix
1431 -- matches the entire first string.
1432 --
1433 -- Examples:
1434 --
1435 -- > stripPrefix "foo" "foobar" == Just "bar"
1436 -- > stripPrefix "" "baz" == Just "baz"
1437 -- > stripPrefix "foo" "quux" == Nothing
1438 --
1439 -- This is particularly useful with the @ViewPatterns@ extension to
1440 -- GHC, as follows:
1441 --
1442 -- > {-# LANGUAGE ViewPatterns #-}
1443 -- > import Data.Text.Lazy as T
1444 -- >
1445 -- > fnordLength :: Text -> Int
1446 -- > fnordLength (stripPrefix "fnord" -> Just suf) = T.length suf
1447 -- > fnordLength _ = -1
1448 stripPrefix :: Text -> Text -> Maybe Text
1449 stripPrefix p t
1450 | null p = Just t
1451 | otherwise = case commonPrefixes p t of
1452 Just (_,c,r) | null c -> Just r
1453 _ -> Nothing
1454
1455 -- | /O(n)/ Find the longest non-empty common prefix of two strings
1456 -- and return it, along with the suffixes of each string at which they
1457 -- no longer match.
1458 --
1459 -- If the strings do not have a common prefix or either one is empty,
1460 -- this function returns 'Nothing'.
1461 --
1462 -- Examples:
1463 --
1464 -- > commonPrefixes "foobar" "fooquux" == Just ("foo","bar","quux")
1465 -- > commonPrefixes "veeble" "fetzer" == Nothing
1466 -- > commonPrefixes "" "baz" == Nothing
1467 commonPrefixes :: Text -> Text -> Maybe (Text,Text,Text)
1468 commonPrefixes Empty _ = Nothing
1469 commonPrefixes _ Empty = Nothing
1470 commonPrefixes a0 b0 = Just (go a0 b0 [])
1471 where
1472 go t0@(Chunk x xs) t1@(Chunk y ys) ps
1473 = case T.commonPrefixes x y of
1474 Just (p,a,b)
1475 | T.null a -> go xs (chunk b ys) (p:ps)
1476 | T.null b -> go (chunk a xs) ys (p:ps)
1477 | otherwise -> (fromChunks (L.reverse (p:ps)),chunk a xs, chunk b ys)
1478 Nothing -> (fromChunks (L.reverse ps),t0,t1)
1479 go t0 t1 ps = (fromChunks (L.reverse ps),t0,t1)
1480
1481 -- | /O(n)/ Return the prefix of the second string if its suffix
1482 -- matches the entire first string.
1483 --
1484 -- Examples:
1485 --
1486 -- > stripSuffix "bar" "foobar" == Just "foo"
1487 -- > stripSuffix "" "baz" == Just "baz"
1488 -- > stripSuffix "foo" "quux" == Nothing
1489 --
1490 -- This is particularly useful with the @ViewPatterns@ extension to
1491 -- GHC, as follows:
1492 --
1493 -- > {-# LANGUAGE ViewPatterns #-}
1494 -- > import Data.Text.Lazy as T
1495 -- >
1496 -- > quuxLength :: Text -> Int
1497 -- > quuxLength (stripSuffix "quux" -> Just pre) = T.length pre
1498 -- > quuxLength _ = -1
1499 stripSuffix :: Text -> Text -> Maybe Text
1500 stripSuffix p t = reverse `fmap` stripPrefix (reverse p) (reverse t)
1501
1502 -- | /O(n)/ 'filter', applied to a predicate and a 'Text',
1503 -- returns a 'Text' containing those characters that satisfy the
1504 -- predicate.
1505 filter :: (Char -> Bool) -> Text -> Text
1506 filter p t = unstream (S.filter p (stream t))
1507 {-# INLINE filter #-}
1508
1509 -- | /O(n)/ The 'find' function takes a predicate and a 'Text', and
1510 -- returns the first element in matching the predicate, or 'Nothing'
1511 -- if there is no such element.
1512 find :: (Char -> Bool) -> Text -> Maybe Char
1513 find p t = S.findBy p (stream t)
1514 {-# INLINE find #-}
1515
1516 -- | /O(n)/ The 'partition' function takes a predicate and a 'Text',
1517 -- and returns the pair of 'Text's with elements which do and do not
1518 -- satisfy the predicate, respectively; i.e.
1519 --
1520 -- > partition p t == (filter p t, filter (not . p) t)
1521 partition :: (Char -> Bool) -> Text -> (Text, Text)
1522 partition p t = (filter p t, filter (not . p) t)
1523 {-# INLINE partition #-}
1524
1525 -- | /O(n)/ 'Text' index (subscript) operator, starting from 0.
1526 index :: Text -> Int64 -> Char
1527 index t n = S.index (stream t) n
1528 {-# INLINE index #-}
1529
1530 -- | /O(n+m)/ The 'count' function returns the number of times the
1531 -- query string appears in the given 'Text'. An empty query string is
1532 -- invalid, and will cause an error to be raised.
1533 --
1534 -- In (unlikely) bad cases, this function's time complexity degrades
1535 -- towards /O(n*m)/.
1536 count :: Text -> Text -> Int64
1537 count pat src
1538 | null pat = emptyError "count"
1539 | otherwise = go 0 (indices pat src)
1540 where go !n [] = n
1541 go !n (_:xs) = go (n+1) xs
1542 {-# INLINE [1] count #-}
1543
1544 {-# RULES
1545 "LAZY TEXT count/singleton -> countChar" [~1] forall c t.
1546 count (singleton c) t = countChar c t
1547 #-}
1548
1549 -- | /O(n)/ The 'countChar' function returns the number of times the
1550 -- query element appears in the given 'Text'. Subject to fusion.
1551 countChar :: Char -> Text -> Int64
1552 countChar c t = S.countChar c (stream t)
1553
1554 -- | /O(n)/ 'zip' takes two 'Text's and returns a list of
1555 -- corresponding pairs of bytes. If one input 'Text' is short,
1556 -- excess elements of the longer 'Text' are discarded. This is
1557 -- equivalent to a pair of 'unpack' operations.
1558 zip :: Text -> Text -> [(Char,Char)]
1559 zip a b = S.unstreamList $ S.zipWith (,) (stream a) (stream b)
1560 {-# INLINE [0] zip #-}
1561
1562 -- | /O(n)/ 'zipWith' generalises 'zip' by zipping with the function
1563 -- given as the first argument, instead of a tupling function.
1564 -- Performs replacement on invalid scalar values.
1565 zipWith :: (Char -> Char -> Char) -> Text -> Text -> Text
1566 zipWith f t1 t2 = unstream (S.zipWith g (stream t1) (stream t2))
1567 where g a b = safe (f a b)
1568 {-# INLINE [0] zipWith #-}
1569
1570 revChunks :: [T.Text] -> Text
1571 revChunks = L.foldl' (flip chunk) Empty
1572
1573 emptyError :: String -> a
1574 emptyError fun = P.error ("Data.Text.Lazy." ++ fun ++ ": empty input")
1575
1576 impossibleError :: String -> a
1577 impossibleError fun = P.error ("Data.Text.Lazy." ++ fun ++ ": impossible case")