on a80bdad help sign in
text/Data/Text.hs
1452 lines 48 kB history raw
1{-# LANGUAGE BangPatterns, CPP, Rank2Types #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
4-- |
5-- Module : Data.Text
6-- Copyright : (c) 2008, 2009 Tom Harper,
7-- (c) 2009, 2010 Bryan O'Sullivan,
8-- (c) 2009 Duncan Coutts
9--
10-- License : BSD-style
11-- Maintainer : bos@serpentine.com, rtomharper@googlemail.com,
12-- duncan@haskell.org
13-- Stability : experimental
14-- Portability : GHC
15--
16-- A time and space-efficient implementation of Unicode text using
17-- packed Word16 arrays. Suitable for performance critical use, both
18-- in terms of large data quantities and high speed.
19--
20-- This module is intended to be imported @qualified@, to avoid name
21-- clashes with "Prelude" functions, e.g.
22--
23-- > import qualified Data.Text as T
25module Data.Text
26 (
27 -- * Strict vs lazy types
28 -- $strict
30 -- * Fusion
31 -- $fusion
33 -- * Types
34 Text
36 -- * Creation and elimination
37 , pack
38 , unpack
39 , singleton
40 , empty
42 -- * Basic interface
43 , cons
44 , snoc
45 , append
46 , uncons
47 , head
48 , last
49 , tail
50 , init
51 , null
52 , length
53 , compareLength
55 -- * Transformations
56 , map
57 , intercalate
58 , intersperse
59 , transpose
60 , reverse
61 , replace
63 -- ** Case conversion
64 -- $case
65 , toCaseFold
66 , toLower
67 , toUpper
69 -- ** Justification
70 , justifyLeft
71 , justifyRight
72 , center
74 -- * Folds
75 , foldl
76 , foldl'
77 , foldl1
78 , foldl1'
79 , foldr
80 , foldr1
82 -- ** Special folds
83 , concat
84 , concatMap
85 , any
86 , all
87 , maximum
88 , minimum
90 -- * Construction
92 -- ** Scans
93 , scanl
94 , scanl1
95 , scanr
96 , scanr1
98 -- ** Accumulating maps
99 , mapAccumL
100 , mapAccumR
102 -- ** Generation and unfolding
103 , replicate
104 , unfoldr
105 , unfoldrN
107 -- * Substrings
109 -- ** Breaking strings
110 , take
111 , drop
112 , takeWhile
113 , dropWhile
114 , dropWhileEnd
115 , dropAround
116 , strip
117 , stripStart
118 , stripEnd
119 , splitAt
120 , spanBy
121 , break
122 , breakEnd
123 , breakBy
124 , group
125 , groupBy
126 , inits
127 , tails
129 -- ** Breaking into many substrings
130 -- $split
131 , split
132 , splitBy
133 , chunksOf
135 -- ** Breaking into lines and words
136 , lines
137 --, lines'
138 , words
139 , unlines
140 , unwords
142 -- * Predicates
143 , isPrefixOf
144 , isSuffixOf
145 , isInfixOf
147 -- ** View patterns
148 , stripPrefix
149 , stripSuffix
151 -- * Searching
152 , filter
153 , find
154 , findBy
155 , partitionBy
157 -- , findSubstring
159 -- * Indexing
160 -- $index
161 , index
162 , findIndex
163 , count
165 -- * Zipping and unzipping
166 , zip
167 , zipWith
169 -- -* Ordered text
170 -- , sort
171 ) where
173import Prelude (Char, Bool(..), Int, Maybe(..), String,
174 Eq(..), Ord(..), Ordering(..), (++),
175 Read(..), Show(..),
176 (&&), (||), (+), (-), (.), ($), ($!), (>>), (*),
177 div, maxBound, not, return, otherwise)
178#if defined(HAVE_DEEPSEQ)
179import Control.DeepSeq (NFData)
180#endif
181#if defined(ASSERTS)
182import Control.Exception (assert)
183#endif
184import Data.Char (isSpace)
185import Data.Data (Data(gfoldl, toConstr, gunfold, dataTypeOf))
186#if __GLASGOW_HASKELL__ >= 612
187import Data.Data (mkNoRepType)
188#else
189import Data.Data (mkNorepType)
190#endif
191import Control.Monad (foldM)
192import qualified Data.Text.Array as A
193import qualified Data.List as L
194import Data.Monoid (Monoid(..))
195import Data.String (IsString(..))
196import qualified Data.Text.Fusion as S
197import qualified Data.Text.Fusion.Common as S
198import Data.Text.Fusion (stream, reverseStream, unstream)
199import Data.Text.Internal (Text(..), empty, text, textP)
200import qualified Prelude as P
201import Data.Text.Unsafe (Iter(..), iter, iter_, lengthWord16, reverseIter,
202 unsafeHead, unsafeTail)
203import Data.Text.UnsafeChar (unsafeChr)
204import qualified Data.Text.Util as U
205import qualified Data.Text.Encoding.Utf16 as U16
206import Data.Text.Search (indices)
207#if defined(__HADDOCK__)
208import Data.ByteString (ByteString)
209import qualified Data.Text.Lazy as L
210import Data.Int (Int64)
211#endif
213-- $strict
214--
215-- This package provides both strict and lazy 'Text' types. The
216-- strict type is provided by the 'Data.Text' package, while the lazy
217-- type is provided by the 'Data.Text.Lazy' package. Internally, the
218-- lazy @Text@ type consists of a list of strict chunks.
219--
220-- The strict 'Text' type requires that an entire string fit into
221-- memory at once. The lazy @Text@ type is capable of streaming
222-- strings that are larger than memory using a small memory footprint.
223-- In many cases, the overhead of chunked streaming makes the lazy
224-- @Text@ type slower than its strict counterpart, but this is not
225-- always the case. Sometimes, the time complexity of a function in
226-- one module may be different from the other, due to their differing
227-- internal structures.
228--
229-- Each module provides an almost identical API, with the main
230-- difference being that the strict module uses 'Int' values for
231-- lengths and counts, while the lazy module uses 'Int64' lengths.
233-- $fusion
234--
235-- Most of the functions in this module are subject to /fusion/,
236-- meaning that a pipeline of such functions will usually allocate at
237-- most one 'Text' value.
238--
239-- As an example, consider the following pipeline:
240--
241-- > import Data.Text as T
242-- > import Data.Text.Encoding as E
243-- >
244-- > countChars :: ByteString -> Int
245-- > countChars = T.length . T.toUpper . E.decodeUtf8
246--
247-- From the type signatures involved, this looks like it should
248-- allocate one 'ByteString' value, and two 'Text' values. However,
249-- when a module is compiled with optimisation enabled under GHC, the
250-- two intermediate 'Text' values will be optimised away, and the
251-- function will be compiled down to a single loop over the source
252-- 'ByteString'.
253--
254-- Functions that can be fused by the compiler are marked with the
255-- phrase \"Subject to fusion\".
257instance Eq Text where
258 t1 == t2 = stream t1 == stream t2
259 {-# INLINE (==) #-}
261instance Ord Text where
262 compare t1 t2 = compare (stream t1) (stream t2)
263 {-# INLINE compare #-}
265instance Show Text where
266 showsPrec p ps r = showsPrec p (unpack ps) r
268instance Read Text where
269 readsPrec p str = [(pack x,y) | (x,y) <- readsPrec p str]
271instance Monoid Text where
272 mempty = empty
273 mappend = append
274 mconcat = concat
276instance IsString Text where
277 fromString = pack
279#if defined(HAVE_DEEPSEQ)
280instance NFData Text
281#endif
283-- This instance preserves data abstraction at the cost of inefficiency.
284-- We omit reflection services for the sake of data abstraction.
285--
286-- This instance was created by copying the behavior of Data.Set and
287-- Data.Map. If you feel a mistake has been made, please feel free to
288-- submit improvements.
289--
290-- Original discussion is archived here:
292-- "could we get a Data instance for Data.Text.Text?"
293-- http://groups.google.com/group/haskell-cafe/browse_thread/thread/b5bbb1b28a7e525d/0639d46852575b93
295instance Data Text where
296 gfoldl f z txt = z pack `f` (unpack txt)
297 toConstr _ = P.error "Data.Text.Text.toConstr"
298 gunfold _ _ = P.error "Data.Text.Text.gunfold"
299#if __GLASGOW_HASKELL__ >= 612
300 dataTypeOf _ = mkNoRepType "Data.Text.Text"
301#else
302 dataTypeOf _ = mkNorepType "Data.Text.Text"
303#endif
305-- -----------------------------------------------------------------------------
306-- * Conversion to/from 'Text'
308-- | /O(n)/ Convert a 'String' into a 'Text'. Subject to fusion.
309pack :: String -> Text
310pack = unstream . S.streamList
311{-# INLINE [1] pack #-}
313-- | /O(n)/ Convert a Text into a String. Subject to fusion.
314unpack :: Text -> String
315unpack = S.unstreamList . stream
316{-# INLINE [1] unpack #-}
318-- | /O(1)/ Convert a character into a Text.
319-- Subject to fusion.
320singleton :: Char -> Text
321singleton = unstream . S.singleton
322{-# INLINE [1] singleton #-}
324-- -----------------------------------------------------------------------------
325-- * Basic functions
327-- | /O(n)/ Adds a character to the front of a 'Text'. This function
328-- is more costly than its 'List' counterpart because it requires
329-- copying a new array. Subject to fusion.
330cons :: Char -> Text -> Text
331cons c t = unstream (S.cons c (stream t))
332{-# INLINE cons #-}
334-- | /O(n)/ Adds a character to the end of a 'Text'. This copies the
335-- entire array in the process, unless fused. Subject to fusion.
336snoc :: Text -> Char -> Text
337snoc t c = unstream (S.snoc (stream t) c)
338{-# INLINE snoc #-}
340-- | /O(n)/ Appends one 'Text' to the other by copying both of them
341-- into a new 'Text'. Subject to fusion.
342append :: Text -> Text -> Text
343append a@(Text arr1 off1 len1) b@(Text arr2 off2 len2)
344 | len1 == 0 = b
345 | len2 == 0 = a
346 | len > 0 = Text (A.run x) 0 len
347 | otherwise = overflowError "append"
348 where
349 len = len1+len2
350 x = do
351 arr <- A.new len
352 A.copyI arr 0 arr1 off1 len1
353 A.copyI arr len1 arr2 off2 len
354 return arr
355{-# INLINE append #-}
357{-# RULES
358"TEXT append -> fused" [~1] forall t1 t2.
359 append t1 t2 = unstream (S.append (stream t1) (stream t2))
360"TEXT append -> unfused" [1] forall t1 t2.
361 unstream (S.append (stream t1) (stream t2)) = append t1 t2
362 #-}
364-- | /O(1)/ Returns the first character of a 'Text', which must be
365-- non-empty. Subject to fusion.
366head :: Text -> Char
367head t = S.head (stream t)
368{-# INLINE head #-}
370-- | /O(1)/ Returns the first character and rest of a 'Text', or
371-- 'Nothing' if empty. Subject to fusion.
372uncons :: Text -> Maybe (Char, Text)
373uncons t@(Text arr off len)
374 | len <= 0 = Nothing
375 | otherwise = Just (c, textP arr (off+d) (len-d))
376 where Iter c d = iter t 0
377{-# INLINE [1] uncons #-}
379-- | Lifted from Control.Arrow and specialized.
380second :: (b -> c) -> (a,b) -> (a,c)
381second f (a, b) = (a, f b)
383-- | /O(1)/ Returns the last character of a 'Text', which must be
384-- non-empty. Subject to fusion.
385last :: Text -> Char
386last (Text arr off len)
387 | len <= 0 = emptyError "last"
388 | n < 0xDC00 || n > 0xDFFF = unsafeChr n
389 | otherwise = U16.chr2 n0 n
390 where n = A.unsafeIndex arr (off+len-1)
391 n0 = A.unsafeIndex arr (off+len-2)
392{-# INLINE [1] last #-}
394{-# RULES
395"TEXT last -> fused" [~1] forall t.
396 last t = S.last (stream t)
397"TEXT last -> unfused" [1] forall t.
398 S.last (stream t) = last t
399 #-}
401-- | /O(1)/ Returns all characters after the head of a 'Text', which
402-- must be non-empty. Subject to fusion.
403tail :: Text -> Text
404tail t@(Text arr off len)
405 | len <= 0 = emptyError "tail"
406 | otherwise = textP arr (off+d) (len-d)
407 where d = iter_ t 0
408{-# INLINE [1] tail #-}
410{-# RULES
411"TEXT tail -> fused" [~1] forall t.
412 tail t = unstream (S.tail (stream t))
413"TEXT tail -> unfused" [1] forall t.
414 unstream (S.tail (stream t)) = tail t
415 #-}
417-- | /O(1)/ Returns all but the last character of a 'Text', which must
418-- be non-empty. Subject to fusion.
419init :: Text -> Text
420init (Text arr off len) | len <= 0 = emptyError "init"
421 | n >= 0xDC00 && n <= 0xDFFF = textP arr off (len-2)
422 | otherwise = textP arr off (len-1)
423 where
424 n = A.unsafeIndex arr (off+len-1)
425{-# INLINE [1] init #-}
427{-# RULES
428"TEXT init -> fused" [~1] forall t.
429 init t = unstream (S.init (stream t))
430"TEXT init -> unfused" [1] forall t.
431 unstream (S.init (stream t)) = init t
432 #-}
434-- | /O(1)/ Tests whether a 'Text' is empty or not. Subject to
435-- fusion.
436null :: Text -> Bool
437null (Text _arr _off len) =
438#if defined(ASSERTS)
439 assert (len >= 0) $
440#endif
441 len <= 0
442{-# INLINE [1] null #-}
444{-# RULES
445"TEXT null -> fused" [~1] forall t.
446 null t = S.null (stream t)
447"TEXT null -> unfused" [1] forall t.
448 S.null (stream t) = null t
449 #-}
451-- | /O(1)/ Tests whether a 'Text' contains exactly one character.
452-- Subject to fusion.
453isSingleton :: Text -> Bool
454isSingleton = S.isSingleton . stream
455{-# INLINE isSingleton #-}
457-- | /O(n)/ Returns the number of characters in a 'Text'.
458-- Subject to fusion.
459length :: Text -> Int
460length t = S.length (stream t)
461{-# INLINE length #-}
463-- | /O(n)/ Compare the count of characters in a 'Text' to a number.
464-- Subject to fusion.
465--
466-- This function gives the same answer as comparing against the result
467-- of 'length', but can short circuit if the count of characters is
468-- greater than the number, and hence be more efficient.
469compareLength :: Text -> Int -> Ordering
470compareLength t n = S.compareLengthI (stream t) n
471{-# INLINE [1] compareLength #-}
473{-# RULES
474"TEXT compareN/length -> compareLength" [~1] forall t n.
475 compare (length t) n = compareLength t n
476 #-}
478{-# RULES
479"TEXT ==N/length -> compareLength/==EQ" [~1] forall t n.
480 (==) (length t) n = compareLength t n == EQ
481 #-}
483{-# RULES
484"TEXT /=N/length -> compareLength//=EQ" [~1] forall t n.
485 (/=) (length t) n = compareLength t n /= EQ
486 #-}
488{-# RULES
489"TEXT <N/length -> compareLength/==LT" [~1] forall t n.
490 (<) (length t) n = compareLength t n == LT
491 #-}
493{-# RULES
494"TEXT <=N/length -> compareLength//=GT" [~1] forall t n.
495 (<=) (length t) n = compareLength t n /= GT
496 #-}
498{-# RULES
499"TEXT >N/length -> compareLength/==GT" [~1] forall t n.
500 (>) (length t) n = compareLength t n == GT
501 #-}
503{-# RULES
504"TEXT >=N/length -> compareLength//=LT" [~1] forall t n.
505 (>=) (length t) n = compareLength t n /= LT
506 #-}
508-- -----------------------------------------------------------------------------
509-- * Transformations
510-- | /O(n)/ 'map' @f@ @t@ is the 'Text' obtained by applying @f@ to
511-- each element of @t@. Subject to fusion.
512map :: (Char -> Char) -> Text -> Text
513map f t = unstream (S.map f (stream t))
514{-# INLINE [1] map #-}
516-- | /O(n)/ The 'intercalate' function takes a 'Text' and a list of
517-- 'Text's and concatenates the list after interspersing the first
518-- argument between each element of the list.
519intercalate :: Text -> [Text] -> Text
520intercalate t = concat . (U.intersperse t)
521{-# INLINE intercalate #-}
523-- | /O(n)/ The 'intersperse' function takes a character and places it
524-- between the characters of a 'Text'. Subject to fusion.
525intersperse :: Char -> Text -> Text
526intersperse c t = unstream (S.intersperse c (stream t))
527{-# INLINE intersperse #-}
529-- | /O(n)/ Reverse the characters of a string. Subject to fusion.
530reverse :: Text -> Text
531reverse t = S.reverse (stream t)
532{-# INLINE reverse #-}
534-- | /O(m+n)/ Replace every occurrence of one substring with another.
535--
536-- In (unlikely) bad cases, this function's time complexity degrades
537-- towards /O(n*m)/.
538replace :: Text -- ^ Text to search for
539 -> Text -- ^ Replacement text
540 -> Text -- ^ Input text
541 -> Text
542replace s d = intercalate d . split s
543{-# INLINE replace #-}
545-- ----------------------------------------------------------------------------
546-- ** Case conversions (folds)
548-- $case
549--
550-- When case converting 'Text' values, do not use combinators like
551-- @map toUpper@ to case convert each character of a string
552-- individually, as this gives incorrect results according to the
553-- rules of some writing systems. The whole-string case conversion
554-- functions from this module, such as @toUpper@, obey the correct
555-- case conversion rules. As a result, these functions may map one
556-- input character to two or three output characters. For examples,
557-- see the documentation of each function.
558--
559-- /Note/: In some languages, case conversion is a locale- and
560-- context-dependent operation. The case conversion functions in this
561-- module are /not/ locale sensitive. Programs that require locale
562-- sensitivity should use appropriate versions of the case mapping
563-- functions from the @text-icu@ package.
565-- | /O(n)/ Convert a string to folded case. This function is mainly
566-- useful for performing caseless (also known as case insensitive)
567-- string comparisons.
568--
569-- A string @x@ is a caseless match for a string @y@ if and only if:
570--
571-- @toCaseFold x == toCaseFold y@
572--
573-- The result string may be longer than the input string, and may
574-- differ from applying 'toLower' to the input string. For instance,
575-- the Armenian small ligature \"&#xfb13;\" (men now, U+FB13) is case
576-- folded to the sequence \"&#x574;\" (men, U+0574) followed by
577-- \"&#x576;\" (now, U+0576), while the Greek \"&#xb5;\" (micro sign,
578-- U+00B5) is case folded to \"&#x3bc;\" (small letter mu, U+03BC)
579-- instead of itself.
580toCaseFold :: Text -> Text
581toCaseFold t = unstream (S.toCaseFold (stream t))
582{-# INLINE [0] toCaseFold #-}
584-- | /O(n)/ Convert a string to lower case, using simple case
585-- conversion. The result string may be longer than the input string.
586-- For instance, \"&#x130;\" (Latin capital letter I with dot above,
587-- U+0130) maps to the sequence \"i\" (Latin small letter i, U+0069) followed
588-- by \" &#x307;\" (combining dot above, U+0307).
589toLower :: Text -> Text
590toLower t = unstream (S.toLower (stream t))
591{-# INLINE toLower #-}
593-- | /O(n)/ Convert a string to upper case, using simple case
594-- conversion. The result string may be longer than the input string.
595-- For instance, the German \"&#xdf;\" (eszett, U+00DF) maps to the
596-- two-letter sequence \"SS\".
597toUpper :: Text -> Text
598toUpper t = unstream (S.toUpper (stream t))
599{-# INLINE toUpper #-}
601-- | /O(n)/ Left-justify a string to the given length, using the
602-- specified fill character on the right. Subject to fusion. Examples:
603--
604-- > justifyLeft 7 'x' "foo" == "fooxxxx"
605-- > justifyLeft 3 'x' "foobar" == "foobar"
606justifyLeft :: Int -> Char -> Text -> Text
607justifyLeft k c t
608 | len >= k = t
609 | otherwise = t `append` replicateChar (k-len) c
610 where len = length t
611{-# INLINE [1] justifyLeft #-}
613{-# RULES
614"TEXT justifyLeft -> fused" [~1] forall k c t.
615 justifyLeft k c t = unstream (S.justifyLeftI k c (stream t))
616"TEXT justifyLeft -> unfused" [1] forall k c t.
617 unstream (S.justifyLeftI k c (stream t)) = justifyLeft k c t
618 #-}
620-- | /O(n)/ Right-justify a string to the given length, using the
621-- specified fill character on the left. Examples:
622--
623-- > justifyRight 7 'x' "bar" == "xxxxbar"
624-- > justifyRight 3 'x' "foobar" == "foobar"
625justifyRight :: Int -> Char -> Text -> Text
626justifyRight k c t
627 | len >= k = t
628 | otherwise = replicateChar (k-len) c `append` t
629 where len = length t
630{-# INLINE justifyRight #-}
632-- | /O(n)/ Center a string to the given length, using the
633-- specified fill character on either side. Examples:
634--
635-- > center 8 'x' "HS" = "xxxHSxxx"
636center :: Int -> Char -> Text -> Text
637center k c t
638 | len >= k = t
639 | otherwise = replicateChar l c `append` t `append` replicateChar r c
640 where len = length t
641 d = k - len
642 r = d `div` 2
643 l = d - r
644{-# INLINE center #-}
646-- | /O(n)/ The 'transpose' function transposes the rows and columns
647-- of its 'Text' argument. Note that this function uses 'pack',
648-- 'unpack', and the list version of transpose, and is thus not very
649-- efficient.
650transpose :: [Text] -> [Text]
651transpose ts = P.map pack (L.transpose (P.map unpack ts))
653-- -----------------------------------------------------------------------------
654-- * Reducing 'Text's (folds)
656-- | /O(n)/ 'foldl', applied to a binary operator, a starting value
657-- (typically the left-identity of the operator), and a 'Text',
658-- reduces the 'Text' using the binary operator, from left to right.
659-- Subject to fusion.
660foldl :: (a -> Char -> a) -> a -> Text -> a
661foldl f z t = S.foldl f z (stream t)
662{-# INLINE foldl #-}
664-- | /O(n)/ A strict version of 'foldl'. Subject to fusion.
665foldl' :: (a -> Char -> a) -> a -> Text -> a
666foldl' f z t = S.foldl' f z (stream t)
667{-# INLINE foldl' #-}
669-- | /O(n)/ A variant of 'foldl' that has no starting value argument,
670-- and thus must be applied to a non-empty 'Text'. Subject to fusion.
671foldl1 :: (Char -> Char -> Char) -> Text -> Char
672foldl1 f t = S.foldl1 f (stream t)
673{-# INLINE foldl1 #-}
675-- | /O(n)/ A strict version of 'foldl1'. Subject to fusion.
676foldl1' :: (Char -> Char -> Char) -> Text -> Char
677foldl1' f t = S.foldl1' f (stream t)
678{-# INLINE foldl1' #-}
680-- | /O(n)/ 'foldr', applied to a binary operator, a starting value
681-- (typically the right-identity of the operator), and a 'Text',
682-- reduces the 'Text' using the binary operator, from right to left.
683-- Subject to fusion.
684foldr :: (Char -> a -> a) -> a -> Text -> a
685foldr f z t = S.foldr f z (stream t)
686{-# INLINE foldr #-}
688-- | /O(n)/ A variant of 'foldr' that has no starting value argument,
689-- and thust must be applied to a non-empty 'Text'. Subject to
690-- fusion.
691foldr1 :: (Char -> Char -> Char) -> Text -> Char
692foldr1 f t = S.foldr1 f (stream t)
693{-# INLINE foldr1 #-}
695-- -----------------------------------------------------------------------------
696-- ** Special folds
698-- | /O(n)/ Concatenate a list of 'Text's.
699concat :: [Text] -> Text
700concat ts = case ts' of
701 [] -> empty
702 [t] -> t
703 _ -> Text (A.run go) 0 len
704 where
705 ts' = L.filter (not . null) ts
706 len = sumP "concat" $ L.map lengthWord16 ts'
707 go = do
708 arr <- A.new len
709 let step i (Text a o l) =
710 let !j = i + l in A.copyI arr i a o j >> return j
711 foldM step 0 ts' >> return arr
713-- | /O(n)/ Map a function over a 'Text' that results in a 'Text', and
714-- concatenate the results.
715concatMap :: (Char -> Text) -> Text -> Text
716concatMap f = concat . foldr ((:) . f) []
717{-# INLINE concatMap #-}
719-- | /O(n)/ 'any' @p@ @t@ determines whether any character in the
720-- 'Text' @t@ satisifes the predicate @p@. Subject to fusion.
721any :: (Char -> Bool) -> Text -> Bool
722any p t = S.any p (stream t)
723{-# INLINE any #-}
725-- | /O(n)/ 'all' @p@ @t@ determines whether all characters in the
726-- 'Text' @t@ satisify the predicate @p@. Subject to fusion.
727all :: (Char -> Bool) -> Text -> Bool
728all p t = S.all p (stream t)
729{-# INLINE all #-}
731-- | /O(n)/ 'maximum' returns the maximum value from a 'Text', which
732-- must be non-empty. Subject to fusion.
733maximum :: Text -> Char
734maximum t = S.maximum (stream t)
735{-# INLINE maximum #-}
737-- | /O(n)/ 'minimum' returns the minimum value from a 'Text', which
738-- must be non-empty. Subject to fusion.
739minimum :: Text -> Char
740minimum t = S.minimum (stream t)
741{-# INLINE minimum #-}
743-- -----------------------------------------------------------------------------
744-- * Building 'Text's
746-- | /O(n)/ 'scanl' is similar to 'foldl', but returns a list of
747-- successive reduced values from the left. Subject to fusion.
748--
749-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
750--
751-- Note that
752--
753-- > last (scanl f z xs) == foldl f z xs.
754scanl :: (Char -> Char -> Char) -> Char -> Text -> Text
755scanl f z t = unstream (S.scanl f z (stream t))
756{-# INLINE scanl #-}
758-- | /O(n)/ 'scanl1' is a variant of 'scanl' that has no starting
759-- value argument. Subject to fusion.
760--
761-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
762scanl1 :: (Char -> Char -> Char) -> Text -> Text
763scanl1 f t | null t = empty
764 | otherwise = scanl f (unsafeHead t) (unsafeTail t)
765{-# INLINE scanl1 #-}
767-- | /O(n)/ 'scanr' is the right-to-left dual of 'scanl'.
768--
769-- > scanr f v == reverse . scanl (flip f) v . reverse
770scanr :: (Char -> Char -> Char) -> Char -> Text -> Text
771scanr f z = S.reverse . S.reverseScanr f z . reverseStream
772{-# INLINE scanr #-}
774-- | /O(n)/ 'scanr1' is a variant of 'scanr' that has no starting
775-- value argument. Subject to fusion.
776scanr1 :: (Char -> Char -> Char) -> Text -> Text
777scanr1 f t | null t = empty
778 | otherwise = scanr f (last t) (init t)
779{-# INLINE scanr1 #-}
781-- | /O(n)/ Like a combination of 'map' and 'foldl''. Applies a
782-- function to each element of a 'Text', passing an accumulating
783-- parameter from left to right, and returns a final 'Text'.
784mapAccumL :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
785mapAccumL f z0 = S.mapAccumL f z0 . stream
786{-# INLINE mapAccumL #-}
788-- | The 'mapAccumR' function behaves like a combination of 'map' and
789-- a strict 'foldr'; it applies a function to each element of a
790-- 'Text', passing an accumulating parameter from right to left, and
791-- returning a final value of this accumulator together with the new
792-- 'Text'.
793mapAccumR :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
794mapAccumR f z0 = second reverse . S.mapAccumL f z0 . reverseStream
795{-# INLINE mapAccumR #-}
797-- -----------------------------------------------------------------------------
798-- ** Generating and unfolding 'Text's
800-- | /O(n*m)/ 'replicate' @n@ @t@ is a 'Text' consisting of the input
801-- @t@ repeated @n@ times.
802replicate :: Int -> Text -> Text
803replicate n t@(Text a o l)
804 | n <= 0 || l <= 0 = empty
805 | n == 1 = t
806 | isSingleton t = replicateChar n (unsafeHead t)
807 | n <= maxBound `div` l = Text (A.run x) 0 len
808 | otherwise = overflowError "replicate"
809 where
810 len = l * n
811 x = do
812 arr <- A.new len
813 let loop !d !i | i >= n = return arr
814 | otherwise = let m = d + l
815 in A.copyI arr d a o m >> loop m (i+1)
816 loop 0 0
817{-# INLINE [1] replicate #-}
819{-# RULES
820"TEXT replicate/singleton -> replicateChar" [~1] forall n c.
821 replicate n (singleton c) = replicateChar n c
822 #-}
824-- | /O(n)/ 'replicateChar' @n@ @c@ is a 'Text' of length @n@ with @c@ the
825-- value of every element. Subject to fusion.
826replicateChar :: Int -> Char -> Text
827replicateChar n c = unstream (S.replicateCharI n c)
828{-# INLINE replicateChar #-}
830-- | /O(n)/, where @n@ is the length of the result. The 'unfoldr'
831-- function is analogous to the List 'L.unfoldr'. 'unfoldr' builds a
832-- 'Text' from a seed value. The function takes the element and
833-- returns 'Nothing' if it is done producing the 'Text', otherwise
834-- 'Just' @(a,b)@. In this case, @a@ is the next 'Char' in the
835-- string, and @b@ is the seed value for further production. Subject
836-- to fusion.
837unfoldr :: (a -> Maybe (Char,a)) -> a -> Text
838unfoldr f s = unstream (S.unfoldr f s)
839{-# INLINE unfoldr #-}
841-- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a 'Text' from a seed
842-- value. However, the length of the result should be limited by the
843-- first argument to 'unfoldrN'. This function is more efficient than
844-- 'unfoldr' when the maximum length of the result is known and
845-- correct, otherwise its performance is similar to 'unfoldr'. Subject
846-- to fusion.
847unfoldrN :: Int -> (a -> Maybe (Char,a)) -> a -> Text
848unfoldrN n f s = unstream (S.unfoldrN n f s)
849{-# INLINE unfoldrN #-}
851-- -----------------------------------------------------------------------------
852-- * Substrings
854-- | /O(n)/ 'take' @n@, applied to a 'Text', returns the prefix of the
855-- 'Text' of length @n@, or the 'Text' itself if @n@ is greater than
856-- the length of the Text. Subject to fusion.
857take :: Int -> Text -> Text
858take n t@(Text arr off len)
859 | n <= 0 = empty
860 | n >= len = t
861 | otherwise = Text arr off (loop 0 0)
862 where
863 loop !i !cnt
864 | i >= len || cnt >= n = i
865 | otherwise = loop (i+d) (cnt+1)
866 where d = iter_ t i
867{-# INLINE [1] take #-}
869{-# RULES
870"TEXT take -> fused" [~1] forall n t.
871 take n t = unstream (S.take n (stream t))
872"TEXT take -> unfused" [1] forall n t.
873 unstream (S.take n (stream t)) = take n t
874 #-}
876-- | /O(n)/ 'drop' @n@, applied to a 'Text', returns the suffix of the
877-- 'Text' after the first @n@ characters, or the empty 'Text' if @n@
878-- is greater than the length of the 'Text'. Subject to fusion.
879drop :: Int -> Text -> Text
880drop n t@(Text arr off len)
881 | n <= 0 = t
882 | n >= len = empty
883 | otherwise = loop 0 0
884 where loop !i !cnt
885 | i >= len || cnt >= n = Text arr (off+i) (len-i)
886 | otherwise = loop (i+d) (cnt+1)
887 where d = iter_ t i
888{-# INLINE [1] drop #-}
890{-# RULES
891"TEXT drop -> fused" [~1] forall n t.
892 drop n t = unstream (S.drop n (stream t))
893"TEXT drop -> unfused" [1] forall n t.
894 unstream (S.drop n (stream t)) = drop n t
895 #-}
897-- | /O(n)/ 'takeWhile', applied to a predicate @p@ and a 'Text',
898-- returns the longest prefix (possibly empty) of elements that
899-- satisfy @p@. Subject to fusion.
900takeWhile :: (Char -> Bool) -> Text -> Text
901takeWhile p t@(Text arr off len) = loop 0
902 where loop !i | i >= len = t
903 | p c = loop (i+d)
904 | otherwise = textP arr off i
905 where Iter c d = iter t i
906{-# INLINE [1] takeWhile #-}
908{-# RULES
909"TEXT takeWhile -> fused" [~1] forall p t.
910 takeWhile p t = unstream (S.takeWhile p (stream t))
911"TEXT takeWhile -> unfused" [1] forall p t.
912 unstream (S.takeWhile p (stream t)) = takeWhile p t
913 #-}
915-- | /O(n)/ 'dropWhile' @p@ @t@ returns the suffix remaining after
916-- 'takeWhile' @p@ @t@. Subject to fusion.
917dropWhile :: (Char -> Bool) -> Text -> Text
918dropWhile p t@(Text arr off len) = loop 0 0
919 where loop !i !l | l >= len = empty
920 | p c = loop (i+d) (l+d)
921 | otherwise = Text arr (off+i) (len-l)
922 where Iter c d = iter t i
923{-# INLINE [1] dropWhile #-}
925{-# RULES
926"TEXT dropWhile -> fused" [~1] forall p t.
927 dropWhile p t = unstream (S.dropWhile p (stream t))
928"TEXT dropWhile -> unfused" [1] forall p t.
929 unstream (S.dropWhile p (stream t)) = dropWhile p t
930 #-}
932-- | /O(n)/ 'dropWhileEnd' @p@ @t@ returns the prefix remaining after
933-- dropping characters that fail the predicate @p@ from the end of
934-- @t@. Subject to fusion.
935-- Examples:
936--
937-- > dropWhileEnd (=='.') "foo..." == "foo"
938dropWhileEnd :: (Char -> Bool) -> Text -> Text
939dropWhileEnd p t@(Text arr off len) = loop (len-1) len
940 where loop !i !l | l <= 0 = empty
941 | p c = loop (i+d) (l+d)
942 | otherwise = Text arr off l
943 where (c,d) = reverseIter t i
944{-# INLINE [1] dropWhileEnd #-}
946{-# RULES
947"TEXT dropWhileEnd -> fused" [~1] forall p t.
948 dropWhileEnd p t = S.reverse (S.dropWhile p (S.reverseStream t))
949"TEXT dropWhileEnd -> unfused" [1] forall p t.
950 S.reverse (S.dropWhile p (S.reverseStream t)) = dropWhileEnd p t
951 #-}
953-- | /O(n)/ 'dropAround' @p@ @t@ returns the substring remaining after
954-- dropping characters that fail the predicate @p@ from both the
955-- beginning and end of @t@. Subject to fusion.
956dropAround :: (Char -> Bool) -> Text -> Text
957dropAround p = dropWhile p . dropWhileEnd p
958{-# INLINE [1] dropAround #-}
960-- | /O(n)/ Remove leading white space from a string. Equivalent to:
961--
962-- > dropWhile isSpace
963stripStart :: Text -> Text
964stripStart = dropWhile isSpace
965{-# INLINE [1] stripStart #-}
967-- | /O(n)/ Remove trailing white space from a string. Equivalent to:
968--
969-- > dropWhileEnd isSpace
970stripEnd :: Text -> Text
971stripEnd = dropWhileEnd isSpace
972{-# INLINE [1] stripEnd #-}
974-- | /O(n)/ Remove leading and trailing white space from a string.
975-- Equivalent to:
976--
977-- > dropAround isSpace
978strip :: Text -> Text
979strip = dropAround isSpace
980{-# INLINE [1] strip #-}
982-- | /O(n)/ 'splitAt' @n t@ returns a pair whose first element is a
983-- prefix of @t@ of length @n@, and whose second is the remainder of
984-- the string. It is equivalent to @('take' n t, 'drop' n t)@.
985splitAt :: Int -> Text -> (Text, Text)
986splitAt n t@(Text arr off len)
987 | n <= 0 = (empty, t)
988 | n >= len = (t, empty)
989 | otherwise = (Text arr off k, Text arr (off+k) (len-k))
990 where k = loop 0 0
991 loop !i !cnt
992 | i >= len || cnt >= n = i
993 | otherwise = loop (i+d) (cnt+1)
994 where d = iter_ t i
995{-# INLINE splitAt #-}
997-- | /O(n)/ 'spanBy', applied to a predicate @p@ and text @t@, returns
998-- a pair whose first element is the longest prefix (possibly empty)
999-- of @t@ of elements that satisfy @p@, and whose second is the
1000-- remainder of the list.
1001spanBy :: (Char -> Bool) -> Text -> (Text, Text)
1002spanBy p t@(Text arr off len) = (textP arr off k, textP arr (off+k) (len-k))
1003 where k = loop 0
1004 loop !i | i >= len || not (p c) = i
1005 | otherwise = loop (i+d)
1006 where Iter c d = iter t i
1007{-# INLINE spanBy #-}
1009-- | /O(n)/ 'breakBy' is like 'spanBy', but the prefix returned is
1010-- over elements that fail the predicate @p@.
1011breakBy :: (Char -> Bool) -> Text -> (Text, Text)
1012breakBy p = spanBy (not . p)
1013{-# INLINE breakBy #-}
1015-- | /O(n)/ Group characters in a string according to a predicate.
1016groupBy :: (Char -> Char -> Bool) -> Text -> [Text]
1017groupBy p = loop
1018 where
1019 loop t@(Text arr off len)
1020 | null t = []
1021 | otherwise = text arr off n : loop (text arr (off+n) (len-n))
1022 where Iter c d = iter t 0
1023 n = d + findAIndexOrEnd (not . p c) (Text arr (off+d) (len-d))
1025-- | Returns the /array/ index (in units of 'Word16') at which a
1026-- character may be found. This is /not/ the same as the logical
1027-- index returned by e.g. 'findIndex'.
1028findAIndexOrEnd :: (Char -> Bool) -> Text -> Int
1029findAIndexOrEnd q t@(Text _arr _off len) = go 0
1030 where go !i | i >= len || q c = i
1031 | otherwise = go (i+d)
1032 where Iter c d = iter t i
1034-- | /O(n)/ Group characters in a string by equality.
1035group :: Text -> [Text]
1036group = groupBy (==)
1038-- | /O(n)/ Return all initial segments of the given 'Text', shortest
1039-- first.
1040inits :: Text -> [Text]
1041inits t@(Text arr off len) = loop 0
1042 where loop i | i >= len = [t]
1043 | otherwise = Text arr off i : loop (i + iter_ t i)
1045-- | /O(n)/ Return all final segments of the given 'Text', longest
1046-- first.
1047tails :: Text -> [Text]
1048tails t | null t = [empty]
1049 | otherwise = t : tails (unsafeTail t)
1051-- $split
1053-- Splitting functions in this library do not perform character-wise
1054-- copies to create substrings; they just construct new 'Text's that
1055-- are slices of the original.
1057-- | /O(m+n)/ Break a 'Text' into pieces separated by the first
1058-- 'Text' argument, consuming the delimiter. An empty delimiter is
1059-- invalid, and will cause an error to be raised.
1061-- Examples:
1063-- > split "\r\n" "a\r\nb\r\nd\r\ne" == ["a","b","d","e"]
1064-- > split "aaa" "aaaXaaaXaaaXaaa" == ["","X","X","X",""]
1065-- > split "x" "x" == ["",""]
1066--
1067-- and
1069-- > intercalate s . split s == id
1070-- > split (singleton c) == splitBy (==c)
1072-- In (unlikely) bad cases, this function's time complexity degrades
1073-- towards /O(n*m)/.
1074split :: Text -> Text -> [Text]
1075split pat@(Text _ _ l) src@(Text arr off len)
1076 | l <= 0 = emptyError "split"
1077 | isSingleton pat = splitBy (== unsafeHead pat) src
1078 | otherwise = go 0 (indices pat src)
1079 where
1080 go !s (x:xs) = textP arr (s+off) (x-s) : go (x+l) xs
1081 go s _ = [textP arr (s+off) (len-s)]
1082{-# INLINE [1] split #-}
1084{-# RULES
1085"TEXT split/singleton -> splitBy/==" [~1] forall c t.
1086 split (singleton c) t = splitBy (==c) t
1087 #-}
1089-- | /O(n)/ Splits a 'Text' into components delimited by separators,
1090-- where the predicate returns True for a separator element. The
1091-- resulting components do not contain the separators. Two adjacent
1092-- separators result in an empty component in the output. eg.
1094-- > splitBy (=='a') "aabbaca" == ["","","bb","c",""]
1095-- > splitBy (=='a') "" == [""]
1096splitBy :: (Char -> Bool) -> Text -> [Text]
1097splitBy _ t@(Text _off _arr 0) = [t]
1098splitBy p t = loop t
1099 where loop s | null s' = [l]
1100 | otherwise = l : loop (unsafeTail s')
1101 where (l, s') = breakBy p s
1102{-# INLINE splitBy #-}
1104-- | /O(n)/ Splits a 'Text' into components of length @k@. The last
1105-- element may be shorter than the other chunks, depending on the
1106-- length of the input. Examples:
1108-- > chunksOf 3 "foobarbaz" == ["foo","bar","baz"]
1109-- > chunksOf 4 "haskell.org" == ["hask","ell.","org"]
1110chunksOf :: Int -> Text -> [Text]
1111chunksOf k = go
1112 where
1113 go t = case splitAt k t of
1114 (a,b) | null a -> []
1115 | otherwise -> a : go b
1116{-# INLINE chunksOf #-}
1118-- ----------------------------------------------------------------------------
1119-- * Searching
1121-------------------------------------------------------------------------------
1122-- ** Searching with a predicate
1124-- | /O(n)/ The 'findBy' function takes a predicate and a 'Text', and
1125-- returns the first element in matching the predicate, or 'Nothing'
1126-- if there is no such element.
1127findBy :: (Char -> Bool) -> Text -> Maybe Char
1128findBy p t = S.findBy p (stream t)
1129{-# INLINE findBy #-}
1131-- | /O(n)/ The 'partitionBy' function takes a predicate and a 'Text',
1132-- and returns the pair of 'Text's with elements which do and do not
1133-- satisfy the predicate, respectively; i.e.
1135-- > partitionBy p t == (filter p t, filter (not . p) t)
1136partitionBy :: (Char -> Bool) -> Text -> (Text, Text)
1137partitionBy p t = (filter p t, filter (not . p) t)
1138{-# INLINE partitionBy #-}
1140-- | /O(n)/ 'filter', applied to a predicate and a 'Text',
1141-- returns a 'Text' containing those characters that satisfy the
1142-- predicate.
1143filter :: (Char -> Bool) -> Text -> Text
1144filter p t = unstream (S.filter p (stream t))
1145{-# INLINE filter #-}
1147-- | /O(n+m)/ Find the first instance of @needle@ (which must be
1148-- non-'null') in @haystack@. The first element of the returned tuple
1149-- is the prefix of @haystack@ before @needle@ is matched. The second
1150-- is the remainder of @haystack@, starting with the match.
1152-- Examples:
1154-- > break "::" "a::b::c" ==> ("a", "::b::c")
1155-- > break "/" "foobar" ==> ("foobar", "")
1157-- Laws:
1159-- > append prefix match == haystack
1160-- > where (prefix, match) = break needle haystack
1162-- If you need to break a string by a substring repeatedly (e.g. you
1163-- want to break on every instance of a substring), use 'find'
1164-- instead, as it has lower startup overhead.
1166-- In (unlikely) bad cases, this function's time complexity degrades
1167-- towards /O(n*m)/.
1168break :: Text -> Text -> (Text, Text)
1169break pat src@(Text arr off len)
1170 | null pat = emptyError "break"
1171 | otherwise = case indices pat src of
1172 [] -> (src, empty)
1173 (x:_) -> (textP arr off x, textP arr (off+x) (len-x))
1174{-# INLINE break #-}
1176-- | /O(n+m)/ Similar to 'break', but searches from the end of the string.
1178-- The first element of the returned tuple is the prefix of @haystack@
1179-- up to and including the last match of @needle@. The second is the
1180-- remainder of @haystack@, following the match.
1182-- > breakEnd "::" "a::b::c" ==> ("a::b::", "c")
1183breakEnd :: Text -> Text -> (Text, Text)
1184breakEnd pat src = let (a,b) = break (reverse pat) (reverse src)
1185 in (reverse b, reverse a)
1186{-# INLINE breakEnd #-}
1188-- | /O(n+m)/ Find all non-overlapping instances of @needle@ in
1189-- @haystack@. Each element of the returned list consists of a pair:
1191-- * The entire string prior to the /k/th match (i.e. the prefix)
1193-- * The /k/th match, followed by the remainder of the string
1195-- Examples:
1197-- > find "::" ""
1198-- > ==> []
1199-- > find "/" "a/b/c/"
1200-- > ==> [("a", "/b/c/"), ("a/b", "/c/"), ("a/b/c", "/")]
1202-- In (unlikely) bad cases, this function's time complexity degrades
1203-- towards /O(n*m)/.
1205-- The @needle@ parameter may not be empty.
1206find :: Text -- ^ @needle@ to search for
1207 -> Text -- ^ @haystack@ in which to search
1208 -> [(Text, Text)]
1209find pat src@(Text arr off slen)
1210 | null pat = emptyError "find"
1211 | otherwise = L.map step (indices pat src)
1212 where
1213 step x = (chunk 0 x, chunk x (slen-x))
1214 chunk !n !l = textP arr (n+off) l
1215{-# INLINE find #-}
1217-------------------------------------------------------------------------------
1218-- ** Indexing 'Text's
1220-- $index
1222-- If you think of a 'Text' value as an array of 'Char' values (which
1223-- it is not), you run the risk of writing inefficient code.
1225-- An idiom that is common in some languages is to find the numeric
1226-- offset of a character or substring, then use that number to split
1227-- or trim the searched string. With a 'Text' value, this approach
1228-- would require two /O(n)/ operations: one to perform the search, and
1229-- one to operate from wherever the search ended.
1231-- For example, suppose you have a string that you want to split on
1232-- the substring @\"::\"@, such as @\"foo::bar::quux\"@. Instead of
1233-- searching for the index of @\"::\"@ and taking the substrings
1234-- before and after that index, you would instead use @find \"::\"@.
1236-- | /O(n)/ 'Text' index (subscript) operator, starting from 0.
1237index :: Text -> Int -> Char
1238index t n = S.index (stream t) n
1239{-# INLINE index #-}
1241-- | /O(n)/ The 'findIndex' function takes a predicate and a 'Text'
1242-- and returns the index of the first element in the 'Text' satisfying
1243-- the predicate. Subject to fusion.
1244findIndex :: (Char -> Bool) -> Text -> Maybe Int
1245findIndex p t = S.findIndex p (stream t)
1246{-# INLINE findIndex #-}
1248-- | /O(n+m)/ The 'count' function returns the number of times the
1249-- query string appears in the given 'Text'. An empty query string is
1250-- invalid, and will cause an error to be raised.
1252-- In (unlikely) bad cases, this function's time complexity degrades
1253-- towards /O(n*m)/.
1254count :: Text -> Text -> Int
1255count pat src
1256 | null pat = emptyError "count"
1257 | isSingleton pat = countChar (unsafeHead pat) src
1258 | otherwise = L.length (indices pat src)
1259{-# INLINE [1] count #-}
1261{-# RULES
1262"TEXT count/singleton -> countChar" [~1] forall c t.
1263 count (singleton c) t = countChar c t
1264 #-}
1266-- | /O(n)/ The 'countChar' function returns the number of times the
1267-- query element appears in the given 'Text'. Subject to fusion.
1268countChar :: Char -> Text -> Int
1269countChar c t = S.countChar c (stream t)
1270{-# INLINE countChar #-}
1272-------------------------------------------------------------------------------
1273-- * Zipping
1275-- | /O(n)/ 'zip' takes two 'Text's and returns a list of
1276-- corresponding pairs of bytes. If one input 'Text' is short,
1277-- excess elements of the longer 'Text' are discarded. This is
1278-- equivalent to a pair of 'unpack' operations.
1279zip :: Text -> Text -> [(Char,Char)]
1280zip a b = S.unstreamList $ S.zipWith (,) (stream a) (stream b)
1281{-# INLINE [0] zip #-}
1283-- | /O(n)/ 'zipWith' generalises 'zip' by zipping with the function
1284-- given as the first argument, instead of a tupling function.
1285zipWith :: (Char -> Char -> Char) -> Text -> Text -> Text
1286zipWith f t1 t2 = unstream (S.zipWith f (stream t1) (stream t2))
1287{-# INLINE [0] zipWith #-}
1289-- | /O(n)/ Breaks a 'Text' up into a list of words, delimited by 'Char's
1290-- representing white space.
1291words :: Text -> [Text]
1292words t@(Text arr off len) = loop 0 0
1293 where
1294 loop !start !n
1295 | n >= len = if start == n
1296 then []
1297 else [Text arr (start+off) (n-start)]
1298 | isSpace c =
1299 if start == n
1300 then loop (start+1) (start+1)
1301 else Text arr (start+off) (n-start) : loop (n+d) (n+d)
1302 | otherwise = loop start (n+d)
1303 where Iter c d = iter t n
1304{-# INLINE words #-}
1306-- | /O(n)/ Breaks a 'Text' up into a list of 'Text's at
1307-- newline 'Char's. The resulting strings do not contain newlines.
1308lines :: Text -> [Text]
1309lines ps | null ps = []
1310 | otherwise = h : if null t
1311 then []
1312 else lines (unsafeTail t)
1313 where (h,t) = spanBy (/= '\n') ps
1314{-# INLINE lines #-}
1317-- | /O(n)/ Portably breaks a 'Text' up into a list of 'Text's at line
1318-- boundaries.
1320-- A line boundary is considered to be either a line feed, a carriage
1321-- return immediately followed by a line feed, or a carriage return.
1322-- This accounts for both Unix and Windows line ending conventions,
1323-- and for the old convention used on Mac OS 9 and earlier.
1324lines' :: Text -> [Text]
1325lines' ps | null ps = []
1326 | otherwise = h : case uncons t of
1327 Nothing -> []
1328 Just (c,t')
1329 | c == '\n' -> lines t'
1330 | c == '\r' -> case uncons t' of
1331 Just ('\n',t'') -> lines t''
1332 _ -> lines t'
1333 where (h,t) = span notEOL ps
1334 notEOL c = c /= '\n' && c /= '\r'
1335{-# INLINE lines' #-}
1338-- | /O(n)/ Joins lines, after appending a terminating newline to
1339-- each.
1340unlines :: [Text] -> Text
1341unlines = concat . L.map (`snoc` '\n')
1342{-# INLINE unlines #-}
1344-- | /O(n)/ Joins words using single space characters.
1345unwords :: [Text] -> Text
1346unwords = intercalate (singleton ' ')
1347{-# INLINE unwords #-}
1349-- | /O(n)/ The 'isPrefixOf' function takes two 'Text's and returns
1350-- 'True' iff the first is a prefix of the second. This function is
1351-- subject to fusion.
1352isPrefixOf :: Text -> Text -> Bool
1353isPrefixOf a@(Text _ _ alen) b@(Text _ _ blen) =
1354 alen <= blen && S.isPrefixOf (stream a) (stream b)
1355{-# INLINE [1] isPrefixOf #-}
1357{-# RULES
1358"TEXT isPrefixOf -> fused" [~1] forall s t.
1359 isPrefixOf s t = S.isPrefixOf (stream s) (stream t)
1360"TEXT isPrefixOf -> unfused" [1] forall s t.
1361 S.isPrefixOf (stream s) (stream t) = isPrefixOf s t
1362 #-}
1364-- | /O(n)/ The 'isSuffixOf' function takes two 'Text's and returns
1365-- 'True' iff the first is a suffix of the second.
1366isSuffixOf :: Text -> Text -> Bool
1367isSuffixOf a@(Text _aarr _aoff alen) b@(Text barr boff blen) =
1368 d >= 0 && a == b'
1369 where d = blen - alen
1370 b' | d == 0 = b
1371 | otherwise = Text barr (boff+d) alen
1372{-# INLINE isSuffixOf #-}
1374-- | /O(n+m)/ The 'isInfixOf' function takes two 'Text's and returns
1375-- 'True' iff the first is contained, wholly and intact, anywhere
1376-- within the second.
1378-- In (unlikely) bad cases, this function's time complexity degrades
1379-- towards /O(n*m)/.
1380isInfixOf :: Text -> Text -> Bool
1381isInfixOf needle haystack
1382 | null needle = True
1383 | isSingleton needle = S.elem (unsafeHead needle) . S.stream $ haystack
1384 | otherwise = not . L.null . indices needle $ haystack
1385{-# INLINE [1] isInfixOf #-}
1387{-# RULES
1388"TEXT isInfixOf/singleton -> S.elem/S.stream" [~1] forall n h.
1389 isInfixOf (singleton n) h = S.elem n (S.stream h)
1390 #-}
1392-------------------------------------------------------------------------------
1393-- * View patterns
1395-- | /O(n)/ Returns the suffix of the second string if its prefix
1396-- matches the first.
1398-- Examples:
1400-- > stripPrefix "foo" "foobar" == Just "bar"
1401-- > stripPrefix "foo" "quux" == Nothing
1403-- This is particularly useful with the @ViewPatterns@ extension to
1404-- GHC, as follows:
1406-- > {-# LANGUAGE ViewPatterns #-}
1407-- > import Data.Text as T
1408-- >
1409-- > fnordLength :: Text -> Int
1410-- > fnordLength (stripPrefix "fnord" -> Just suf) = T.length suf
1411-- > fnordLength _ = -1
1412stripPrefix :: Text -> Text -> Maybe Text
1413stripPrefix p@(Text _arr _off plen) t@(Text arr off len)
1414 | p `isPrefixOf` t = Just $! textP arr (off+plen) (len-plen)
1415 | otherwise = Nothing
1417-- | /O(n)/ Returns the prefix of the second string if its suffix
1418-- matches the first.
1420-- Examples:
1422-- > stripSuffix "bar" "foobar" == Just "foo"
1423-- > stripSuffix "foo" "quux" == Nothing
1425-- This is particularly useful with the @ViewPatterns@ extension to
1426-- GHC, as follows:
1428-- > {-# LANGUAGE ViewPatterns #-}
1429-- > import Data.Text as T
1430-- >
1431-- > quuxLength :: Text -> Int
1432-- > quuxLength (stripSuffix "quux" -> Just pre) = T.length pre
1433-- > quuxLength _ = -1
1434stripSuffix :: Text -> Text -> Maybe Text
1435stripSuffix p@(Text _arr _off plen) t@(Text arr off len)
1436 | p `isSuffixOf` t = Just $! textP arr off (len-plen)
1437 | otherwise = Nothing
1439-- | Add a list of non-negative numbers. Errors out on overflow.
1440sumP :: String -> [Int] -> Int
1441sumP fun = go 0
1442 where go !a (x:xs)
1443 | ax >= 0 = go ax xs
1444 | otherwise = overflowError fun
1445 where ax = a + x
1446 go a _ = a
1448emptyError :: String -> a
1449emptyError fun = P.error $ "Data.Text." ++ fun ++ ": empty input"
1451overflowError :: String -> a
1452overflowError fun = P.error $ "Data.Text." ++ fun ++ ": size overflow"