on builder help sign in
text/Data/Text.hs
1561 lines 53 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.
17-- Suitable for performance critical use, both in terms of large data
18-- quantities and high speed.
19--
20-- /Note/: Read below the synopsis for important notes on the use of
21-- this module.
22--
23-- This module is intended to be imported @qualified@, to avoid name
24-- clashes with "Prelude" functions, e.g.
25--
26-- > import qualified Data.Text as T
27--
28-- To use an extended and very rich family of functions for working
29-- with Unicode text (including normalization, regular expressions,
30-- non-standard encodings, text breaking, and locales), see the
31-- @text-icu@ package: <http://hackage.haskell.org/package/text-icu>
33module Data.Text
34 (
35 -- * Strict vs lazy types
36 -- $strict
38 -- * Acceptable data
39 -- $replacement
41 -- * Fusion
42 -- $fusion
44 -- * Types
45 Text
47 -- * Creation and elimination
48 , pack
49 , unpack
50 , singleton
51 , empty
53 -- * Basic interface
54 , cons
55 , snoc
56 , append
57 , uncons
58 , head
59 , last
60 , tail
61 , init
62 , null
63 , length
64 , compareLength
66 -- * Transformations
67 , map
68 , intercalate
69 , intersperse
70 , transpose
71 , reverse
72 , replace
74 -- ** Case conversion
75 -- $case
76 , toCaseFold
77 , toLower
78 , toUpper
80 -- ** Justification
81 , justifyLeft
82 , justifyRight
83 , center
85 -- * Folds
86 , foldl
87 , foldl'
88 , foldl1
89 , foldl1'
90 , foldr
91 , foldr1
93 -- ** Special folds
94 , concat
95 , concatMap
96 , any
97 , all
98 , maximum
99 , minimum
101 -- * Construction
103 -- ** Scans
104 , scanl
105 , scanl1
106 , scanr
107 , scanr1
109 -- ** Accumulating maps
110 , mapAccumL
111 , mapAccumR
113 -- ** Generation and unfolding
114 , replicate
115 , unfoldr
116 , unfoldrN
118 -- * Substrings
120 -- ** Breaking strings
121 , take
122 , drop
123 , takeWhile
124 , dropWhile
125 , dropWhileEnd
126 , dropAround
127 , strip
128 , stripStart
129 , stripEnd
130 , splitAt
131 , breakOn
132 , breakOnEnd
133 , break
134 , span
135 , group
136 , groupBy
137 , inits
138 , tails
140 -- ** Breaking into many substrings
141 -- $split
142 , splitOn
143 , split
144 , chunksOf
146 -- ** Breaking into lines and words
147 , lines
148 --, lines'
149 , words
150 , unlines
151 , unwords
153 -- * Predicates
154 , isPrefixOf
155 , isSuffixOf
156 , isInfixOf
158 -- ** View patterns
159 , stripPrefix
160 , stripSuffix
161 , commonPrefixes
163 -- * Searching
164 , filter
165 , breakOnAll
166 , find
167 , partition
169 -- , findSubstring
171 -- * Indexing
172 -- $index
173 , index
174 , findIndex
175 , count
177 -- * Zipping and unzipping
178 , zip
179 , zipWith
181 -- -* Ordered text
182 -- , sort
183 ) where
185import Prelude (Char, Bool(..), Int, Maybe(..), String,
186 Eq(..), Ord(..), Ordering(..), (++),
187 Read(..), Show(..),
188 (&&), (||), (+), (-), (.), ($), ($!), (>>), (*),
189 div, maxBound, not, return, otherwise)
190#if defined(HAVE_DEEPSEQ)
191import Control.DeepSeq (NFData)
192#endif
193#if defined(ASSERTS)
194import Control.Exception (assert)
195#endif
196import Data.Char (isSpace)
197import Data.Data (Data(gfoldl, toConstr, gunfold, dataTypeOf))
198#if __GLASGOW_HASKELL__ >= 612
199import Data.Data (mkNoRepType)
200#else
201import Data.Data (mkNorepType)
202#endif
203import Control.Monad (foldM)
204import qualified Data.Text.Array as A
205import qualified Data.List as L
206import Data.Monoid (Monoid(..))
207import Data.String (IsString(..))
208import qualified Data.Text.Fusion as S
209import qualified Data.Text.Fusion.Common as S
210import Data.Text.Fusion (stream, reverseStream, unstream)
211import Data.Text.Internal (Text(..), empty, firstf, safe, text, textP)
212import qualified Prelude as P
213import Data.Text.Unsafe (Iter(..), iter, iter_, lengthWord16, reverseIter,
214 unsafeHead, unsafeTail)
215import Data.Text.UnsafeChar (unsafeChr)
216import qualified Data.Text.Util as U
217import qualified Data.Text.Encoding.Utf16 as U16
218import Data.Text.Search (indices)
219#if defined(__HADDOCK__)
220import Data.ByteString (ByteString)
221import qualified Data.Text.Lazy as L
222import Data.Int (Int64)
223#endif
225-- $strict
226--
227-- This package provides both strict and lazy 'Text' types. The
228-- strict type is provided by the 'Data.Text' package, while the lazy
229-- type is provided by the 'Data.Text.Lazy' package. Internally, the
230-- lazy @Text@ type consists of a list of strict chunks.
231--
232-- The strict 'Text' type requires that an entire string fit into
233-- memory at once. The lazy @Text@ type is capable of streaming
234-- strings that are larger than memory using a small memory footprint.
235-- In many cases, the overhead of chunked streaming makes the lazy
236-- @Text@ type slower than its strict counterpart, but this is not
237-- always the case. Sometimes, the time complexity of a function in
238-- one module may be different from the other, due to their differing
239-- internal structures.
240--
241-- Each module provides an almost identical API, with the main
242-- difference being that the strict module uses 'Int' values for
243-- lengths and counts, while the lazy module uses 'Int64' lengths.
245-- $replacement
246--
247-- A 'Text' value is a sequence of Unicode scalar values, as defined
248-- in &#xa7;3.9, definition D76 of the Unicode 5.2 standard:
249-- <http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#page=35>. As
250-- such, a 'Text' cannot contain values in the range U+D800 to U+DFFF
251-- inclusive. Haskell implementations admit all Unicode code points
252-- (&#xa7;3.4, definition D10) as 'Char' values, including code points
253-- from this invalid range. This means that there are some 'Char'
254-- values that are not valid Unicode scalar values, and the functions
255-- in this module must handle those cases.
256--
257-- Within this module, many functions construct a 'Text' from one or
258-- more 'Char' values. Those functions will substitute 'Char' values
259-- that are not valid Unicode scalar values with the replacement
260-- character \"&#xfffd;\" (U+FFFD). Functions that perform this
261-- inspection and replacement are documented with the phrase
262-- \"Performs replacement on invalid scalar values\".
263--
264-- (One reason for this policy of replacement is that internally, a
265-- 'Text' value is represented as packed UTF-16 data. Values in the
266-- range U+D800 through U+DFFF are used by UTF-16 to denote surrogate
267-- code points, and so cannot be represented. The functions replace
268-- invalid scalar values, instead of dropping them, as a security
269-- measure. For details, see Unicode Technical Report 36, &#xa7;3.5:
270-- <http://unicode.org/reports/tr36/#Deletion_of_Noncharacters>)
272-- $fusion
273--
274-- Most of the functions in this module are subject to /fusion/,
275-- meaning that a pipeline of such functions will usually allocate at
276-- most one 'Text' value.
277--
278-- As an example, consider the following pipeline:
279--
280-- > import Data.Text as T
281-- > import Data.Text.Encoding as E
282-- > import Data.ByteString (ByteString)
283-- >
284-- > countChars :: ByteString -> Int
285-- > countChars = T.length . T.toUpper . E.decodeUtf8
286--
287-- From the type signatures involved, this looks like it should
288-- allocate one 'ByteString' value, and two 'Text' values. However,
289-- when a module is compiled with optimisation enabled under GHC, the
290-- two intermediate 'Text' values will be optimised away, and the
291-- function will be compiled down to a single loop over the source
292-- 'ByteString'.
293--
294-- Functions that can be fused by the compiler are documented with the
295-- phrase \"Subject to fusion\".
297instance Eq Text where
298 Text arrA offA lenA == Text arrB offB lenB
299 | lenA == lenB = A.equal arrA offA arrB offB lenA
300 | otherwise = False
301 {-# INLINE (==) #-}
303instance Ord Text where
304 compare = compareText
306instance Show Text where
307 showsPrec p ps r = showsPrec p (unpack ps) r
309instance Read Text where
310 readsPrec p str = [(pack x,y) | (x,y) <- readsPrec p str]
312instance Monoid Text where
313 mempty = empty
314 mappend = append
315 mconcat = concat
317instance IsString Text where
318 fromString = pack
320#if defined(HAVE_DEEPSEQ)
321instance NFData Text
322#endif
324-- This instance preserves data abstraction at the cost of inefficiency.
325-- We omit reflection services for the sake of data abstraction.
326--
327-- This instance was created by copying the behavior of Data.Set and
328-- Data.Map. If you feel a mistake has been made, please feel free to
329-- submit improvements.
330--
331-- Original discussion is archived here:
333-- "could we get a Data instance for Data.Text.Text?"
334-- http://groups.google.com/group/haskell-cafe/browse_thread/thread/b5bbb1b28a7e525d/0639d46852575b93
336instance Data Text where
337 gfoldl f z txt = z pack `f` (unpack txt)
338 toConstr _ = P.error "Data.Text.Text.toConstr"
339 gunfold _ _ = P.error "Data.Text.Text.gunfold"
340#if __GLASGOW_HASKELL__ >= 612
341 dataTypeOf _ = mkNoRepType "Data.Text.Text"
342#else
343 dataTypeOf _ = mkNorepType "Data.Text.Text"
344#endif
346-- | /O(n)/ Compare two 'Text' values lexicographically.
347compareText :: Text -> Text -> Ordering
348compareText ta@(Text _arrA _offA lenA) tb@(Text _arrB _offB lenB)
349 | lenA == 0 && lenB == 0 = EQ
350 | otherwise = go 0 0
351 where
352 go !i !j
353 | i >= lenA || j >= lenB = compare lenA lenB
354 | a < b = LT
355 | a > b = GT
356 | otherwise = go (i+di) (j+dj)
357 where Iter a di = iter ta i
358 Iter b dj = iter tb j
360-- -----------------------------------------------------------------------------
361-- * Conversion to/from 'Text'
363-- | /O(n)/ Convert a 'String' into a 'Text'. Subject to
364-- fusion. Performs replacement on invalid scalar values.
365pack :: String -> Text
366pack = unstream . S.streamList . L.map safe
367{-# INLINE [1] pack #-}
369-- | /O(n)/ Convert a Text into a String. Subject to fusion.
370unpack :: Text -> String
371unpack = S.unstreamList . stream
372{-# INLINE [1] unpack #-}
374-- | /O(1)/ Convert a character into a Text. Subject to fusion.
375-- Performs replacement on invalid scalar values.
376singleton :: Char -> Text
377singleton = unstream . S.singleton . safe
378{-# INLINE [1] singleton #-}
380-- -----------------------------------------------------------------------------
381-- * Basic functions
383-- | /O(n)/ Adds a character to the front of a 'Text'. This function
384-- is more costly than its 'List' counterpart because it requires
385-- copying a new array. Subject to fusion. Performs replacement on
386-- invalid scalar values.
387cons :: Char -> Text -> Text
388cons c t = unstream (S.cons (safe c) (stream t))
389{-# INLINE cons #-}
391infixr 5 `cons`
393-- | /O(n)/ Adds a character to the end of a 'Text'. This copies the
394-- entire array in the process, unless fused. Subject to fusion.
395-- Performs replacement on invalid scalar values.
396snoc :: Text -> Char -> Text
397snoc t c = unstream (S.snoc (stream t) (safe c))
398{-# INLINE snoc #-}
400-- | /O(n)/ Appends one 'Text' to the other by copying both of them
401-- into a new 'Text'. Subject to fusion.
402append :: Text -> Text -> Text
403append a@(Text arr1 off1 len1) b@(Text arr2 off2 len2)
404 | len1 == 0 = b
405 | len2 == 0 = a
406 | len > 0 = Text (A.run x) 0 len
407 | otherwise = overflowError "append"
408 where
409 len = len1+len2
410 x = do
411 arr <- A.new len
412 A.copyI arr 0 arr1 off1 len1
413 A.copyI arr len1 arr2 off2 len
414 return arr
415{-# INLINE append #-}
417{-# RULES
418"TEXT append -> fused" [~1] forall t1 t2.
419 append t1 t2 = unstream (S.append (stream t1) (stream t2))
420"TEXT append -> unfused" [1] forall t1 t2.
421 unstream (S.append (stream t1) (stream t2)) = append t1 t2
422 #-}
424-- | /O(1)/ Returns the first character of a 'Text', which must be
425-- non-empty. Subject to fusion.
426head :: Text -> Char
427head t = S.head (stream t)
428{-# INLINE head #-}
430-- | /O(1)/ Returns the first character and rest of a 'Text', or
431-- 'Nothing' if empty. Subject to fusion.
432uncons :: Text -> Maybe (Char, Text)
433uncons t@(Text arr off len)
434 | len <= 0 = Nothing
435 | otherwise = Just (c, textP arr (off+d) (len-d))
436 where Iter c d = iter t 0
437{-# INLINE [1] uncons #-}
439-- | Lifted from Control.Arrow and specialized.
440second :: (b -> c) -> (a,b) -> (a,c)
441second f (a, b) = (a, f b)
443-- | /O(1)/ Returns the last character of a 'Text', which must be
444-- non-empty. Subject to fusion.
445last :: Text -> Char
446last (Text arr off len)
447 | len <= 0 = emptyError "last"
448 | n < 0xDC00 || n > 0xDFFF = unsafeChr n
449 | otherwise = U16.chr2 n0 n
450 where n = A.unsafeIndex arr (off+len-1)
451 n0 = A.unsafeIndex arr (off+len-2)
452{-# INLINE [1] last #-}
454{-# RULES
455"TEXT last -> fused" [~1] forall t.
456 last t = S.last (stream t)
457"TEXT last -> unfused" [1] forall t.
458 S.last (stream t) = last t
459 #-}
461-- | /O(1)/ Returns all characters after the head of a 'Text', which
462-- must be non-empty. Subject to fusion.
463tail :: Text -> Text
464tail t@(Text arr off len)
465 | len <= 0 = emptyError "tail"
466 | otherwise = textP arr (off+d) (len-d)
467 where d = iter_ t 0
468{-# INLINE [1] tail #-}
470{-# RULES
471"TEXT tail -> fused" [~1] forall t.
472 tail t = unstream (S.tail (stream t))
473"TEXT tail -> unfused" [1] forall t.
474 unstream (S.tail (stream t)) = tail t
475 #-}
477-- | /O(1)/ Returns all but the last character of a 'Text', which must
478-- be non-empty. Subject to fusion.
479init :: Text -> Text
480init (Text arr off len) | len <= 0 = emptyError "init"
481 | n >= 0xDC00 && n <= 0xDFFF = textP arr off (len-2)
482 | otherwise = textP arr off (len-1)
483 where
484 n = A.unsafeIndex arr (off+len-1)
485{-# INLINE [1] init #-}
487{-# RULES
488"TEXT init -> fused" [~1] forall t.
489 init t = unstream (S.init (stream t))
490"TEXT init -> unfused" [1] forall t.
491 unstream (S.init (stream t)) = init t
492 #-}
494-- | /O(1)/ Tests whether a 'Text' is empty or not. Subject to
495-- fusion.
496null :: Text -> Bool
497null (Text _arr _off len) =
498#if defined(ASSERTS)
499 assert (len >= 0) $
500#endif
501 len <= 0
502{-# INLINE [1] null #-}
504{-# RULES
505"TEXT null -> fused" [~1] forall t.
506 null t = S.null (stream t)
507"TEXT null -> unfused" [1] forall t.
508 S.null (stream t) = null t
509 #-}
511-- | /O(1)/ Tests whether a 'Text' contains exactly one character.
512-- Subject to fusion.
513isSingleton :: Text -> Bool
514isSingleton = S.isSingleton . stream
515{-# INLINE isSingleton #-}
517-- | /O(n)/ Returns the number of characters in a 'Text'.
518-- Subject to fusion.
519length :: Text -> Int
520length t = S.length (stream t)
521{-# INLINE length #-}
523-- | /O(n)/ Compare the count of characters in a 'Text' to a number.
524-- Subject to fusion.
525--
526-- This function gives the same answer as comparing against the result
527-- of 'length', but can short circuit if the count of characters is
528-- greater than the number, and hence be more efficient.
529compareLength :: Text -> Int -> Ordering
530compareLength t n = S.compareLengthI (stream t) n
531{-# INLINE [1] compareLength #-}
533{-# RULES
534"TEXT compareN/length -> compareLength" [~1] forall t n.
535 compare (length t) n = compareLength t n
536 #-}
538{-# RULES
539"TEXT ==N/length -> compareLength/==EQ" [~1] forall t n.
540 (==) (length t) n = compareLength t n == EQ
541 #-}
543{-# RULES
544"TEXT /=N/length -> compareLength//=EQ" [~1] forall t n.
545 (/=) (length t) n = compareLength t n /= EQ
546 #-}
548{-# RULES
549"TEXT <N/length -> compareLength/==LT" [~1] forall t n.
550 (<) (length t) n = compareLength t n == LT
551 #-}
553{-# RULES
554"TEXT <=N/length -> compareLength//=GT" [~1] forall t n.
555 (<=) (length t) n = compareLength t n /= GT
556 #-}
558{-# RULES
559"TEXT >N/length -> compareLength/==GT" [~1] forall t n.
560 (>) (length t) n = compareLength t n == GT
561 #-}
563{-# RULES
564"TEXT >=N/length -> compareLength//=LT" [~1] forall t n.
565 (>=) (length t) n = compareLength t n /= LT
566 #-}
568-- -----------------------------------------------------------------------------
569-- * Transformations
570-- | /O(n)/ 'map' @f@ @t@ is the 'Text' obtained by applying @f@ to
571-- each element of @t@. Subject to fusion. Performs replacement on
572-- invalid scalar values.
573map :: (Char -> Char) -> Text -> Text
574map f t = unstream (S.map (safe . f) (stream t))
575{-# INLINE [1] map #-}
577-- | /O(n)/ The 'intercalate' function takes a 'Text' and a list of
578-- 'Text's and concatenates the list after interspersing the first
579-- argument between each element of the list.
580intercalate :: Text -> [Text] -> Text
581intercalate t = concat . (U.intersperse t)
582{-# INLINE intercalate #-}
584-- | /O(n)/ The 'intersperse' function takes a character and places it
585-- between the characters of a 'Text'. Subject to fusion. Performs
586-- replacement on invalid scalar values.
587intersperse :: Char -> Text -> Text
588intersperse c t = unstream (S.intersperse (safe c) (stream t))
589{-# INLINE intersperse #-}
591-- | /O(n)/ Reverse the characters of a string. Subject to fusion.
592reverse :: Text -> Text
593reverse t = S.reverse (stream t)
594{-# INLINE reverse #-}
596-- | /O(m+n)/ Replace every occurrence of one substring with another.
597--
598-- In (unlikely) bad cases, this function's time complexity degrades
599-- towards /O(n*m)/.
600replace :: Text -- ^ Text to search for
601 -> Text -- ^ Replacement text
602 -> Text -- ^ Input text
603 -> Text
604replace s d = intercalate d . splitOn s
605{-# INLINE replace #-}
607-- ----------------------------------------------------------------------------
608-- ** Case conversions (folds)
610-- $case
611--
612-- When case converting 'Text' values, do not use combinators like
613-- @map toUpper@ to case convert each character of a string
614-- individually, as this gives incorrect results according to the
615-- rules of some writing systems. The whole-string case conversion
616-- functions from this module, such as @toUpper@, obey the correct
617-- case conversion rules. As a result, these functions may map one
618-- input character to two or three output characters. For examples,
619-- see the documentation of each function.
620--
621-- /Note/: In some languages, case conversion is a locale- and
622-- context-dependent operation. The case conversion functions in this
623-- module are /not/ locale sensitive. Programs that require locale
624-- sensitivity should use appropriate versions of the case mapping
625-- functions from the @text-icu@ package:
626-- <http://hackage.haskell.org/package/text-icu>
628-- | /O(n)/ Convert a string to folded case. This function is mainly
629-- useful for performing caseless (also known as case insensitive)
630-- string comparisons.
631--
632-- A string @x@ is a caseless match for a string @y@ if and only if:
633--
634-- @toCaseFold x == toCaseFold y@
635--
636-- The result string may be longer than the input string, and may
637-- differ from applying 'toLower' to the input string. For instance,
638-- the Armenian small ligature \"&#xfb13;\" (men now, U+FB13) is case
639-- folded to the sequence \"&#x574;\" (men, U+0574) followed by
640-- \"&#x576;\" (now, U+0576), while the Greek \"&#xb5;\" (micro sign,
641-- U+00B5) is case folded to \"&#x3bc;\" (small letter mu, U+03BC)
642-- instead of itself.
643toCaseFold :: Text -> Text
644toCaseFold t = unstream (S.toCaseFold (stream t))
645{-# INLINE [0] toCaseFold #-}
647-- | /O(n)/ Convert a string to lower case, using simple case
648-- conversion. The result string may be longer than the input string.
649-- For instance, \"&#x130;\" (Latin capital letter I with dot above,
650-- U+0130) maps to the sequence \"i\" (Latin small letter i, U+0069) followed
651-- by \" &#x307;\" (combining dot above, U+0307).
652toLower :: Text -> Text
653toLower t = unstream (S.toLower (stream t))
654{-# INLINE toLower #-}
656-- | /O(n)/ Convert a string to upper case, using simple case
657-- conversion. The result string may be longer than the input string.
658-- For instance, the German \"&#xdf;\" (eszett, U+00DF) maps to the
659-- two-letter sequence \"SS\".
660toUpper :: Text -> Text
661toUpper t = unstream (S.toUpper (stream t))
662{-# INLINE toUpper #-}
664-- | /O(n)/ Left-justify a string to the given length, using the
665-- specified fill character on the right. Subject to fusion.
666-- Performs replacement on invalid scalar values.
667--
668-- Examples:
669--
670-- > justifyLeft 7 'x' "foo" == "fooxxxx"
671-- > justifyLeft 3 'x' "foobar" == "foobar"
672justifyLeft :: Int -> Char -> Text -> Text
673justifyLeft k c t
674 | len >= k = t
675 | otherwise = t `append` replicateChar (k-len) c
676 where len = length t
677{-# INLINE [1] justifyLeft #-}
679{-# RULES
680"TEXT justifyLeft -> fused" [~1] forall k c t.
681 justifyLeft k c t = unstream (S.justifyLeftI k c (stream t))
682"TEXT justifyLeft -> unfused" [1] forall k c t.
683 unstream (S.justifyLeftI k c (stream t)) = justifyLeft k c t
684 #-}
686-- | /O(n)/ Right-justify a string to the given length, using the
687-- specified fill character on the left. Performs replacement on
688-- invalid scalar values.
689--
690-- Examples:
691--
692-- > justifyRight 7 'x' "bar" == "xxxxbar"
693-- > justifyRight 3 'x' "foobar" == "foobar"
694justifyRight :: Int -> Char -> Text -> Text
695justifyRight k c t
696 | len >= k = t
697 | otherwise = replicateChar (k-len) c `append` t
698 where len = length t
699{-# INLINE justifyRight #-}
701-- | /O(n)/ Center a string to the given length, using the specified
702-- fill character on either side. Performs replacement on invalid
703-- scalar values.
704--
705-- Examples:
706--
707-- > center 8 'x' "HS" = "xxxHSxxx"
708center :: Int -> Char -> Text -> Text
709center k c t
710 | len >= k = t
711 | otherwise = replicateChar l c `append` t `append` replicateChar r c
712 where len = length t
713 d = k - len
714 r = d `div` 2
715 l = d - r
716{-# INLINE center #-}
718-- | /O(n)/ The 'transpose' function transposes the rows and columns
719-- of its 'Text' argument. Note that this function uses 'pack',
720-- 'unpack', and the list version of transpose, and is thus not very
721-- efficient.
722transpose :: [Text] -> [Text]
723transpose ts = P.map pack (L.transpose (P.map unpack ts))
725-- -----------------------------------------------------------------------------
726-- * Reducing 'Text's (folds)
728-- | /O(n)/ 'foldl', applied to a binary operator, a starting value
729-- (typically the left-identity of the operator), and a 'Text',
730-- reduces the 'Text' using the binary operator, from left to right.
731-- Subject to fusion.
732foldl :: (a -> Char -> a) -> a -> Text -> a
733foldl f z t = S.foldl f z (stream t)
734{-# INLINE foldl #-}
736-- | /O(n)/ A strict version of 'foldl'. Subject to fusion.
737foldl' :: (a -> Char -> a) -> a -> Text -> a
738foldl' f z t = S.foldl' f z (stream t)
739{-# INLINE foldl' #-}
741-- | /O(n)/ A variant of 'foldl' that has no starting value argument,
742-- and thus must be applied to a non-empty 'Text'. Subject to fusion.
743foldl1 :: (Char -> Char -> Char) -> Text -> Char
744foldl1 f t = S.foldl1 f (stream t)
745{-# INLINE foldl1 #-}
747-- | /O(n)/ A strict version of 'foldl1'. Subject to fusion.
748foldl1' :: (Char -> Char -> Char) -> Text -> Char
749foldl1' f t = S.foldl1' f (stream t)
750{-# INLINE foldl1' #-}
752-- | /O(n)/ 'foldr', applied to a binary operator, a starting value
753-- (typically the right-identity of the operator), and a 'Text',
754-- reduces the 'Text' using the binary operator, from right to left.
755-- Subject to fusion.
756foldr :: (Char -> a -> a) -> a -> Text -> a
757foldr f z t = S.foldr f z (stream t)
758{-# INLINE foldr #-}
760-- | /O(n)/ A variant of 'foldr' that has no starting value argument,
761-- and thust must be applied to a non-empty 'Text'. Subject to
762-- fusion.
763foldr1 :: (Char -> Char -> Char) -> Text -> Char
764foldr1 f t = S.foldr1 f (stream t)
765{-# INLINE foldr1 #-}
767-- -----------------------------------------------------------------------------
768-- ** Special folds
770-- | /O(n)/ Concatenate a list of 'Text's.
771concat :: [Text] -> Text
772concat ts = case ts' of
773 [] -> empty
774 [t] -> t
775 _ -> Text (A.run go) 0 len
776 where
777 ts' = L.filter (not . null) ts
778 len = sumP "concat" $ L.map lengthWord16 ts'
779 go = do
780 arr <- A.new len
781 let step i (Text a o l) =
782 let !j = i + l in A.copyI arr i a o j >> return j
783 foldM step 0 ts' >> return arr
785-- | /O(n)/ Map a function over a 'Text' that results in a 'Text', and
786-- concatenate the results.
787concatMap :: (Char -> Text) -> Text -> Text
788concatMap f = concat . foldr ((:) . f) []
789{-# INLINE concatMap #-}
791-- | /O(n)/ 'any' @p@ @t@ determines whether any character in the
792-- 'Text' @t@ satisifes the predicate @p@. Subject to fusion.
793any :: (Char -> Bool) -> Text -> Bool
794any p t = S.any p (stream t)
795{-# INLINE any #-}
797-- | /O(n)/ 'all' @p@ @t@ determines whether all characters in the
798-- 'Text' @t@ satisify the predicate @p@. Subject to fusion.
799all :: (Char -> Bool) -> Text -> Bool
800all p t = S.all p (stream t)
801{-# INLINE all #-}
803-- | /O(n)/ 'maximum' returns the maximum value from a 'Text', which
804-- must be non-empty. Subject to fusion.
805maximum :: Text -> Char
806maximum t = S.maximum (stream t)
807{-# INLINE maximum #-}
809-- | /O(n)/ 'minimum' returns the minimum value from a 'Text', which
810-- must be non-empty. Subject to fusion.
811minimum :: Text -> Char
812minimum t = S.minimum (stream t)
813{-# INLINE minimum #-}
815-- -----------------------------------------------------------------------------
816-- * Building 'Text's
818-- | /O(n)/ 'scanl' is similar to 'foldl', but returns a list of
819-- successive reduced values from the left. Subject to fusion.
820-- Performs replacement on invalid scalar values.
821--
822-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
823--
824-- Note that
825--
826-- > last (scanl f z xs) == foldl f z xs.
827scanl :: (Char -> Char -> Char) -> Char -> Text -> Text
828scanl f z t = unstream (S.scanl g z (stream t))
829 where g a b = safe (f a b)
830{-# INLINE scanl #-}
832-- | /O(n)/ 'scanl1' is a variant of 'scanl' that has no starting
833-- value argument. Subject to fusion. Performs replacement on
834-- invalid scalar values.
835--
836-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
837scanl1 :: (Char -> Char -> Char) -> Text -> Text
838scanl1 f t | null t = empty
839 | otherwise = scanl f (unsafeHead t) (unsafeTail t)
840{-# INLINE scanl1 #-}
842-- | /O(n)/ 'scanr' is the right-to-left dual of 'scanl'. Performs
843-- replacement on invalid scalar values.
844--
845-- > scanr f v == reverse . scanl (flip f) v . reverse
846scanr :: (Char -> Char -> Char) -> Char -> Text -> Text
847scanr f z = S.reverse . S.reverseScanr g z . reverseStream
848 where g a b = safe (f a b)
849{-# INLINE scanr #-}
851-- | /O(n)/ 'scanr1' is a variant of 'scanr' that has no starting
852-- value argument. Subject to fusion. Performs replacement on
853-- invalid scalar values.
854scanr1 :: (Char -> Char -> Char) -> Text -> Text
855scanr1 f t | null t = empty
856 | otherwise = scanr f (last t) (init t)
857{-# INLINE scanr1 #-}
859-- | /O(n)/ Like a combination of 'map' and 'foldl''. Applies a
860-- function to each element of a 'Text', passing an accumulating
861-- parameter from left to right, and returns a final 'Text'. Performs
862-- replacement on invalid scalar values.
863mapAccumL :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
864mapAccumL f z0 = S.mapAccumL g z0 . stream
865 where g a b = second safe (f a b)
866{-# INLINE mapAccumL #-}
868-- | The 'mapAccumR' function behaves like a combination of 'map' and
869-- a strict 'foldr'; it applies a function to each element of a
870-- 'Text', passing an accumulating parameter from right to left, and
871-- returning a final value of this accumulator together with the new
872-- 'Text'.
873-- Performs replacement on invalid scalar values.
874mapAccumR :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
875mapAccumR f z0 = second reverse . S.mapAccumL g z0 . reverseStream
876 where g a b = second safe (f a b)
877{-# INLINE mapAccumR #-}
879-- -----------------------------------------------------------------------------
880-- ** Generating and unfolding 'Text's
882-- | /O(n*m)/ 'replicate' @n@ @t@ is a 'Text' consisting of the input
883-- @t@ repeated @n@ times.
884replicate :: Int -> Text -> Text
885replicate n t@(Text a o l)
886 | n <= 0 || l <= 0 = empty
887 | n == 1 = t
888 | isSingleton t = replicateChar n (unsafeHead t)
889 | n <= maxBound `div` l = Text (A.run x) 0 len
890 | otherwise = overflowError "replicate"
891 where
892 len = l * n
893 x = do
894 arr <- A.new len
895 let loop !d !i | i >= n = return arr
896 | otherwise = let m = d + l
897 in A.copyI arr d a o m >> loop m (i+1)
898 loop 0 0
899{-# INLINE [1] replicate #-}
901{-# RULES
902"TEXT replicate/singleton -> replicateChar" [~1] forall n c.
903 replicate n (singleton c) = replicateChar n c
904 #-}
906-- | /O(n)/ 'replicateChar' @n@ @c@ is a 'Text' of length @n@ with @c@ the
907-- value of every element. Subject to fusion.
908replicateChar :: Int -> Char -> Text
909replicateChar n c = unstream (S.replicateCharI n (safe c))
910{-# INLINE replicateChar #-}
912-- | /O(n)/, where @n@ is the length of the result. The 'unfoldr'
913-- function is analogous to the List 'L.unfoldr'. 'unfoldr' builds a
914-- 'Text' from a seed value. The function takes the element and
915-- returns 'Nothing' if it is done producing the 'Text', otherwise
916-- 'Just' @(a,b)@. In this case, @a@ is the next 'Char' in the
917-- string, and @b@ is the seed value for further production. Subject
918-- to fusion. Performs replacement on invalid scalar values.
919unfoldr :: (a -> Maybe (Char,a)) -> a -> Text
920unfoldr f s = unstream (S.unfoldr (firstf safe . f) s)
921{-# INLINE unfoldr #-}
923-- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a 'Text' from a seed
924-- value. However, the length of the result should be limited by the
925-- first argument to 'unfoldrN'. This function is more efficient than
926-- 'unfoldr' when the maximum length of the result is known and
927-- correct, otherwise its performance is similar to 'unfoldr'. Subject
928-- to fusion. Performs replacement on invalid scalar values.
929unfoldrN :: Int -> (a -> Maybe (Char,a)) -> a -> Text
930unfoldrN n f s = unstream (S.unfoldrN n (firstf safe . f) s)
931{-# INLINE unfoldrN #-}
933-- -----------------------------------------------------------------------------
934-- * Substrings
936-- | /O(n)/ 'take' @n@, applied to a 'Text', returns the prefix of the
937-- 'Text' of length @n@, or the 'Text' itself if @n@ is greater than
938-- the length of the Text. Subject to fusion.
939take :: Int -> Text -> Text
940take n t@(Text arr off len)
941 | n <= 0 = empty
942 | n >= len = t
943 | otherwise = Text arr off (loop 0 0)
944 where
945 loop !i !cnt
946 | i >= len || cnt >= n = i
947 | otherwise = loop (i+d) (cnt+1)
948 where d = iter_ t i
949{-# INLINE [1] take #-}
951{-# RULES
952"TEXT take -> fused" [~1] forall n t.
953 take n t = unstream (S.take n (stream t))
954"TEXT take -> unfused" [1] forall n t.
955 unstream (S.take n (stream t)) = take n t
956 #-}
958-- | /O(n)/ 'drop' @n@, applied to a 'Text', returns the suffix of the
959-- 'Text' after the first @n@ characters, or the empty 'Text' if @n@
960-- is greater than the length of the 'Text'. Subject to fusion.
961drop :: Int -> Text -> Text
962drop n t@(Text arr off len)
963 | n <= 0 = t
964 | n >= len = empty
965 | otherwise = loop 0 0
966 where loop !i !cnt
967 | i >= len || cnt >= n = Text arr (off+i) (len-i)
968 | otherwise = loop (i+d) (cnt+1)
969 where d = iter_ t i
970{-# INLINE [1] drop #-}
972{-# RULES
973"TEXT drop -> fused" [~1] forall n t.
974 drop n t = unstream (S.drop n (stream t))
975"TEXT drop -> unfused" [1] forall n t.
976 unstream (S.drop n (stream t)) = drop n t
977 #-}
979-- | /O(n)/ 'takeWhile', applied to a predicate @p@ and a 'Text',
980-- returns the longest prefix (possibly empty) of elements that
981-- satisfy @p@. Subject to fusion.
982takeWhile :: (Char -> Bool) -> Text -> Text
983takeWhile p t@(Text arr off len) = loop 0
984 where loop !i | i >= len = t
985 | p c = loop (i+d)
986 | otherwise = textP arr off i
987 where Iter c d = iter t i
988{-# INLINE [1] takeWhile #-}
990{-# RULES
991"TEXT takeWhile -> fused" [~1] forall p t.
992 takeWhile p t = unstream (S.takeWhile p (stream t))
993"TEXT takeWhile -> unfused" [1] forall p t.
994 unstream (S.takeWhile p (stream t)) = takeWhile p t
995 #-}
997-- | /O(n)/ 'dropWhile' @p@ @t@ returns the suffix remaining after
998-- 'takeWhile' @p@ @t@. Subject to fusion.
999dropWhile :: (Char -> Bool) -> Text -> Text
1000dropWhile p t@(Text arr off len) = loop 0 0
1001 where loop !i !l | l >= len = empty
1002 | p c = loop (i+d) (l+d)
1003 | otherwise = Text arr (off+i) (len-l)
1004 where Iter c d = iter t i
1005{-# INLINE [1] dropWhile #-}
1007{-# RULES
1008"TEXT dropWhile -> fused" [~1] forall p t.
1009 dropWhile p t = unstream (S.dropWhile p (stream t))
1010"TEXT dropWhile -> unfused" [1] forall p t.
1011 unstream (S.dropWhile p (stream t)) = dropWhile p t
1012 #-}
1014-- | /O(n)/ 'dropWhileEnd' @p@ @t@ returns the prefix remaining after
1015-- dropping characters that fail the predicate @p@ from the end of
1016-- @t@. Subject to fusion.
1017-- Examples:
1019-- > dropWhileEnd (=='.') "foo..." == "foo"
1020dropWhileEnd :: (Char -> Bool) -> Text -> Text
1021dropWhileEnd p t@(Text arr off len) = loop (len-1) len
1022 where loop !i !l | l <= 0 = empty
1023 | p c = loop (i+d) (l+d)
1024 | otherwise = Text arr off l
1025 where (c,d) = reverseIter t i
1026{-# INLINE [1] dropWhileEnd #-}
1028{-# RULES
1029"TEXT dropWhileEnd -> fused" [~1] forall p t.
1030 dropWhileEnd p t = S.reverse (S.dropWhile p (S.reverseStream t))
1031"TEXT dropWhileEnd -> unfused" [1] forall p t.
1032 S.reverse (S.dropWhile p (S.reverseStream t)) = dropWhileEnd p t
1033 #-}
1035-- | /O(n)/ 'dropAround' @p@ @t@ returns the substring remaining after
1036-- dropping characters that fail the predicate @p@ from both the
1037-- beginning and end of @t@. Subject to fusion.
1038dropAround :: (Char -> Bool) -> Text -> Text
1039dropAround p = dropWhile p . dropWhileEnd p
1040{-# INLINE [1] dropAround #-}
1042-- | /O(n)/ Remove leading white space from a string. Equivalent to:
1044-- > dropWhile isSpace
1045stripStart :: Text -> Text
1046stripStart = dropWhile isSpace
1047{-# INLINE [1] stripStart #-}
1049-- | /O(n)/ Remove trailing white space from a string. Equivalent to:
1051-- > dropWhileEnd isSpace
1052stripEnd :: Text -> Text
1053stripEnd = dropWhileEnd isSpace
1054{-# INLINE [1] stripEnd #-}
1056-- | /O(n)/ Remove leading and trailing white space from a string.
1057-- Equivalent to:
1059-- > dropAround isSpace
1060strip :: Text -> Text
1061strip = dropAround isSpace
1062{-# INLINE [1] strip #-}
1064-- | /O(n)/ 'splitAt' @n t@ returns a pair whose first element is a
1065-- prefix of @t@ of length @n@, and whose second is the remainder of
1066-- the string. It is equivalent to @('take' n t, 'drop' n t)@.
1067splitAt :: Int -> Text -> (Text, Text)
1068splitAt n t@(Text arr off len)
1069 | n <= 0 = (empty, t)
1070 | n >= len = (t, empty)
1071 | otherwise = (Text arr off k, Text arr (off+k) (len-k))
1072 where k = loop 0 0
1073 loop !i !cnt
1074 | i >= len || cnt >= n = i
1075 | otherwise = loop (i+d) (cnt+1)
1076 where d = iter_ t i
1077{-# INLINE splitAt #-}
1079-- | /O(n)/ 'span', applied to a predicate @p@ and text @t@, returns
1080-- a pair whose first element is the longest prefix (possibly empty)
1081-- of @t@ of elements that satisfy @p@, and whose second is the
1082-- remainder of the list.
1083span :: (Char -> Bool) -> Text -> (Text, Text)
1084span p t@(Text arr off len) = (textP arr off k, textP arr (off+k) (len-k))
1085 where k = loop 0
1086 loop !i | i >= len || not (p c) = i
1087 | otherwise = loop (i+d)
1088 where Iter c d = iter t i
1089{-# INLINE span #-}
1091-- | /O(n)/ 'break' is like 'span', but the prefix returned is
1092-- over elements that fail the predicate @p@.
1093break :: (Char -> Bool) -> Text -> (Text, Text)
1094break p = span (not . p)
1095{-# INLINE break #-}
1097-- | /O(n)/ Group characters in a string according to a predicate.
1098groupBy :: (Char -> Char -> Bool) -> Text -> [Text]
1099groupBy p = loop
1100 where
1101 loop t@(Text arr off len)
1102 | null t = []
1103 | otherwise = text arr off n : loop (text arr (off+n) (len-n))
1104 where Iter c d = iter t 0
1105 n = d + findAIndexOrEnd (not . p c) (Text arr (off+d) (len-d))
1107-- | Returns the /array/ index (in units of 'Word16') at which a
1108-- character may be found. This is /not/ the same as the logical
1109-- index returned by e.g. 'findIndex'.
1110findAIndexOrEnd :: (Char -> Bool) -> Text -> Int
1111findAIndexOrEnd q t@(Text _arr _off len) = go 0
1112 where go !i | i >= len || q c = i
1113 | otherwise = go (i+d)
1114 where Iter c d = iter t i
1116-- | /O(n)/ Group characters in a string by equality.
1117group :: Text -> [Text]
1118group = groupBy (==)
1120-- | /O(n)/ Return all initial segments of the given 'Text', shortest
1121-- first.
1122inits :: Text -> [Text]
1123inits t@(Text arr off len) = loop 0
1124 where loop i | i >= len = [t]
1125 | otherwise = Text arr off i : loop (i + iter_ t i)
1127-- | /O(n)/ Return all final segments of the given 'Text', longest
1128-- first.
1129tails :: Text -> [Text]
1130tails t | null t = [empty]
1131 | otherwise = t : tails (unsafeTail t)
1133-- $split
1135-- Splitting functions in this library do not perform character-wise
1136-- copies to create substrings; they just construct new 'Text's that
1137-- are slices of the original.
1139-- | /O(m+n)/ Break a 'Text' into pieces separated by the first
1140-- 'Text' argument, consuming the delimiter. An empty delimiter is
1141-- invalid, and will cause an error to be raised.
1143-- Examples:
1145-- > splitOn "\r\n" "a\r\nb\r\nd\r\ne" == ["a","b","d","e"]
1146-- > splitOn "aaa" "aaaXaaaXaaaXaaa" == ["","X","X","X",""]
1147-- > splitOn "x" "x" == ["",""]
1148--
1149-- and
1151-- > intercalate s . splitOn s == id
1152-- > splitOn (singleton c) == split (==c)
1154-- In (unlikely) bad cases, this function's time complexity degrades
1155-- towards /O(n*m)/.
1156splitOn :: Text -> Text -> [Text]
1157splitOn pat@(Text _ _ l) src@(Text arr off len)
1158 | l <= 0 = emptyError "splitOn"
1159 | isSingleton pat = split (== unsafeHead pat) src
1160 | otherwise = go 0 (indices pat src)
1161 where
1162 go !s (x:xs) = textP arr (s+off) (x-s) : go (x+l) xs
1163 go s _ = [textP arr (s+off) (len-s)]
1164{-# INLINE [1] splitOn #-}
1166{-# RULES
1167"TEXT splitOn/singleton -> split/==" [~1] forall c t.
1168 splitOn (singleton c) t = split (==c) t
1169 #-}
1171-- | /O(n)/ Splits a 'Text' into components delimited by separators,
1172-- where the predicate returns True for a separator element. The
1173-- resulting components do not contain the separators. Two adjacent
1174-- separators result in an empty component in the output. eg.
1176-- > split (=='a') "aabbaca" == ["","","bb","c",""]
1177-- > split (=='a') "" == [""]
1178split :: (Char -> Bool) -> Text -> [Text]
1179split _ t@(Text _off _arr 0) = [t]
1180split p t = loop t
1181 where loop s | null s' = [l]
1182 | otherwise = l : loop (unsafeTail s')
1183 where (l, s') = break p s
1184{-# INLINE split #-}
1186-- | /O(n)/ Splits a 'Text' into components of length @k@. The last
1187-- element may be shorter than the other chunks, depending on the
1188-- length of the input. Examples:
1190-- > chunksOf 3 "foobarbaz" == ["foo","bar","baz"]
1191-- > chunksOf 4 "haskell.org" == ["hask","ell.","org"]
1192chunksOf :: Int -> Text -> [Text]
1193chunksOf k = go
1194 where
1195 go t = case splitAt k t of
1196 (a,b) | null a -> []
1197 | otherwise -> a : go b
1198{-# INLINE chunksOf #-}
1200-- ----------------------------------------------------------------------------
1201-- * Searching
1203-------------------------------------------------------------------------------
1204-- ** Searching with a predicate
1206-- | /O(n)/ The 'find' function takes a predicate and a 'Text', and
1207-- returns the first element matching the predicate, or 'Nothing' if
1208-- there is no such element.
1209find :: (Char -> Bool) -> Text -> Maybe Char
1210find p t = S.findBy p (stream t)
1211{-# INLINE find #-}
1213-- | /O(n)/ The 'partition' function takes a predicate and a 'Text',
1214-- and returns the pair of 'Text's with elements which do and do not
1215-- satisfy the predicate, respectively; i.e.
1217-- > partition p t == (filter p t, filter (not . p) t)
1218partition :: (Char -> Bool) -> Text -> (Text, Text)
1219partition p t = (filter p t, filter (not . p) t)
1220{-# INLINE partition #-}
1222-- | /O(n)/ 'filter', applied to a predicate and a 'Text',
1223-- returns a 'Text' containing those characters that satisfy the
1224-- predicate.
1225filter :: (Char -> Bool) -> Text -> Text
1226filter p t = unstream (S.filter p (stream t))
1227{-# INLINE filter #-}
1229-- | /O(n+m)/ Find the first instance of @needle@ (which must be
1230-- non-'null') in @haystack@. The first element of the returned tuple
1231-- is the prefix of @haystack@ before @needle@ is matched. The second
1232-- is the remainder of @haystack@, starting with the match.
1234-- Examples:
1236-- > breakOn "::" "a::b::c" ==> ("a", "::b::c")
1237-- > breakOn "/" "foobar" ==> ("foobar", "")
1239-- Laws:
1241-- > append prefix match == haystack
1242-- > where (prefix, match) = breakOn needle haystack
1244-- If you need to break a string by a substring repeatedly (e.g. you
1245-- want to break on every instance of a substring), use 'breakOnAll'
1246-- instead, as it has lower startup overhead.
1248-- In (unlikely) bad cases, this function's time complexity degrades
1249-- towards /O(n*m)/.
1250breakOn :: Text -> Text -> (Text, Text)
1251breakOn pat src@(Text arr off len)
1252 | null pat = emptyError "breakOn"
1253 | otherwise = case indices pat src of
1254 [] -> (src, empty)
1255 (x:_) -> (textP arr off x, textP arr (off+x) (len-x))
1256{-# INLINE breakOn #-}
1258-- | /O(n+m)/ Similar to 'breakOn', but searches from the end of the
1259-- string.
1261-- The first element of the returned tuple is the prefix of @haystack@
1262-- up to and including the last match of @needle@. The second is the
1263-- remainder of @haystack@, following the match.
1265-- > breakOnEnd "::" "a::b::c" ==> ("a::b::", "c")
1266breakOnEnd :: Text -> Text -> (Text, Text)
1267breakOnEnd pat src = (reverse b, reverse a)
1268 where (a,b) = breakOn (reverse pat) (reverse src)
1269{-# INLINE breakOnEnd #-}
1271-- | /O(n+m)/ Find all non-overlapping instances of @needle@ in
1272-- @haystack@. Each element of the returned list consists of a pair:
1274-- * The entire string prior to the /k/th match (i.e. the prefix)
1276-- * The /k/th match, followed by the remainder of the string
1278-- Examples:
1280-- > find "::" ""
1281-- > ==> []
1282-- > find "/" "a/b/c/"
1283-- > ==> [("a", "/b/c/"), ("a/b", "/c/"), ("a/b/c", "/")]
1285-- In (unlikely) bad cases, this function's time complexity degrades
1286-- towards /O(n*m)/.
1288-- The @needle@ parameter may not be empty.
1289breakOnAll :: Text -- ^ @needle@ to search for
1290 -> Text -- ^ @haystack@ in which to search
1291 -> [(Text, Text)]
1292breakOnAll pat src@(Text arr off slen)
1293 | null pat = emptyError "breakOnAll"
1294 | otherwise = L.map step (indices pat src)
1295 where
1296 step x = (chunk 0 x, chunk x (slen-x))
1297 chunk !n !l = textP arr (n+off) l
1298{-# INLINE breakOnAll #-}
1300-------------------------------------------------------------------------------
1301-- ** Indexing 'Text's
1303-- $index
1305-- If you think of a 'Text' value as an array of 'Char' values (which
1306-- it is not), you run the risk of writing inefficient code.
1308-- An idiom that is common in some languages is to find the numeric
1309-- offset of a character or substring, then use that number to split
1310-- or trim the searched string. With a 'Text' value, this approach
1311-- would require two /O(n)/ operations: one to perform the search, and
1312-- one to operate from wherever the search ended.
1314-- For example, suppose you have a string that you want to split on
1315-- the substring @\"::\"@, such as @\"foo::bar::quux\"@. Instead of
1316-- searching for the index of @\"::\"@ and taking the substrings
1317-- before and after that index, you would instead use @find \"::\"@.
1319-- | /O(n)/ 'Text' index (subscript) operator, starting from 0.
1320index :: Text -> Int -> Char
1321index t n = S.index (stream t) n
1322{-# INLINE index #-}
1324-- | /O(n)/ The 'findIndex' function takes a predicate and a 'Text'
1325-- and returns the index of the first element in the 'Text' satisfying
1326-- the predicate. Subject to fusion.
1327findIndex :: (Char -> Bool) -> Text -> Maybe Int
1328findIndex p t = S.findIndex p (stream t)
1329{-# INLINE findIndex #-}
1331-- | /O(n+m)/ The 'count' function returns the number of times the
1332-- query string appears in the given 'Text'. An empty query string is
1333-- invalid, and will cause an error to be raised.
1335-- In (unlikely) bad cases, this function's time complexity degrades
1336-- towards /O(n*m)/.
1337count :: Text -> Text -> Int
1338count pat src
1339 | null pat = emptyError "count"
1340 | isSingleton pat = countChar (unsafeHead pat) src
1341 | otherwise = L.length (indices pat src)
1342{-# INLINE [1] count #-}
1344{-# RULES
1345"TEXT count/singleton -> countChar" [~1] forall c t.
1346 count (singleton c) t = countChar c t
1347 #-}
1349-- | /O(n)/ The 'countChar' function returns the number of times the
1350-- query element appears in the given 'Text'. Subject to fusion.
1351countChar :: Char -> Text -> Int
1352countChar c t = S.countChar c (stream t)
1353{-# INLINE countChar #-}
1355-------------------------------------------------------------------------------
1356-- * Zipping
1358-- | /O(n)/ 'zip' takes two 'Text's and returns a list of
1359-- corresponding pairs of bytes. If one input 'Text' is short,
1360-- excess elements of the longer 'Text' are discarded. This is
1361-- equivalent to a pair of 'unpack' operations.
1362zip :: Text -> Text -> [(Char,Char)]
1363zip a b = S.unstreamList $ S.zipWith (,) (stream a) (stream b)
1364{-# INLINE [0] zip #-}
1366-- | /O(n)/ 'zipWith' generalises 'zip' by zipping with the function
1367-- given as the first argument, instead of a tupling function.
1368-- Performs replacement on invalid scalar values.
1369zipWith :: (Char -> Char -> Char) -> Text -> Text -> Text
1370zipWith f t1 t2 = unstream (S.zipWith g (stream t1) (stream t2))
1371 where g a b = safe (f a b)
1372{-# INLINE [0] zipWith #-}
1374-- | /O(n)/ Breaks a 'Text' up into a list of words, delimited by 'Char's
1375-- representing white space.
1376words :: Text -> [Text]
1377words t@(Text arr off len) = loop 0 0
1378 where
1379 loop !start !n
1380 | n >= len = if start == n
1381 then []
1382 else [Text arr (start+off) (n-start)]
1383 | isSpace c =
1384 if start == n
1385 then loop (start+1) (start+1)
1386 else Text arr (start+off) (n-start) : loop (n+d) (n+d)
1387 | otherwise = loop start (n+d)
1388 where Iter c d = iter t n
1389{-# INLINE words #-}
1391-- | /O(n)/ Breaks a 'Text' up into a list of 'Text's at
1392-- newline 'Char's. The resulting strings do not contain newlines.
1393lines :: Text -> [Text]
1394lines ps | null ps = []
1395 | otherwise = h : if null t
1396 then []
1397 else lines (unsafeTail t)
1398 where (h,t) = span (/= '\n') ps
1399{-# INLINE lines #-}
1402-- | /O(n)/ Portably breaks a 'Text' up into a list of 'Text's at line
1403-- boundaries.
1405-- A line boundary is considered to be either a line feed, a carriage
1406-- return immediately followed by a line feed, or a carriage return.
1407-- This accounts for both Unix and Windows line ending conventions,
1408-- and for the old convention used on Mac OS 9 and earlier.
1409lines' :: Text -> [Text]
1410lines' ps | null ps = []
1411 | otherwise = h : case uncons t of
1412 Nothing -> []
1413 Just (c,t')
1414 | c == '\n' -> lines t'
1415 | c == '\r' -> case uncons t' of
1416 Just ('\n',t'') -> lines t''
1417 _ -> lines t'
1418 where (h,t) = span notEOL ps
1419 notEOL c = c /= '\n' && c /= '\r'
1420{-# INLINE lines' #-}
1423-- | /O(n)/ Joins lines, after appending a terminating newline to
1424-- each.
1425unlines :: [Text] -> Text
1426unlines = concat . L.map (`snoc` '\n')
1427{-# INLINE unlines #-}
1429-- | /O(n)/ Joins words using single space characters.
1430unwords :: [Text] -> Text
1431unwords = intercalate (singleton ' ')
1432{-# INLINE unwords #-}
1434-- | /O(n)/ The 'isPrefixOf' function takes two 'Text's and returns
1435-- 'True' iff the first is a prefix of the second. Subject to fusion.
1436isPrefixOf :: Text -> Text -> Bool
1437isPrefixOf a@(Text _ _ alen) b@(Text _ _ blen) =
1438 alen <= blen && S.isPrefixOf (stream a) (stream b)
1439{-# INLINE [1] isPrefixOf #-}
1441{-# RULES
1442"TEXT isPrefixOf -> fused" [~1] forall s t.
1443 isPrefixOf s t = S.isPrefixOf (stream s) (stream t)
1444"TEXT isPrefixOf -> unfused" [1] forall s t.
1445 S.isPrefixOf (stream s) (stream t) = isPrefixOf s t
1446 #-}
1448-- | /O(n)/ The 'isSuffixOf' function takes two 'Text's and returns
1449-- 'True' iff the first is a suffix of the second.
1450isSuffixOf :: Text -> Text -> Bool
1451isSuffixOf a@(Text _aarr _aoff alen) b@(Text barr boff blen) =
1452 d >= 0 && a == b'
1453 where d = blen - alen
1454 b' | d == 0 = b
1455 | otherwise = Text barr (boff+d) alen
1456{-# INLINE isSuffixOf #-}
1458-- | /O(n+m)/ The 'isInfixOf' function takes two 'Text's and returns
1459-- 'True' iff the first is contained, wholly and intact, anywhere
1460-- within the second.
1462-- In (unlikely) bad cases, this function's time complexity degrades
1463-- towards /O(n*m)/.
1464isInfixOf :: Text -> Text -> Bool
1465isInfixOf needle haystack
1466 | null needle = True
1467 | isSingleton needle = S.elem (unsafeHead needle) . S.stream $ haystack
1468 | otherwise = not . L.null . indices needle $ haystack
1469{-# INLINE [1] isInfixOf #-}
1471{-# RULES
1472"TEXT isInfixOf/singleton -> S.elem/S.stream" [~1] forall n h.
1473 isInfixOf (singleton n) h = S.elem n (S.stream h)
1474 #-}
1476-------------------------------------------------------------------------------
1477-- * View patterns
1479-- | /O(n)/ Return the suffix of the second string if its prefix
1480-- matches the entire first string.
1482-- Examples:
1484-- > stripPrefix "foo" "foobar" == Just "bar"
1485-- > stripPrefix "" "baz" == Just "baz"
1486-- > stripPrefix "foo" "quux" == Nothing
1488-- This is particularly useful with the @ViewPatterns@ extension to
1489-- GHC, as follows:
1491-- > {-# LANGUAGE ViewPatterns #-}
1492-- > import Data.Text as T
1493-- >
1494-- > fnordLength :: Text -> Int
1495-- > fnordLength (stripPrefix "fnord" -> Just suf) = T.length suf
1496-- > fnordLength _ = -1
1497stripPrefix :: Text -> Text -> Maybe Text
1498stripPrefix p@(Text _arr _off plen) t@(Text arr off len)
1499 | p `isPrefixOf` t = Just $! textP arr (off+plen) (len-plen)
1500 | otherwise = Nothing
1502-- | /O(n)/ Find the longest non-empty common prefix of two strings
1503-- and return it, along with the suffixes of each string at which they
1504-- no longer match.
1506-- If the strings do not have a common prefix or either one is empty,
1507-- this function returns 'Nothing'.
1509-- Examples:
1511-- > commonPrefixes "foobar" "fooquux" == Just ("foo","bar","quux")
1512-- > commonPrefixes "veeble" "fetzer" == Nothing
1513-- > commonPrefixes "" "baz" == Nothing
1514commonPrefixes :: Text -> Text -> Maybe (Text,Text,Text)
1515commonPrefixes t0@(Text arr0 off0 len0) t1@(Text arr1 off1 len1) = go 0 0
1516 where
1517 go !i !j | i < len0 && j < len1 && a == b = go (i+d0) (j+d1)
1518 | i > 0 = Just (Text arr0 off0 i,
1519 textP arr0 (off0+i) (len0-i),
1520 textP arr1 (off1+j) (len1-j))
1521 | otherwise = Nothing
1522 where Iter a d0 = iter t0 i
1523 Iter b d1 = iter t1 j
1525-- | /O(n)/ Return the prefix of the second string if its suffix
1526-- matches the entire first string.
1528-- Examples:
1530-- > stripSuffix "bar" "foobar" == Just "foo"
1531-- > stripSuffix "" "baz" == Just "baz"
1532-- > stripSuffix "foo" "quux" == Nothing
1534-- This is particularly useful with the @ViewPatterns@ extension to
1535-- GHC, as follows:
1537-- > {-# LANGUAGE ViewPatterns #-}
1538-- > import Data.Text as T
1539-- >
1540-- > quuxLength :: Text -> Int
1541-- > quuxLength (stripSuffix "quux" -> Just pre) = T.length pre
1542-- > quuxLength _ = -1
1543stripSuffix :: Text -> Text -> Maybe Text
1544stripSuffix p@(Text _arr _off plen) t@(Text arr off len)
1545 | p `isSuffixOf` t = Just $! textP arr off (len-plen)
1546 | otherwise = Nothing
1548-- | Add a list of non-negative numbers. Errors out on overflow.
1549sumP :: String -> [Int] -> Int
1550sumP fun = go 0
1551 where go !a (x:xs)
1552 | ax >= 0 = go ax xs
1553 | otherwise = overflowError fun
1554 where ax = a + x
1555 go a _ = a
1557emptyError :: String -> a
1558emptyError fun = P.error $ "Data.Text." ++ fun ++ ": empty input"
1560overflowError :: String -> a
1561overflowError fun = P.error $ "Data.Text." ++ fun ++ ": size overflow"