1{-# LANGUAGE BangPatterns, CPP, MagicHash, Rank2Types, UnboxedTuples #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
3#if __GLASGOW_HASKELL__ >= 702
4{-# LANGUAGE Trustworthy #-}
9-- Copyright : (c) 2009, 2010, 2011, 2012 Bryan O'Sullivan,
10-- (c) 2009 Duncan Coutts,
11-- (c) 2008, 2009 Tom Harper
14-- Maintainer : bos@serpentine.com
15-- Stability : experimental
18-- A time and space-efficient implementation of Unicode text.
19-- Suitable for performance critical use, both in terms of large data
20-- quantities and high speed.
22-- /Note/: Read below the synopsis for important notes on the use of
25-- This module is intended to be imported @qualified@, to avoid name
26-- clashes with "Prelude" functions, e.g.
28-- > import qualified Data.Text as T
30-- To use an extended and very rich family of functions for working
31-- with Unicode text (including normalization, regular expressions,
32-- non-standard encodings, text breaking, and locales), see
33-- <http://hackage.haskell.org/package/text-icu the text-icu package >.
37 -- * Strict vs lazy types
49 -- * Creation and elimination
112 -- ** Accumulating maps
116 -- ** Generation and unfolding
123 -- ** Breaking strings
145 -- ** Breaking into many substrings
151 -- ** Breaking into lines and words
189 -- * Low level operations
193import Prelude (Char, Bool(..), Int, Maybe(..), String,
194 Eq(..), Ord(..), Ordering(..), (++),
196 (&&), (||), (+), (-), (.), ($), ($!), (>>), (*),
197 maxBound, not, return, otherwise, quot)
198#if defined(HAVE_DEEPSEQ)
199import Control.DeepSeq (NFData)
202import Control.Exception (assert)
204import Data.Char (isSpace)
205import Data.Data (Data(gfoldl, toConstr, gunfold, dataTypeOf), constrIndex,
206 Constr, mkConstr, DataType, mkDataType, Fixity(Prefix))
207import Control.Monad (foldM)
208import qualified Data.Text.Array as A
209import qualified Data.List as L
210import Data.Monoid (Monoid(..))
211import Data.String (IsString(..))
212import qualified Data.Text.Internal.Fusion as S
213import qualified Data.Text.Internal.Fusion.Common as S
214import Data.Text.Internal.Fusion (stream, reverseStream, unstream)
215import Data.Text.Internal.Private (span_)
216import Data.Text.Internal (Text(..), empty, firstf, safe, text)
217import qualified Prelude as P
218import Data.Text.Unsafe (Iter(..), iter, iter_, lengthWord16, reverseIter,
219 reverseIter_, unsafeHead, unsafeTail)
220import Data.Text.Internal.Unsafe.Char (unsafeChr)
221import qualified Data.Text.Internal.Functions as F
222import qualified Data.Text.Internal.Encoding.Utf16 as U16
223import Data.Text.Internal.Search (indices)
224#if defined(__HADDOCK__)
225import Data.ByteString (ByteString)
226import qualified Data.Text.Lazy as L
227import Data.Int (Int64)
229#if __GLASGOW_HASKELL__ >= 702
230import qualified GHC.CString as GHC
232import qualified GHC.Base as GHC
234import GHC.Prim (Addr#)
238-- This package provides both strict and lazy 'Text' types. The
239-- strict type is provided by the "Data.Text" module, while the lazy
240-- type is provided by the "Data.Text.Lazy" module. Internally, the
241-- lazy @Text@ type consists of a list of strict chunks.
243-- The strict 'Text' type requires that an entire string fit into
244-- memory at once. The lazy 'Data.Text.Lazy.Text' type is capable of
245-- streaming strings that are larger than memory using a small memory
246-- footprint. In many cases, the overhead of chunked streaming makes
247-- the lazy 'Data.Text.Lazy.Text' type slower than its strict
248-- counterpart, but this is not always the case. Sometimes, the time
249-- complexity of a function in one module may be different from the
250-- other, due to their differing internal structures.
252-- Each module provides an almost identical API, with the main
253-- difference being that the strict module uses 'Int' values for
254-- lengths and counts, while the lazy module uses 'Data.Int.Int64'
259-- A 'Text' value is a sequence of Unicode scalar values, as defined
261-- <http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#page=35 §3.9, definition D76 of the Unicode 5.2 standard >.
262-- As such, a 'Text' cannot contain values in the range U+D800 to
263-- U+DFFF inclusive. Haskell implementations admit all Unicode code
265-- (<http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#page=13 §3.4, definition D10 >)
266-- as 'Char' values, including code points from this invalid range.
267-- This means that there are some 'Char' values that are not valid
268-- Unicode scalar values, and the functions in this module must handle
271-- Within this module, many functions construct a 'Text' from one or
272-- more 'Char' values. Those functions will substitute 'Char' values
273-- that are not valid Unicode scalar values with the replacement
274-- character \"�\" (U+FFFD). Functions that perform this
275-- inspection and replacement are documented with the phrase
276-- \"Performs replacement on invalid scalar values\".
278-- (One reason for this policy of replacement is that internally, a
279-- 'Text' value is represented as packed UTF-16 data. Values in the
280-- range U+D800 through U+DFFF are used by UTF-16 to denote surrogate
281-- code points, and so cannot be represented. The functions replace
282-- invalid scalar values, instead of dropping them, as a security
283-- measure. For details, see
284-- <http://unicode.org/reports/tr36/#Deletion_of_Noncharacters Unicode Technical Report 36, §3.5 >.)
288-- Most of the functions in this module are subject to /fusion/,
289-- meaning that a pipeline of such functions will usually allocate at
290-- most one 'Text' value.
292-- As an example, consider the following pipeline:
294-- > import Data.Text as T
295-- > import Data.Text.Encoding as E
296-- > import Data.ByteString (ByteString)
298-- > countChars :: ByteString -> Int
299-- > countChars = T.length . T.toUpper . E.decodeUtf8
301-- From the type signatures involved, this looks like it should
302-- allocate one 'Data.ByteString.ByteString' value, and two 'Text'
303-- values. However, when a module is compiled with optimisation
304-- enabled under GHC, the two intermediate 'Text' values will be
305-- optimised away, and the function will be compiled down to a single
306-- loop over the source 'Data.ByteString.ByteString'.
308-- Functions that can be fused by the compiler are documented with the
309-- phrase \"Subject to fusion\".
311instance Eq Text where
312 Text arrA offA lenA == Text arrB offB lenB
313 | lenA == lenB = A.equal arrA offA arrB offB lenA
317instance Ord Text where
318 compare = compareText
320instance Show Text where
321 showsPrec p ps r = showsPrec p (unpack ps) r
323instance Read Text where
324 readsPrec p str = [(pack x,y) | (x,y) <- readsPrec p str]
326instance Monoid Text where
331instance IsString Text where
334#if defined(HAVE_DEEPSEQ)
338-- | This instance preserves data abstraction at the cost of inefficiency.
339-- We omit reflection services for the sake of data abstraction.
341-- This instance was created by copying the updated behavior of
342-- @"Data.Set".@'Data.Set.Set' and @"Data.Map".@'Data.Map.Map'. If you
343-- feel a mistake has been made, please feel free to submit
346-- The original discussion is archived here:
347-- <http://groups.google.com/group/haskell-cafe/browse_thread/thread/b5bbb1b28a7e525d/0639d46852575b93 could we get a Data instance for Data.Text.Text? >
349-- The followup discussion that changed the behavior of 'Data.Set.Set'
350-- and 'Data.Map.Map' is archived here:
351-- <http://markmail.org/message/trovdc6zkphyi3cr#query:+page:1+mid:a46der3iacwjcf6n+state:results Proposal: Allow gunfold for Data.Map, ... >
353instance Data Text where
354 gfoldl f z txt = z pack `f` (unpack txt)
355 toConstr _ = packConstr
356 gunfold k z c = case constrIndex c of
358 _ -> P.error "gunfold"
359 dataTypeOf _ = textDataType
362packConstr = mkConstr textDataType "pack" [] Prefix
364textDataType :: DataType
365textDataType = mkDataType "Data.Text.Text" [packConstr]
367-- | /O(n)/ Compare two 'Text' values lexicographically.
368compareText :: Text -> Text -> Ordering
369compareText ta@(Text _arrA _offA lenA) tb@(Text _arrB _offB lenB)
370 | lenA == 0 && lenB == 0 = EQ
374 | i >= lenA || j >= lenB = compare lenA lenB
377 | otherwise = go (i+di) (j+dj)
378 where Iter a di = iter ta i
379 Iter b dj = iter tb j
381-- -----------------------------------------------------------------------------
382-- * Conversion to/from 'Text'
384-- | /O(n)/ Convert a 'String' into a 'Text'. Subject to
385-- fusion. Performs replacement on invalid scalar values.
386pack :: String -> Text
387pack = unstream . S.map safe . S.streamList
388{-# INLINE [1] pack #-}
390-- | /O(n)/ Convert a 'Text' into a 'String'. Subject to fusion.
391unpack :: Text -> String
392unpack = S.unstreamList . stream
393{-# INLINE [1] unpack #-}
395-- | /O(n)/ Convert a literal string into a Text. Subject to fusion.
396unpackCString# :: Addr# -> Text
397unpackCString# addr# = unstream (S.streamCString# addr#)
398{-# NOINLINE unpackCString# #-}
400{-# RULES "TEXT literal" forall a.
401 unstream (S.map safe (S.streamList (GHC.unpackCString# a)))
402 = unpackCString# a #-}
404{-# RULES "TEXT literal UTF8" forall a.
405 unstream (S.map safe (S.streamList (GHC.unpackCStringUtf8# a)))
406 = unpackCString# a #-}
408-- | /O(1)/ Convert a character into a Text. Subject to fusion.
409-- Performs replacement on invalid scalar values.
410singleton :: Char -> Text
411singleton = unstream . S.singleton . safe
412{-# INLINE [1] singleton #-}
414-- -----------------------------------------------------------------------------
417-- | /O(n)/ Adds a character to the front of a 'Text'. This function
418-- is more costly than its 'List' counterpart because it requires
419-- copying a new array. Subject to fusion. Performs replacement on
420-- invalid scalar values.
421cons :: Char -> Text -> Text
422cons c t = unstream (S.cons (safe c) (stream t))
427-- | /O(n)/ Adds a character to the end of a 'Text'. This copies the
428-- entire array in the process, unless fused. Subject to fusion.
429-- Performs replacement on invalid scalar values.
430snoc :: Text -> Char -> Text
431snoc t c = unstream (S.snoc (stream t) (safe c))
434-- | /O(n)/ Appends one 'Text' to the other by copying both of them
435-- into a new 'Text'. Subject to fusion.
436append :: Text -> Text -> Text
437append a@(Text arr1 off1 len1) b@(Text arr2 off2 len2)
440 | len > 0 = Text (A.run x) 0 len
441 | otherwise = overflowError "append"
446 A.copyI arr 0 arr1 off1 len1
447 A.copyI arr len1 arr2 off2 len
449{-# NOINLINE append #-}
452"TEXT append -> fused" [~1] forall t1 t2.
453 append t1 t2 = unstream (S.append (stream t1) (stream t2))
454"TEXT append -> unfused" [1] forall t1 t2.
455 unstream (S.append (stream t1) (stream t2)) = append t1 t2
458-- | /O(1)/ Returns the first character of a 'Text', which must be
459-- non-empty. Subject to fusion.
461head t = S.head (stream t)
464-- | /O(1)/ Returns the first character and rest of a 'Text', or
465-- 'Nothing' if empty. Subject to fusion.
466uncons :: Text -> Maybe (Char, Text)
467uncons t@(Text arr off len)
469 | otherwise = Just (c, text arr (off+d) (len-d))
470 where Iter c d = iter t 0
471{-# INLINE [1] uncons #-}
473-- | Lifted from Control.Arrow and specialized.
474second :: (b -> c) -> (a,b) -> (a,c)
475second f (a, b) = (a, f b)
477-- | /O(1)/ Returns the last character of a 'Text', which must be
478-- non-empty. Subject to fusion.
480last (Text arr off len)
481 | len <= 0 = emptyError "last"
482 | n < 0xDC00 || n > 0xDFFF = unsafeChr n
483 | otherwise = U16.chr2 n0 n
484 where n = A.unsafeIndex arr (off+len-1)
485 n0 = A.unsafeIndex arr (off+len-2)
486{-# INLINE [1] last #-}
489"TEXT last -> fused" [~1] forall t.
490 last t = S.last (stream t)
491"TEXT last -> unfused" [1] forall t.
492 S.last (stream t) = last t
495-- | /O(1)/ Returns all characters after the head of a 'Text', which
496-- must be non-empty. Subject to fusion.
498tail t@(Text arr off len)
499 | len <= 0 = emptyError "tail"
500 | otherwise = text arr (off+d) (len-d)
502{-# INLINE [1] tail #-}
505"TEXT tail -> fused" [~1] forall t.
506 tail t = unstream (S.tail (stream t))
507"TEXT tail -> unfused" [1] forall t.
508 unstream (S.tail (stream t)) = tail t
511-- | /O(1)/ Returns all but the last character of a 'Text', which must
512-- be non-empty. Subject to fusion.
514init (Text arr off len) | len <= 0 = emptyError "init"
515 | n >= 0xDC00 && n <= 0xDFFF = text arr off (len-2)
516 | otherwise = text arr off (len-1)
518 n = A.unsafeIndex arr (off+len-1)
519{-# INLINE [1] init #-}
522"TEXT init -> fused" [~1] forall t.
523 init t = unstream (S.init (stream t))
524"TEXT init -> unfused" [1] forall t.
525 unstream (S.init (stream t)) = init t
528-- | /O(1)/ Tests whether a 'Text' is empty or not. Subject to
531null (Text _arr _off len) =
536{-# INLINE [1] null #-}
539"TEXT null -> fused" [~1] forall t.
540 null t = S.null (stream t)
541"TEXT null -> unfused" [1] forall t.
542 S.null (stream t) = null t
545-- | /O(1)/ Tests whether a 'Text' contains exactly one character.
547isSingleton :: Text -> Bool
548isSingleton = S.isSingleton . stream
549{-# INLINE isSingleton #-}
551-- | /O(n)/ Returns the number of characters in a 'Text'.
554length t = S.length (stream t)
557-- | /O(n)/ Compare the count of characters in a 'Text' to a number.
560-- This function gives the same answer as comparing against the result
561-- of 'length', but can short circuit if the count of characters is
562-- greater than the number, and hence be more efficient.
563compareLength :: Text -> Int -> Ordering
564compareLength t n = S.compareLengthI (stream t) n
565{-# INLINE [1] compareLength #-}
568"TEXT compareN/length -> compareLength" [~1] forall t n.
569 compare (length t) n = compareLength t n
573"TEXT ==N/length -> compareLength/==EQ" [~1] forall t n.
574 (==) (length t) n = compareLength t n == EQ
578"TEXT /=N/length -> compareLength//=EQ" [~1] forall t n.
579 (/=) (length t) n = compareLength t n /= EQ
583"TEXT <N/length -> compareLength/==LT" [~1] forall t n.
584 (<) (length t) n = compareLength t n == LT
588"TEXT <=N/length -> compareLength//=GT" [~1] forall t n.
589 (<=) (length t) n = compareLength t n /= GT
593"TEXT >N/length -> compareLength/==GT" [~1] forall t n.
594 (>) (length t) n = compareLength t n == GT
598"TEXT >=N/length -> compareLength//=LT" [~1] forall t n.
599 (>=) (length t) n = compareLength t n /= LT
602-- -----------------------------------------------------------------------------
604-- | /O(n)/ 'map' @f@ @t@ is the 'Text' obtained by applying @f@ to
605-- each element of @t@. Subject to fusion. Performs replacement on
606-- invalid scalar values.
607map :: (Char -> Char) -> Text -> Text
608map f t = unstream (S.map (safe . f) (stream t))
609{-# INLINE [1] map #-}
611-- | /O(n)/ The 'intercalate' function takes a 'Text' and a list of
612-- 'Text's and concatenates the list after interspersing the first
613-- argument between each element of the list.
614intercalate :: Text -> [Text] -> Text
615intercalate t = concat . (F.intersperse t)
616{-# INLINE intercalate #-}
618-- | /O(n)/ The 'intersperse' function takes a character and places it
619-- between the characters of a 'Text'. Subject to fusion. Performs
620-- replacement on invalid scalar values.
621intersperse :: Char -> Text -> Text
622intersperse c t = unstream (S.intersperse (safe c) (stream t))
623{-# INLINE intersperse #-}
625-- | /O(n)/ Reverse the characters of a string. Subject to fusion.
626reverse :: Text -> Text
627reverse t = S.reverse (stream t)
628{-# INLINE reverse #-}
630-- | /O(m+n)/ Replace every occurrence of one substring with another.
632-- In (unlikely) bad cases, this function's time complexity degrades
634replace :: Text -> Text -> Text -> Text
635replace needle@(Text _ _ neeLen)
636 (Text repArr repOff repLen)
637 haystack@(Text hayArr hayOff hayLen)
638 | neeLen == 0 = emptyError "replace"
639 | L.null ixs = haystack
640 | len > 0 = Text (A.run x) 0 len
641 | len < 0 = overflowError "replace"
644 ixs = indices needle haystack
645 len = hayLen - (neeLen - repLen) * L.length ixs
648 let loop (i:is) o d = do
651 A.copyI marr d hayArr (hayOff+o) d0
652 A.copyI marr d0 repArr repOff d1
653 loop is (i + neeLen) d1
654 loop [] o d = A.copyI marr d hayArr (hayOff+o) len
658-- ----------------------------------------------------------------------------
659-- ** Case conversions (folds)
663-- When case converting 'Text' values, do not use combinators like
664-- @map toUpper@ to case convert each character of a string
665-- individually, as this gives incorrect results according to the
666-- rules of some writing systems. The whole-string case conversion
667-- functions from this module, such as @toUpper@, obey the correct
668-- case conversion rules. As a result, these functions may map one
669-- input character to two or three output characters. For examples,
670-- see the documentation of each function.
672-- /Note/: In some languages, case conversion is a locale- and
673-- context-dependent operation. The case conversion functions in this
674-- module are /not/ locale sensitive. Programs that require locale
675-- sensitivity should use appropriate versions of the
676-- <http://hackage.haskell.org/package/text-icu-0.6.3.7/docs/Data-Text-ICU.html#g:4 case mapping functions from the text-icu package >.
678-- | /O(n)/ Convert a string to folded case. Subject to fusion.
680-- This function is mainly useful for performing caseless (also known
681-- as case insensitive) string comparisons.
683-- A string @x@ is a caseless match for a string @y@ if and only if:
685-- @toCaseFold x == toCaseFold y@
687-- The result string may be longer than the input string, and may
688-- differ from applying 'toLower' to the input string. For instance,
689-- the Armenian small ligature \"ﬓ\" (men now, U+FB13) is case
690-- folded to the sequence \"մ\" (men, U+0574) followed by
691-- \"ն\" (now, U+0576), while the Greek \"µ\" (micro sign,
692-- U+00B5) is case folded to \"μ\" (small letter mu, U+03BC)
694toCaseFold :: Text -> Text
695toCaseFold t = unstream (S.toCaseFold (stream t))
696{-# INLINE [0] toCaseFold #-}
698-- | /O(n)/ Convert a string to lower case, using simple case
699-- conversion. Subject to fusion.
701-- The result string may be longer than the input string. For
702-- instance, \"İ\" (Latin capital letter I with dot above,
703-- U+0130) maps to the sequence \"i\" (Latin small letter i, U+0069)
704-- followed by \" ̇\" (combining dot above, U+0307).
705toLower :: Text -> Text
706toLower t = unstream (S.toLower (stream t))
707{-# INLINE toLower #-}
709-- | /O(n)/ Convert a string to upper case, using simple case
710-- conversion. Subject to fusion.
712-- The result string may be longer than the input string. For
713-- instance, the German \"ß\" (eszett, U+00DF) maps to the
714-- two-letter sequence \"SS\".
715toUpper :: Text -> Text
716toUpper t = unstream (S.toUpper (stream t))
717{-# INLINE toUpper #-}
719-- | /O(n)/ Convert a string to title case, using simple case
720-- conversion. Subject to fusion.
722-- The first letter of the input is converted to title case, as is
723-- every subsequent letter that immediately follows a non-letter.
724-- Every letter that immediately follows another letter is converted
727-- The result string may be longer than the input string. For example,
728-- the Latin small ligature fl (U+FB02) is converted to the
729-- sequence Latin capital letter F (U+0046) followed by Latin small
732-- /Note/: this function does not take language or culture specific
733-- rules into account. For instance, in English, different style
734-- guides disagree on whether the book name \"The Hill of the Red
735-- Fox\" is correctly title cased—but this function will
736-- capitalize /every/ word.
737toTitle :: Text -> Text
738toTitle t = unstream (S.toTitle (stream t))
739{-# INLINE toTitle #-}
741-- | /O(n)/ Left-justify a string to the given length, using the
742-- specified fill character on the right. Subject to fusion.
743-- Performs replacement on invalid scalar values.
747-- > justifyLeft 7 'x' "foo" == "fooxxxx"
748-- > justifyLeft 3 'x' "foobar" == "foobar"
749justifyLeft :: Int -> Char -> Text -> Text
752 | otherwise = t `append` replicateChar (k-len) c
754{-# INLINE [1] justifyLeft #-}
757"TEXT justifyLeft -> fused" [~1] forall k c t.
758 justifyLeft k c t = unstream (S.justifyLeftI k c (stream t))
759"TEXT justifyLeft -> unfused" [1] forall k c t.
760 unstream (S.justifyLeftI k c (stream t)) = justifyLeft k c t
763-- | /O(n)/ Right-justify a string to the given length, using the
764-- specified fill character on the left. Performs replacement on
765-- invalid scalar values.
769-- > justifyRight 7 'x' "bar" == "xxxxbar"
770-- > justifyRight 3 'x' "foobar" == "foobar"
771justifyRight :: Int -> Char -> Text -> Text
774 | otherwise = replicateChar (k-len) c `append` t
776{-# INLINE justifyRight #-}
778-- | /O(n)/ Center a string to the given length, using the specified
779-- fill character on either side. Performs replacement on invalid
784-- > center 8 'x' "HS" = "xxxHSxxx"
785center :: Int -> Char -> Text -> Text
788 | otherwise = replicateChar l c `append` t `append` replicateChar r c
795-- | /O(n)/ The 'transpose' function transposes the rows and columns
796-- of its 'Text' argument. Note that this function uses 'pack',
797-- 'unpack', and the list version of transpose, and is thus not very
799transpose :: [Text] -> [Text]
800transpose ts = P.map pack (L.transpose (P.map unpack ts))
802-- -----------------------------------------------------------------------------
803-- * Reducing 'Text's (folds)
805-- | /O(n)/ 'foldl', applied to a binary operator, a starting value
806-- (typically the left-identity of the operator), and a 'Text',
807-- reduces the 'Text' using the binary operator, from left to right.
809foldl :: (a -> Char -> a) -> a -> Text -> a
810foldl f z t = S.foldl f z (stream t)
813-- | /O(n)/ A strict version of 'foldl'. Subject to fusion.
814foldl' :: (a -> Char -> a) -> a -> Text -> a
815foldl' f z t = S.foldl' f z (stream t)
818-- | /O(n)/ A variant of 'foldl' that has no starting value argument,
819-- and thus must be applied to a non-empty 'Text'. Subject to fusion.
820foldl1 :: (Char -> Char -> Char) -> Text -> Char
821foldl1 f t = S.foldl1 f (stream t)
824-- | /O(n)/ A strict version of 'foldl1'. Subject to fusion.
825foldl1' :: (Char -> Char -> Char) -> Text -> Char
826foldl1' f t = S.foldl1' f (stream t)
827{-# INLINE foldl1' #-}
829-- | /O(n)/ 'foldr', applied to a binary operator, a starting value
830-- (typically the right-identity of the operator), and a 'Text',
831-- reduces the 'Text' using the binary operator, from right to left.
833foldr :: (Char -> a -> a) -> a -> Text -> a
834foldr f z t = S.foldr f z (stream t)
837-- | /O(n)/ A variant of 'foldr' that has no starting value argument,
838-- and thus must be applied to a non-empty 'Text'. Subject to
840foldr1 :: (Char -> Char -> Char) -> Text -> Char
841foldr1 f t = S.foldr1 f (stream t)
844-- -----------------------------------------------------------------------------
847-- | /O(n)/ Concatenate a list of 'Text's.
848concat :: [Text] -> Text
849concat ts = case ts' of
852 _ -> Text (A.run go) 0 len
854 ts' = L.filter (not . null) ts
855 len = sumP "concat" $ L.map lengthWord16 ts'
858 let step i (Text a o l) =
859 let !j = i + l in A.copyI arr i a o j >> return j
860 foldM step 0 ts' >> return arr
862-- | /O(n)/ Map a function over a 'Text' that results in a 'Text', and
863-- concatenate the results.
864concatMap :: (Char -> Text) -> Text -> Text
865concatMap f = concat . foldr ((:) . f) []
866{-# INLINE concatMap #-}
868-- | /O(n)/ 'any' @p@ @t@ determines whether any character in the
869-- 'Text' @t@ satisifes the predicate @p@. Subject to fusion.
870any :: (Char -> Bool) -> Text -> Bool
871any p t = S.any p (stream t)
874-- | /O(n)/ 'all' @p@ @t@ determines whether all characters in the
875-- 'Text' @t@ satisify the predicate @p@. Subject to fusion.
876all :: (Char -> Bool) -> Text -> Bool
877all p t = S.all p (stream t)
880-- | /O(n)/ 'maximum' returns the maximum value from a 'Text', which
881-- must be non-empty. Subject to fusion.
882maximum :: Text -> Char
883maximum t = S.maximum (stream t)
884{-# INLINE maximum #-}
886-- | /O(n)/ 'minimum' returns the minimum value from a 'Text', which
887-- must be non-empty. Subject to fusion.
888minimum :: Text -> Char
889minimum t = S.minimum (stream t)
890{-# INLINE minimum #-}
892-- -----------------------------------------------------------------------------
895-- | /O(n)/ 'scanl' is similar to 'foldl', but returns a list of
896-- successive reduced values from the left. Subject to fusion.
897-- Performs replacement on invalid scalar values.
899-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
903-- > last (scanl f z xs) == foldl f z xs.
904scanl :: (Char -> Char -> Char) -> Char -> Text -> Text
905scanl f z t = unstream (S.scanl g z (stream t))
906 where g a b = safe (f a b)
909-- | /O(n)/ 'scanl1' is a variant of 'scanl' that has no starting
910-- value argument. Subject to fusion. Performs replacement on
911-- invalid scalar values.
913-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
914scanl1 :: (Char -> Char -> Char) -> Text -> Text
915scanl1 f t | null t = empty
916 | otherwise = scanl f (unsafeHead t) (unsafeTail t)
919-- | /O(n)/ 'scanr' is the right-to-left dual of 'scanl'. Performs
920-- replacement on invalid scalar values.
922-- > scanr f v == reverse . scanl (flip f) v . reverse
923scanr :: (Char -> Char -> Char) -> Char -> Text -> Text
924scanr f z = S.reverse . S.reverseScanr g z . reverseStream
925 where g a b = safe (f a b)
928-- | /O(n)/ 'scanr1' is a variant of 'scanr' that has no starting
929-- value argument. Subject to fusion. Performs replacement on
930-- invalid scalar values.
931scanr1 :: (Char -> Char -> Char) -> Text -> Text
932scanr1 f t | null t = empty
933 | otherwise = scanr f (last t) (init t)
936-- | /O(n)/ Like a combination of 'map' and 'foldl''. Applies a
937-- function to each element of a 'Text', passing an accumulating
938-- parameter from left to right, and returns a final 'Text'. Performs
939-- replacement on invalid scalar values.
940mapAccumL :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
941mapAccumL f z0 = S.mapAccumL g z0 . stream
942 where g a b = second safe (f a b)
943{-# INLINE mapAccumL #-}
945-- | The 'mapAccumR' function behaves like a combination of 'map' and
946-- a strict 'foldr'; it applies a function to each element of a
947-- 'Text', passing an accumulating parameter from right to left, and
948-- returning a final value of this accumulator together with the new
950-- Performs replacement on invalid scalar values.
951mapAccumR :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
952mapAccumR f z0 = second reverse . S.mapAccumL g z0 . reverseStream
953 where g a b = second safe (f a b)
954{-# INLINE mapAccumR #-}
956-- -----------------------------------------------------------------------------
957-- ** Generating and unfolding 'Text's
959-- | /O(n*m)/ 'replicate' @n@ @t@ is a 'Text' consisting of the input
960-- @t@ repeated @n@ times.
961replicate :: Int -> Text -> Text
962replicate n t@(Text a o l)
963 | n <= 0 || l <= 0 = empty
965 | isSingleton t = replicateChar n (unsafeHead t)
966 | n <= maxBound `quot` l = Text (A.run x) 0 len
967 | otherwise = overflowError "replicate"
972 let loop !d !i | i >= n = return arr
973 | otherwise = let m = d + l
974 in A.copyI arr d a o m >> loop m (i+1)
976{-# INLINE [1] replicate #-}
979"TEXT replicate/singleton -> replicateChar" [~1] forall n c.
980 replicate n (singleton c) = replicateChar n c
983-- | /O(n)/ 'replicateChar' @n@ @c@ is a 'Text' of length @n@ with @c@ the
984-- value of every element. Subject to fusion.
985replicateChar :: Int -> Char -> Text
986replicateChar n c = unstream (S.replicateCharI n (safe c))
987{-# INLINE replicateChar #-}
989-- | /O(n)/, where @n@ is the length of the result. The 'unfoldr'
990-- function is analogous to the List 'L.unfoldr'. 'unfoldr' builds a
991-- 'Text' from a seed value. The function takes the element and
992-- returns 'Nothing' if it is done producing the 'Text', otherwise
993-- 'Just' @(a,b)@. In this case, @a@ is the next 'Char' in the
994-- string, and @b@ is the seed value for further production. Subject
995-- to fusion. Performs replacement on invalid scalar values.
996unfoldr :: (a -> Maybe (Char,a)) -> a -> Text
997unfoldr f s = unstream (S.unfoldr (firstf safe . f) s)
998{-# INLINE unfoldr #-}
1000-- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a 'Text' from a seed
1001-- value. However, the length of the result should be limited by the
1002-- first argument to 'unfoldrN'. This function is more efficient than
1003-- 'unfoldr' when the maximum length of the result is known and
1004-- correct, otherwise its performance is similar to 'unfoldr'. Subject
1005-- to fusion. Performs replacement on invalid scalar values.
1006unfoldrN :: Int -> (a -> Maybe (Char,a)) -> a -> Text
1007unfoldrN n f s = unstream (S.unfoldrN n (firstf safe . f) s)
1008{-# INLINE unfoldrN #-}
1010-- -----------------------------------------------------------------------------
1013-- | /O(n)/ 'take' @n@, applied to a 'Text', returns the prefix of the
1014-- 'Text' of length @n@, or the 'Text' itself if @n@ is greater than
1015-- the length of the Text. Subject to fusion.
1016take :: Int -> Text -> Text
1017take n t@(Text arr off len)
1020 | otherwise = text arr off (iterN n t)
1021{-# INLINE [1] take #-}
1023iterN :: Int -> Text -> Int
1024iterN n t@(Text _arr _off len) = loop 0 0
1026 | i >= len || cnt >= n = i
1027 | otherwise = loop (i+d) (cnt+1)
1031"TEXT take -> fused" [~1] forall n t.
1032 take n t = unstream (S.take n (stream t))
1033"TEXT take -> unfused" [1] forall n t.
1034 unstream (S.take n (stream t)) = take n t
1037-- | /O(n)/ 'takeEnd' @n@ @t@ returns the suffix remaining after
1038-- taking @n@ characters from the end of @t@.
1042-- > takeEnd 3 "foobar" == "bar"
1043takeEnd :: Int -> Text -> Text
1044takeEnd n t@(Text arr off len)
1047 | otherwise = text arr (off+i) (len-i)
1048 where i = iterNEnd n t
1050iterNEnd :: Int -> Text -> Int
1051iterNEnd n t@(Text _arr _off len) = loop (len-1) n
1055 | otherwise = loop (i+d) (m-1)
1056 where d = reverseIter_ t i
1058-- | /O(n)/ 'drop' @n@, applied to a 'Text', returns the suffix of the
1059-- 'Text' after the first @n@ characters, or the empty 'Text' if @n@
1060-- is greater than the length of the 'Text'. Subject to fusion.
1061drop :: Int -> Text -> Text
1062drop n t@(Text arr off len)
1065 | otherwise = text arr (off+i) (len-i)
1067{-# INLINE [1] drop #-}
1070"TEXT drop -> fused" [~1] forall n t.
1071 drop n t = unstream (S.drop n (stream t))
1072"TEXT drop -> unfused" [1] forall n t.
1073 unstream (S.drop n (stream t)) = drop n t
1076-- | /O(n)/ 'dropEnd' @n@ @t@ returns the prefix remaining after
1077-- dropping @n@ characters from the end of @t@.
1081-- > dropEnd 3 "foobar" == "foo"
1082dropEnd :: Int -> Text -> Text
1083dropEnd n t@(Text arr off len)
1086 | otherwise = text arr off (iterNEnd n t)
1088-- | /O(n)/ 'takeWhile', applied to a predicate @p@ and a 'Text',
1089-- returns the longest prefix (possibly empty) of elements that
1090-- satisfy @p@. Subject to fusion.
1091takeWhile :: (Char -> Bool) -> Text -> Text
1092takeWhile p t@(Text arr off len) = loop 0
1093 where loop !i | i >= len = t
1095 | otherwise = text arr off i
1096 where Iter c d = iter t i
1097{-# INLINE [1] takeWhile #-}
1100"TEXT takeWhile -> fused" [~1] forall p t.
1101 takeWhile p t = unstream (S.takeWhile p (stream t))
1102"TEXT takeWhile -> unfused" [1] forall p t.
1103 unstream (S.takeWhile p (stream t)) = takeWhile p t
1106-- | /O(n)/ 'dropWhile' @p@ @t@ returns the suffix remaining after
1107-- 'takeWhile' @p@ @t@. Subject to fusion.
1108dropWhile :: (Char -> Bool) -> Text -> Text
1109dropWhile p t@(Text arr off len) = loop 0 0
1110 where loop !i !l | l >= len = empty
1111 | p c = loop (i+d) (l+d)
1112 | otherwise = Text arr (off+i) (len-l)
1113 where Iter c d = iter t i
1114{-# INLINE [1] dropWhile #-}
1117"TEXT dropWhile -> fused" [~1] forall p t.
1118 dropWhile p t = unstream (S.dropWhile p (stream t))
1119"TEXT dropWhile -> unfused" [1] forall p t.
1120 unstream (S.dropWhile p (stream t)) = dropWhile p t
1123-- | /O(n)/ 'dropWhileEnd' @p@ @t@ returns the prefix remaining after
1124-- dropping characters that fail the predicate @p@ from the end of
1125-- @t@. Subject to fusion.
1128-- > dropWhileEnd (=='.') "foo..." == "foo"
1129dropWhileEnd :: (Char -> Bool) -> Text -> Text
1130dropWhileEnd p t@(Text arr off len) = loop (len-1) len
1131 where loop !i !l | l <= 0 = empty
1132 | p c = loop (i+d) (l+d)
1133 | otherwise = Text arr off l
1134 where (c,d) = reverseIter t i
1135{-# INLINE [1] dropWhileEnd #-}
1138"TEXT dropWhileEnd -> fused" [~1] forall p t.
1139 dropWhileEnd p t = S.reverse (S.dropWhile p (S.reverseStream t))
1140"TEXT dropWhileEnd -> unfused" [1] forall p t.
1141 S.reverse (S.dropWhile p (S.reverseStream t)) = dropWhileEnd p t
1144-- | /O(n)/ 'dropAround' @p@ @t@ returns the substring remaining after
1145-- dropping characters that fail the predicate @p@ from both the
1146-- beginning and end of @t@. Subject to fusion.
1147dropAround :: (Char -> Bool) -> Text -> Text
1148dropAround p = dropWhile p . dropWhileEnd p
1149{-# INLINE [1] dropAround #-}
1151-- | /O(n)/ Remove leading white space from a string. Equivalent to:
1153-- > dropWhile isSpace
1154stripStart :: Text -> Text
1155stripStart = dropWhile isSpace
1156{-# INLINE [1] stripStart #-}
1158-- | /O(n)/ Remove trailing white space from a string. Equivalent to:
1160-- > dropWhileEnd isSpace
1161stripEnd :: Text -> Text
1162stripEnd = dropWhileEnd isSpace
1163{-# INLINE [1] stripEnd #-}
1165-- | /O(n)/ Remove leading and trailing white space from a string.
1168-- > dropAround isSpace
1169strip :: Text -> Text
1170strip = dropAround isSpace
1171{-# INLINE [1] strip #-}
1173-- | /O(n)/ 'splitAt' @n t@ returns a pair whose first element is a
1174-- prefix of @t@ of length @n@, and whose second is the remainder of
1175-- the string. It is equivalent to @('take' n t, 'drop' n t)@.
1176splitAt :: Int -> Text -> (Text, Text)
1177splitAt n t@(Text arr off len)
1178 | n <= 0 = (empty, t)
1179 | n >= len = (t, empty)
1180 | otherwise = let k = iterN n t
1181 in (text arr off k, text arr (off+k) (len-k))
1183-- | /O(n)/ 'span', applied to a predicate @p@ and text @t@, returns
1184-- a pair whose first element is the longest prefix (possibly empty)
1185-- of @t@ of elements that satisfy @p@, and whose second is the
1186-- remainder of the list.
1187span :: (Char -> Bool) -> Text -> (Text, Text)
1188span p t = case span_ p t of
1189 (# hd,tl #) -> (hd,tl)
1192-- | /O(n)/ 'break' is like 'span', but the prefix returned is
1193-- over elements that fail the predicate @p@.
1194break :: (Char -> Bool) -> Text -> (Text, Text)
1195break p = span (not . p)
1198-- | /O(n)/ Group characters in a string according to a predicate.
1199groupBy :: (Char -> Char -> Bool) -> Text -> [Text]
1202 loop t@(Text arr off len)
1204 | otherwise = text arr off n : loop (text arr (off+n) (len-n))
1205 where Iter c d = iter t 0
1206 n = d + findAIndexOrEnd (not . p c) (Text arr (off+d) (len-d))
1208-- | Returns the /array/ index (in units of 'Word16') at which a
1209-- character may be found. This is /not/ the same as the logical
1210-- index returned by e.g. 'findIndex'.
1211findAIndexOrEnd :: (Char -> Bool) -> Text -> Int
1212findAIndexOrEnd q t@(Text _arr _off len) = go 0
1213 where go !i | i >= len || q c = i
1214 | otherwise = go (i+d)
1215 where Iter c d = iter t i
1217-- | /O(n)/ Group characters in a string by equality.
1218group :: Text -> [Text]
1221-- | /O(n)/ Return all initial segments of the given 'Text', shortest
1223inits :: Text -> [Text]
1224inits t@(Text arr off len) = loop 0
1225 where loop i | i >= len = [t]
1226 | otherwise = Text arr off i : loop (i + iter_ t i)
1228-- | /O(n)/ Return all final segments of the given 'Text', longest
1230tails :: Text -> [Text]
1231tails t | null t = [empty]
1232 | otherwise = t : tails (unsafeTail t)
1236-- Splitting functions in this library do not perform character-wise
1237-- copies to create substrings; they just construct new 'Text's that
1238-- are slices of the original.
1240-- | /O(m+n)/ Break a 'Text' into pieces separated by the first
1241-- 'Text' argument, consuming the delimiter. An empty delimiter is
1242-- invalid, and will cause an error to be raised.
1246-- > splitOn "\r\n" "a\r\nb\r\nd\r\ne" == ["a","b","d","e"]
1247-- > splitOn "aaa" "aaaXaaaXaaaXaaa" == ["","X","X","X",""]
1248-- > splitOn "x" "x" == ["",""]
1252-- > intercalate s . splitOn s == id
1253-- > splitOn (singleton c) == split (==c)
1255-- In (unlikely) bad cases, this function's time complexity degrades
1257splitOn :: Text -> Text -> [Text]
1258splitOn pat@(Text _ _ l) src@(Text arr off len)
1259 | l <= 0 = emptyError "splitOn"
1260 | isSingleton pat = split (== unsafeHead pat) src
1261 | otherwise = go 0 (indices pat src)
1263 go !s (x:xs) = text arr (s+off) (x-s) : go (x+l) xs
1264 go s _ = [text arr (s+off) (len-s)]
1265{-# INLINE [1] splitOn #-}
1268"TEXT splitOn/singleton -> split/==" [~1] forall c t.
1269 splitOn (singleton c) t = split (==c) t
1272-- | /O(n)/ Splits a 'Text' into components delimited by separators,
1273-- where the predicate returns True for a separator element. The
1274-- resulting components do not contain the separators. Two adjacent
1275-- separators result in an empty component in the output. eg.
1277-- > split (=='a') "aabbaca" == ["","","bb","c",""]
1278-- > split (=='a') "" == [""]
1279split :: (Char -> Bool) -> Text -> [Text]
1280split _ t@(Text _off _arr 0) = [t]
1282 where loop s | null s' = [l]
1283 | otherwise = l : loop (unsafeTail s')
1284 where (# l, s' #) = span_ (not . p) s
1287-- | /O(n)/ Splits a 'Text' into components of length @k@. The last
1288-- element may be shorter than the other chunks, depending on the
1289-- length of the input. Examples:
1291-- > chunksOf 3 "foobarbaz" == ["foo","bar","baz"]
1292-- > chunksOf 4 "haskell.org" == ["hask","ell.","org"]
1293chunksOf :: Int -> Text -> [Text]
1296 go t = case splitAt k t of
1297 (a,b) | null a -> []
1298 | otherwise -> a : go b
1299{-# INLINE chunksOf #-}
1301-- ----------------------------------------------------------------------------
1304-------------------------------------------------------------------------------
1305-- ** Searching with a predicate
1307-- | /O(n)/ The 'find' function takes a predicate and a 'Text', and
1308-- returns the first element matching the predicate, or 'Nothing' if
1309-- there is no such element.
1310find :: (Char -> Bool) -> Text -> Maybe Char
1311find p t = S.findBy p (stream t)
1314-- | /O(n)/ The 'partition' function takes a predicate and a 'Text',
1315-- and returns the pair of 'Text's with elements which do and do not
1316-- satisfy the predicate, respectively; i.e.
1318-- > partition p t == (filter p t, filter (not . p) t)
1319partition :: (Char -> Bool) -> Text -> (Text, Text)
1320partition p t = (filter p t, filter (not . p) t)
1321{-# INLINE partition #-}
1323-- | /O(n)/ 'filter', applied to a predicate and a 'Text',
1324-- returns a 'Text' containing those characters that satisfy the
1326filter :: (Char -> Bool) -> Text -> Text
1327filter p t = unstream (S.filter p (stream t))
1328{-# INLINE filter #-}
1330-- | /O(n+m)/ Find the first instance of @needle@ (which must be
1331-- non-'null') in @haystack@. The first element of the returned tuple
1332-- is the prefix of @haystack@ before @needle@ is matched. The second
1333-- is the remainder of @haystack@, starting with the match.
1337-- > breakOn "::" "a::b::c" ==> ("a", "::b::c")
1338-- > breakOn "/" "foobar" ==> ("foobar", "")
1342-- > append prefix match == haystack
1343-- > where (prefix, match) = breakOn needle haystack
1345-- If you need to break a string by a substring repeatedly (e.g. you
1346-- want to break on every instance of a substring), use 'breakOnAll'
1347-- instead, as it has lower startup overhead.
1349-- In (unlikely) bad cases, this function's time complexity degrades
1351breakOn :: Text -> Text -> (Text, Text)
1352breakOn pat src@(Text arr off len)
1353 | null pat = emptyError "breakOn"
1354 | otherwise = case indices pat src of
1356 (x:_) -> (text arr off x, text arr (off+x) (len-x))
1357{-# INLINE breakOn #-}
1359-- | /O(n+m)/ Similar to 'breakOn', but searches from the end of the
1362-- The first element of the returned tuple is the prefix of @haystack@
1363-- up to and including the last match of @needle@. The second is the
1364-- remainder of @haystack@, following the match.
1366-- > breakOnEnd "::" "a::b::c" ==> ("a::b::", "c")
1367breakOnEnd :: Text -> Text -> (Text, Text)
1368breakOnEnd pat src = (reverse b, reverse a)
1369 where (a,b) = breakOn (reverse pat) (reverse src)
1370{-# INLINE breakOnEnd #-}
1372-- | /O(n+m)/ Find all non-overlapping instances of @needle@ in
1373-- @haystack@. Each element of the returned list consists of a pair:
1375-- * The entire string prior to the /k/th match (i.e. the prefix)
1377-- * The /k/th match, followed by the remainder of the string
1381-- > breakOnAll "::" ""
1383-- > breakOnAll "/" "a/b/c/"
1384-- > ==> [("a", "/b/c/"), ("a/b", "/c/"), ("a/b/c", "/")]
1386-- In (unlikely) bad cases, this function's time complexity degrades
1389-- The @needle@ parameter may not be empty.
1390breakOnAll :: Text -- ^ @needle@ to search for
1391 -> Text -- ^ @haystack@ in which to search
1393breakOnAll pat src@(Text arr off slen)
1394 | null pat = emptyError "breakOnAll"
1395 | otherwise = L.map step (indices pat src)
1397 step x = (chunk 0 x, chunk x (slen-x))
1398 chunk !n !l = text arr (n+off) l
1399{-# INLINE breakOnAll #-}
1401-------------------------------------------------------------------------------
1402-- ** Indexing 'Text's
1406-- If you think of a 'Text' value as an array of 'Char' values (which
1407-- it is not), you run the risk of writing inefficient code.
1409-- An idiom that is common in some languages is to find the numeric
1410-- offset of a character or substring, then use that number to split
1411-- or trim the searched string. With a 'Text' value, this approach
1412-- would require two /O(n)/ operations: one to perform the search, and
1413-- one to operate from wherever the search ended.
1415-- For example, suppose you have a string that you want to split on
1416-- the substring @\"::\"@, such as @\"foo::bar::quux\"@. Instead of
1417-- searching for the index of @\"::\"@ and taking the substrings
1418-- before and after that index, you would instead use @breakOnAll \"::\"@.
1420-- | /O(n)/ 'Text' index (subscript) operator, starting from 0.
1421index :: Text -> Int -> Char
1422index t n = S.index (stream t) n
1425-- | /O(n)/ The 'findIndex' function takes a predicate and a 'Text'
1426-- and returns the index of the first element in the 'Text' satisfying
1427-- the predicate. Subject to fusion.
1428findIndex :: (Char -> Bool) -> Text -> Maybe Int
1429findIndex p t = S.findIndex p (stream t)
1430{-# INLINE findIndex #-}
1432-- | /O(n+m)/ The 'count' function returns the number of times the
1433-- query string appears in the given 'Text'. An empty query string is
1434-- invalid, and will cause an error to be raised.
1436-- In (unlikely) bad cases, this function's time complexity degrades
1438count :: Text -> Text -> Int
1440 | null pat = emptyError "count"
1441 | isSingleton pat = countChar (unsafeHead pat) src
1442 | otherwise = L.length (indices pat src)
1443{-# INLINE [1] count #-}
1446"TEXT count/singleton -> countChar" [~1] forall c t.
1447 count (singleton c) t = countChar c t
1450-- | /O(n)/ The 'countChar' function returns the number of times the
1451-- query element appears in the given 'Text'. Subject to fusion.
1452countChar :: Char -> Text -> Int
1453countChar c t = S.countChar c (stream t)
1454{-# INLINE countChar #-}
1456-------------------------------------------------------------------------------
1459-- | /O(n)/ 'zip' takes two 'Text's and returns a list of
1460-- corresponding pairs of bytes. If one input 'Text' is short,
1461-- excess elements of the longer 'Text' are discarded. This is
1462-- equivalent to a pair of 'unpack' operations.
1463zip :: Text -> Text -> [(Char,Char)]
1464zip a b = S.unstreamList $ S.zipWith (,) (stream a) (stream b)
1465{-# INLINE [0] zip #-}
1467-- | /O(n)/ 'zipWith' generalises 'zip' by zipping with the function
1468-- given as the first argument, instead of a tupling function.
1469-- Performs replacement on invalid scalar values.
1470zipWith :: (Char -> Char -> Char) -> Text -> Text -> Text
1471zipWith f t1 t2 = unstream (S.zipWith g (stream t1) (stream t2))
1472 where g a b = safe (f a b)
1473{-# INLINE [0] zipWith #-}
1475-- | /O(n)/ Breaks a 'Text' up into a list of words, delimited by 'Char's
1476-- representing white space.
1477words :: Text -> [Text]
1478words t@(Text arr off len) = loop 0 0
1481 | n >= len = if start == n
1483 else [Text arr (start+off) (n-start)]
1486 then loop (start+1) (start+1)
1487 else Text arr (start+off) (n-start) : loop (n+d) (n+d)
1488 | otherwise = loop start (n+d)
1489 where Iter c d = iter t n
1492-- | /O(n)/ Breaks a 'Text' up into a list of 'Text's at
1493-- newline 'Char's. The resulting strings do not contain newlines.
1494lines :: Text -> [Text]
1495lines ps | null ps = []
1496 | otherwise = h : if null t
1498 else lines (unsafeTail t)
1499 where (# h,t #) = span_ (/= '\n') ps
1503-- | /O(n)/ Portably breaks a 'Text' up into a list of 'Text's at line
1506-- A line boundary is considered to be either a line feed, a carriage
1507-- return immediately followed by a line feed, or a carriage return.
1508-- This accounts for both Unix and Windows line ending conventions,
1509-- and for the old convention used on Mac OS 9 and earlier.
1510lines' :: Text -> [Text]
1511lines' ps | null ps = []
1512 | otherwise = h : case uncons t of
1515 | c == '\n' -> lines t'
1516 | c == '\r' -> case uncons t' of
1517 Just ('\n',t'') -> lines t''
1519 where (h,t) = span notEOL ps
1520 notEOL c = c /= '\n' && c /= '\r'
1521{-# INLINE lines' #-}
1524-- | /O(n)/ Joins lines, after appending a terminating newline to
1526unlines :: [Text] -> Text
1527unlines = concat . L.map (`snoc` '\n')
1528{-# INLINE unlines #-}
1530-- | /O(n)/ Joins words using single space characters.
1531unwords :: [Text] -> Text
1532unwords = intercalate (singleton ' ')
1533{-# INLINE unwords #-}
1535-- | /O(n)/ The 'isPrefixOf' function takes two 'Text's and returns
1536-- 'True' iff the first is a prefix of the second. Subject to fusion.
1537isPrefixOf :: Text -> Text -> Bool
1538isPrefixOf a@(Text _ _ alen) b@(Text _ _ blen) =
1539 alen <= blen && S.isPrefixOf (stream a) (stream b)
1540{-# INLINE [1] isPrefixOf #-}
1543"TEXT isPrefixOf -> fused" [~1] forall s t.
1544 isPrefixOf s t = S.isPrefixOf (stream s) (stream t)
1547-- | /O(n)/ The 'isSuffixOf' function takes two 'Text's and returns
1548-- 'True' iff the first is a suffix of the second.
1549isSuffixOf :: Text -> Text -> Bool
1550isSuffixOf a@(Text _aarr _aoff alen) b@(Text barr boff blen) =
1552 where d = blen - alen
1554 | otherwise = Text barr (boff+d) alen
1555{-# INLINE isSuffixOf #-}
1557-- | /O(n+m)/ The 'isInfixOf' function takes two 'Text's and returns
1558-- 'True' iff the first is contained, wholly and intact, anywhere
1559-- within the second.
1561-- In (unlikely) bad cases, this function's time complexity degrades
1563isInfixOf :: Text -> Text -> Bool
1564isInfixOf needle haystack
1565 | null needle = True
1566 | isSingleton needle = S.elem (unsafeHead needle) . S.stream $ haystack
1567 | otherwise = not . L.null . indices needle $ haystack
1568{-# INLINE [1] isInfixOf #-}
1571"TEXT isInfixOf/singleton -> S.elem/S.stream" [~1] forall n h.
1572 isInfixOf (singleton n) h = S.elem n (S.stream h)
1575-------------------------------------------------------------------------------
1578-- | /O(n)/ Return the suffix of the second string if its prefix
1579-- matches the entire first string.
1583-- > stripPrefix "foo" "foobar" == Just "bar"
1584-- > stripPrefix "" "baz" == Just "baz"
1585-- > stripPrefix "foo" "quux" == Nothing
1587-- This is particularly useful with the @ViewPatterns@ extension to
1590-- > {-# LANGUAGE ViewPatterns #-}
1591-- > import Data.Text as T
1593-- > fnordLength :: Text -> Int
1594-- > fnordLength (stripPrefix "fnord" -> Just suf) = T.length suf
1595-- > fnordLength _ = -1
1596stripPrefix :: Text -> Text -> Maybe Text
1597stripPrefix p@(Text _arr _off plen) t@(Text arr off len)
1598 | p `isPrefixOf` t = Just $! text arr (off+plen) (len-plen)
1599 | otherwise = Nothing
1601-- | /O(n)/ Find the longest non-empty common prefix of two strings
1602-- and return it, along with the suffixes of each string at which they
1605-- If the strings do not have a common prefix or either one is empty,
1606-- this function returns 'Nothing'.
1610-- > commonPrefixes "foobar" "fooquux" == Just ("foo","bar","quux")
1611-- > commonPrefixes "veeble" "fetzer" == Nothing
1612-- > commonPrefixes "" "baz" == Nothing
1613commonPrefixes :: Text -> Text -> Maybe (Text,Text,Text)
1614commonPrefixes t0@(Text arr0 off0 len0) t1@(Text arr1 off1 len1) = go 0 0
1616 go !i !j | i < len0 && j < len1 && a == b = go (i+d0) (j+d1)
1617 | i > 0 = Just (Text arr0 off0 i,
1618 text arr0 (off0+i) (len0-i),
1619 text arr1 (off1+j) (len1-j))
1620 | otherwise = Nothing
1621 where Iter a d0 = iter t0 i
1622 Iter b d1 = iter t1 j
1624-- | /O(n)/ Return the prefix of the second string if its suffix
1625-- matches the entire first string.
1629-- > stripSuffix "bar" "foobar" == Just "foo"
1630-- > stripSuffix "" "baz" == Just "baz"
1631-- > stripSuffix "foo" "quux" == Nothing
1633-- This is particularly useful with the @ViewPatterns@ extension to
1636-- > {-# LANGUAGE ViewPatterns #-}
1637-- > import Data.Text as T
1639-- > quuxLength :: Text -> Int
1640-- > quuxLength (stripSuffix "quux" -> Just pre) = T.length pre
1641-- > quuxLength _ = -1
1642stripSuffix :: Text -> Text -> Maybe Text
1643stripSuffix p@(Text _arr _off plen) t@(Text arr off len)
1644 | p `isSuffixOf` t = Just $! text arr off (len-plen)
1645 | otherwise = Nothing
1647-- | Add a list of non-negative numbers. Errors out on overflow.
1648sumP :: String -> [Int] -> Int
1651 | ax >= 0 = go ax xs
1652 | otherwise = overflowError fun
1656emptyError :: String -> a
1657emptyError fun = P.error $ "Data.Text." ++ fun ++ ": empty input"
1659overflowError :: String -> a
1660overflowError fun = P.error $ "Data.Text." ++ fun ++ ": size overflow"
1662-- | /O(n)/ Make a distinct copy of the given string, sharing no
1663-- storage with the original string.
1665-- As an example, suppose you read a large string, of which you need
1666-- only a small portion. If you do not use 'copy', the entire original
1667-- array will be kept alive in memory by the smaller string. Making a
1668-- copy \"breaks the link\" to the original array, allowing it to be
1669-- garbage collected if there are no other live references to it.
1671copy (Text arr off len) = Text (A.run go) 0 len
1675 A.copyI marr 0 arr off len
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list