@@ -1,29 +1,48 @@
1−{-# LANGUAGE BangPatterns #-}
1+{-# LANGUAGE BangPatterns, CPP, MagicHash, Rank2Types, UnboxedTuples #-}
22{-# OPTIONS_GHC -fno-warn-orphans #-}
3+#if __GLASGOW_HASKELL__ >= 702
4+{-# LANGUAGE Trustworthy #-}
5+#endif
6+#if __GLASGOW_HASKELL__ >= 708
7+{-# LANGUAGE TypeFamilies #-}
8+#endif
39
410-- |
511-- Module : Data.Text
6−-- Copyright : (c) Tom Harper 2008-2009,
7−-- (c) Bryan O'Sullivan 2009,
8−-- (c) Duncan Coutts 2009
12+-- Copyright : (c) 2009, 2010, 2011, 2012 Bryan O'Sullivan,
13+-- (c) 2009 Duncan Coutts,
14+-- (c) 2008, 2009 Tom Harper
915--
1016-- License : BSD-style
11−-- Maintainer : rtharper@aftereternity.co.uk, bos@serpentine.com,
12−-- duncan@haskell.org
17+-- Maintainer : bos@serpentine.com
1318-- Stability : experimental
1419-- Portability : GHC
1520--
16−-- A time and space-efficient implementation of Unicode text using
17−-- packed Word16 arrays. Suitable for performance critical use, both
18−-- in terms of large data quantities and high speed.
21+-- A time and space-efficient implementation of Unicode text.
22+-- Suitable for performance critical use, both in terms of large data
23+-- quantities and high speed.
24+--
25+-- /Note/: Read below the synopsis for important notes on the use of
26+-- this module.
1927--
2028-- This module is intended to be imported @qualified@, to avoid name
2129-- clashes with "Prelude" functions, e.g.
2230--
2331-- > import qualified Data.Text as T
32+--
33+-- To use an extended and very rich family of functions for working
34+-- with Unicode text (including normalization, regular expressions,
35+-- non-standard encodings, text breaking, and locales), see
36+-- <http://hackage.haskell.org/package/text-icu the text-icu package >.
2437
2538module Data.Text
2639 (
40+ -- * Strict vs lazy types
41+ -- $strict
42+
43+ -- * Acceptable data
44+ -- $replacement
45+
2746 -- * Fusion
2847 -- $fusion
2948
@@ -47,6 +66,7 @@ module Data.Text
4766 , init
4867 , null
4968 , length
69+ , compareLength
5070
5171 -- * Transformations
5272 , map
@@ -54,6 +74,19 @@ module Data.Text
5474 , intersperse
5575 , transpose
5676 , reverse
77+ , replace
78+
79+ -- ** Case conversion
80+ -- $case
81+ , toCaseFold
82+ , toLower
83+ , toUpper
84+ , toTitle
85+
86+ -- ** Justification
87+ , justifyLeft
88+ , justifyRight
89+ , center
5790
5891 -- * Folds
5992 , foldl
@@ -76,12 +109,12 @@ module Data.Text
76109 -- ** Scans
77110 , scanl
78111 , scanl1
79− -- , scanr
80− -- , scanr1
112+ , scanr
113+ , scanr1
81114
82115 -- ** Accumulating maps
83116 , mapAccumL
84− -- , mapAccumR
117+ , mapAccumR
85118
86119 -- ** Generation and unfolding
87120 , replicate
@@ -92,24 +125,36 @@ module Data.Text
92125
93126 -- ** Breaking strings
94127 , take
128+ , takeEnd
95129 , drop
130+ , dropEnd
96131 , takeWhile
132+ , takeWhileEnd
97133 , dropWhile
134+ , dropWhileEnd
135+ , dropAround
136+ , strip
137+ , stripStart
138+ , stripEnd
98139 , splitAt
99− , span
140+ , breakOn
141+ , breakOnEnd
100142 , break
143+ , span
101144 , group
102145 , groupBy
103146 , inits
104147 , tails
105148
106149 -- ** Breaking into many substrings
150+ -- $split
151+ , splitOn
107152 , split
108− , splitWith
109− , breakSubstring
153+ , chunksOf
110154
111155 -- ** Breaking into lines and words
112156 , lines
157+ --, lines'
113158 , words
114159 , unlines
115160 , unwords
@@ -119,146 +164,309 @@ module Data.Text
119164 , isSuffixOf
120165 , isInfixOf
121166
167+ -- ** View patterns
168+ , stripPrefix
169+ , stripSuffix
170+ , commonPrefixes
171+
122172 -- * Searching
123− , elem
124173 , filter
174+ , breakOnAll
125175 , find
126176 , partition
127177
128178 -- , findSubstring
129−
179+
130180 -- * Indexing
181+ -- $index
131182 , index
132183 , findIndex
133− , findIndices
134− , elemIndex
135− -- , elemIndices
136− -- , count
184+ , count
137185
138− -- * Zipping and unzipping
186+ -- * Zipping
187+ , zip
139188 , zipWith
140189
141− -- * Ordered ByteStrings
142− , -- sort
190+ -- -* Ordered text
191+ -- , sort
192+
193+ -- * Low level operations
194+ , copy
195+ , unpackCString#
143196 ) where
144197
145−import Prelude (Char, Bool(..), Functor(..), Int, Maybe(..), String,
146− Eq, (==), (++), error,
147− Read(..), Show(..),
148− (&&), (||), (+), (-), (<), (>), (<=), (>=), (.), ($),
149− not, return, otherwise)
198+import Prelude (Char, Bool(..), Int, Maybe(..), String,
199+ Eq(..), Ord(..), Ordering(..), (++),
200+ Read(..),
201+ (&&), (||), (+), (-), (.), ($), ($!), (>>),
202+ not, return, otherwise, quot)
203+#if defined(HAVE_DEEPSEQ)
204+import Control.DeepSeq (NFData(rnf))
205+#endif
206+#if defined(ASSERTS)
150207import Control.Exception (assert)
208+#endif
151209import Data.Char (isSpace)
210+import Data.Data (Data(gfoldl, toConstr, gunfold, dataTypeOf), constrIndex,
211+ Constr, mkConstr, DataType, mkDataType, Fixity(Prefix))
212+import Control.Monad (foldM)
152213import Control.Monad.ST (ST)
153214import qualified Data.Text.Array as A
154215import qualified Data.List as L
216+import Data.Binary (Binary(get, put))
155217import Data.Monoid (Monoid(..))
156−import Data.Word (Word16)
218+#if MIN_VERSION_base(4,9,0)
219+import Data.Semigroup (Semigroup(..))
220+#endif
157221import Data.String (IsString(..))
158−
159−import qualified Data.Text.Fusion as S
160−import Data.Text.Fusion (Stream(..), Step(..), stream, unstream)
161−import Data.Text.Internal (Text(..), empty, text)
222+import qualified Data.Text.Internal.Fusion as S
223+import qualified Data.Text.Internal.Fusion.Common as S
224+import Data.Text.Encoding (decodeUtf8', encodeUtf8)
225+import Data.Text.Internal.Fusion (stream, reverseStream, unstream)
226+import Data.Text.Internal.Private (span_)
227+import Data.Text.Internal (Text(..), empty, firstf, mul, safe, text)
228+import Data.Text.Show (singleton, unpack, unpackCString#)
162229import qualified Prelude as P
163−import Data.Text.Unsafe (iter, iter_)
164−import Data.Text.UnsafeChar (unsafeChr)
165−import qualified Data.Text.Utf16 as U16
230+import Data.Text.Unsafe (Iter(..), iter, iter_, lengthWord16, reverseIter,
231+ reverseIter_, unsafeHead, unsafeTail)
232+import Data.Text.Internal.Unsafe.Char (unsafeChr)
233+import qualified Data.Text.Internal.Functions as F
234+import qualified Data.Text.Internal.Encoding.Utf16 as U16
235+import Data.Text.Internal.Search (indices)
236+#if defined(__HADDOCK__)
237+import Data.ByteString (ByteString)
238+import qualified Data.Text.Lazy as L
239+import Data.Int (Int64)
240+#endif
241+import GHC.Base (eqInt, neInt, gtInt, geInt, ltInt, leInt)
242+#if __GLASGOW_HASKELL__ >= 708
243+import qualified GHC.Exts as Exts
244+#endif
245+#if MIN_VERSION_base(4,7,0)
246+import Text.Printf (PrintfArg, formatArg, formatString)
247+#endif
248+
249+-- $strict
250+--
251+-- This package provides both strict and lazy 'Text' types. The
252+-- strict type is provided by the "Data.Text" module, while the lazy
253+-- type is provided by the "Data.Text.Lazy" module. Internally, the
254+-- lazy @Text@ type consists of a list of strict chunks.
255+--
256+-- The strict 'Text' type requires that an entire string fit into
257+-- memory at once. The lazy 'Data.Text.Lazy.Text' type is capable of
258+-- streaming strings that are larger than memory using a small memory
259+-- footprint. In many cases, the overhead of chunked streaming makes
260+-- the lazy 'Data.Text.Lazy.Text' type slower than its strict
261+-- counterpart, but this is not always the case. Sometimes, the time
262+-- complexity of a function in one module may be different from the
263+-- other, due to their differing internal structures.
264+--
265+-- Each module provides an almost identical API, with the main
266+-- difference being that the strict module uses 'Int' values for
267+-- lengths and counts, while the lazy module uses 'Data.Int.Int64'
268+-- lengths.
269+
270+-- $replacement
271+--
272+-- A 'Text' value is a sequence of Unicode scalar values, as defined
273+-- in
274+-- <http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#page=35 §3.9, definition D76 of the Unicode 5.2 standard >.
275+-- As such, a 'Text' cannot contain values in the range U+D800 to
276+-- U+DFFF inclusive. Haskell implementations admit all Unicode code
277+-- points
278+-- (<http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#page=13 §3.4, definition D10 >)
279+-- as 'Char' values, including code points from this invalid range.
280+-- This means that there are some 'Char' values that are not valid
281+-- Unicode scalar values, and the functions in this module must handle
282+-- those cases.
283+--
284+-- Within this module, many functions construct a 'Text' from one or
285+-- more 'Char' values. Those functions will substitute 'Char' values
286+-- that are not valid Unicode scalar values with the replacement
287+-- character \"�\" (U+FFFD). Functions that perform this
288+-- inspection and replacement are documented with the phrase
289+-- \"Performs replacement on invalid scalar values\".
290+--
291+-- (One reason for this policy of replacement is that internally, a
292+-- 'Text' value is represented as packed UTF-16 data. Values in the
293+-- range U+D800 through U+DFFF are used by UTF-16 to denote surrogate
294+-- code points, and so cannot be represented. The functions replace
295+-- invalid scalar values, instead of dropping them, as a security
296+-- measure. For details, see
297+-- <http://unicode.org/reports/tr36/#Deletion_of_Noncharacters Unicode Technical Report 36, §3.5 >.)
166298
167299-- $fusion
168300--
169−-- Most of the functions in this module are subject to /array fusion/,
170−-- meaning that a pipeline of functions will usually allocate at most
171−-- one 'Text' value.
301+-- Most of the functions in this module are subject to /fusion/,
302+-- meaning that a pipeline of such functions will usually allocate at
303+-- most one 'Text' value.
304+--
305+-- As an example, consider the following pipeline:
306+--
307+-- > import Data.Text as T
308+-- > import Data.Text.Encoding as E
309+-- > import Data.ByteString (ByteString)
310+-- >
311+-- > countChars :: ByteString -> Int
312+-- > countChars = T.length . T.toUpper . E.decodeUtf8
313+--
314+-- From the type signatures involved, this looks like it should
315+-- allocate one 'Data.ByteString.ByteString' value, and two 'Text'
316+-- values. However, when a module is compiled with optimisation
317+-- enabled under GHC, the two intermediate 'Text' values will be
318+-- optimised away, and the function will be compiled down to a single
319+-- loop over the source 'Data.ByteString.ByteString'.
320+--
321+-- Functions that can be fused by the compiler are documented with the
322+-- phrase \"Subject to fusion\".
172323
173324instance Eq Text where
174− t1 == t2 = (stream t1) `S.eq` (stream t2)
325+ Text arrA offA lenA == Text arrB offB lenB
326+ | lenA == lenB = A.equal arrA offA arrB offB lenA
327+ | otherwise = False
328+ {-# INLINE (==) #-}
175329
176−instance Show Text where
177− showsPrec p ps r = showsPrec p (unpack ps) r
330+instance Ord Text where
331+ compare = compareText
178332
179333instance Read Text where
180334 readsPrec p str = [(pack x,y) | (x,y) <- readsPrec p str]
181335
336+#if MIN_VERSION_base(4,9,0)
337+-- Semigroup orphan instances for older GHCs are provided by
338+-- 'semigroups` package
339+
340+instance Semigroup Text where
341+ (<>) = append
342+#endif
343+
182344instance Monoid Text where
183345 mempty = empty
346+#if MIN_VERSION_base(4,9,0)
347+ mappend = (<>) -- future-proof definition
348+#else
184349 mappend = append
350+#endif
185351 mconcat = concat
186352
187353instance IsString Text where
188354 fromString = pack
189355
356+#if __GLASGOW_HASKELL__ >= 708
357+instance Exts.IsList Text where
358+ type Item Text = Char
359+ fromList = pack
360+ toList = unpack
361+#endif
362+
363+#if defined(HAVE_DEEPSEQ)
364+instance NFData Text where rnf !_ = ()
365+#endif
366+
367+instance Binary Text where
368+ put t = put (encodeUtf8 t)
369+ get = do
370+ bs <- get
371+ case decodeUtf8' bs of
372+ P.Left exn -> P.fail (P.show exn)
373+ P.Right a -> P.return a
374+
375+-- | This instance preserves data abstraction at the cost of inefficiency.
376+-- We omit reflection services for the sake of data abstraction.
377+--
378+-- This instance was created by copying the updated behavior of
379+-- @"Data.Set".@'Data.Set.Set' and @"Data.Map".@'Data.Map.Map'. If you
380+-- feel a mistake has been made, please feel free to submit
381+-- improvements.
382+--
383+-- The original discussion is archived here:
384+-- <http://groups.google.com/group/haskell-cafe/browse_thread/thread/b5bbb1b28a7e525d/0639d46852575b93 could we get a Data instance for Data.Text.Text? >
385+--
386+-- The followup discussion that changed the behavior of 'Data.Set.Set'
387+-- and 'Data.Map.Map' is archived here:
388+-- <http://markmail.org/message/trovdc6zkphyi3cr#query:+page:1+mid:a46der3iacwjcf6n+state:results Proposal: Allow gunfold for Data.Map, ... >
389+
390+instance Data Text where
391+ gfoldl f z txt = z pack `f` (unpack txt)
392+ toConstr _ = packConstr
393+ gunfold k z c = case constrIndex c of
394+ 1 -> k (z pack)
395+ _ -> P.error "gunfold"
396+ dataTypeOf _ = textDataType
397+
398+#if MIN_VERSION_base(4,7,0)
399+-- | Only defined for @base-4.7.0.0@ and later
400+instance PrintfArg Text where
401+ formatArg txt = formatString $ unpack txt
402+#endif
403+
404+packConstr :: Constr
405+packConstr = mkConstr textDataType "pack" [] Prefix
406+
407+textDataType :: DataType
408+textDataType = mkDataType "Data.Text.Text" [packConstr]
409+
410+-- | /O(n)/ Compare two 'Text' values lexicographically.
411+compareText :: Text -> Text -> Ordering
412+compareText ta@(Text _arrA _offA lenA) tb@(Text _arrB _offB lenB)
413+ | lenA == 0 && lenB == 0 = EQ
414+ | otherwise = go 0 0
415+ where
416+ go !i !j
417+ | i >= lenA || j >= lenB = compare lenA lenB
418+ | a < b = LT
419+ | a > b = GT
420+ | otherwise = go (i+di) (j+dj)
421+ where Iter a di = iter ta i
422+ Iter b dj = iter tb j
423+
190424-- -----------------------------------------------------------------------------
191425-- * Conversion to/from 'Text'
192426
193−-- | /O(n)/ Convert a 'String' into a 'Text'.
194−--
195−-- This function is subject to array fusion.
427+-- | /O(n)/ Convert a 'String' into a 'Text'. Subject to
428+-- fusion. Performs replacement on invalid scalar values.
196429pack :: String -> Text
197−pack str = (unstream (stream_list str))
198− where
199− stream_list s0 = S.Stream next s0 (P.length s0) -- total guess
200− where
201− next [] = S.Done
202− next (x:xs) = S.Yield x xs
430+pack = unstream . S.map safe . S.streamList
203431{-# INLINE [1] pack #-}
204−-- TODO: Has to do validation! -- No, it doesn't, the
205−
206−-- | /O(n)/ Convert a Text into a String.
207−-- Subject to array fusion.
208−unpack :: Text -> String
209−unpack txt = (unstream_list (stream txt))
210− where
211− unstream_list (S.Stream next s0 _len) = unfold s0
212− where
213− unfold !s = case next s of
214− S.Done -> []
215− S.Skip s' -> unfold s'
216− S.Yield x s' -> x : unfold s'
217−{-# INLINE [1] unpack #-}
218−
219−-- | /O(1)/ Convert a character into a Text.
220−-- Subject to array fusion.
221−singleton :: Char -> Text
222−singleton c = unstream (Stream next (c:[]) 1)
223− where
224− {-# INLINE next #-}
225− next (k:ks) = Yield k ks
226− next [] = Done
227−{-# INLINE [1] singleton #-}
228432
229433-- -----------------------------------------------------------------------------
230434-- * Basic functions
231435
232436-- | /O(n)/ Adds a character to the front of a 'Text'. This function
233437-- is more costly than its 'List' counterpart because it requires
234−-- copying a new array. Subject to array fusion.
438+-- copying a new array. Subject to fusion. Performs replacement on
439+-- invalid scalar values.
235440cons :: Char -> Text -> Text
236−cons c t = unstream (S.cons c (stream t))
441+cons c t = unstream (S.cons (safe c) (stream t))
237442{-# INLINE cons #-}
238443
444+infixr 5 `cons`
445+
239446-- | /O(n)/ Adds a character to the end of a 'Text'. This copies the
240−-- entire array in the process. Subject to array fusion.
447+-- entire array in the process, unless fused. Subject to fusion.
448+-- Performs replacement on invalid scalar values.
241449snoc :: Text -> Char -> Text
242−snoc t c = unstream (S.snoc (stream t) c)
450+snoc t c = unstream (S.snoc (stream t) (safe c))
243451{-# INLINE snoc #-}
244452
245453-- | /O(n)/ Appends one 'Text' to the other by copying both of them
246−-- into a new 'Text'. Subject to array fusion.
454+-- into a new 'Text'. Subject to fusion.
247455append :: Text -> Text -> Text
248−append (Text arr1 off1 len1) (Text arr2 off2 len2) = Text (A.run x) 0 len
456+append a@(Text arr1 off1 len1) b@(Text arr2 off2 len2)
457+ | len1 == 0 = b
458+ | len2 == 0 = a
459+ | len > 0 = Text (A.run x) 0 len
460+ | otherwise = overflowError "append"
249461 where
250462 len = len1+len2
463+ x :: ST s (A.MArray s)
251464 x = do
252− arr <- A.unsafeNew len :: ST s (A.MArray s Word16)
253− copy arr1 off1 (len1+off1) arr 0
254− copy arr2 off2 (len2+off2) arr len1
465+ arr <- A.new len
466+ A.copyI arr 0 arr1 off1 len1
467+ A.copyI arr len1 arr2 off2 len
255468 return arr
256− where
257− copy arr i max arr' j
258− | i >= max = return ()
259− | otherwise = do A.unsafeWrite arr' j (arr `A.unsafeIndex` i)
260− copy arr (i+1) max arr' (j+1)
261−{-# INLINE append #-}
469+{-# NOINLINE append #-}
262470
263471{-# RULES
264472"TEXT append -> fused" [~1] forall t1 t2.
@@ -268,35 +476,29 @@ append (Text arr1 off1 len1) (Text arr2 off2 len2) = Text (A.run x) 0 len
268476 #-}
269477
270478-- | /O(1)/ Returns the first character of a 'Text', which must be
271−-- non-empty. Subject to array fusion.
479+-- non-empty. Subject to fusion.
272480head :: Text -> Char
273481head t = S.head (stream t)
274482{-# INLINE head #-}
275483
276484-- | /O(1)/ Returns the first character and rest of a 'Text', or
277−-- 'Nothing' if empty. Subject to array fusion.
485+-- 'Nothing' if empty. Subject to fusion.
278486uncons :: Text -> Maybe (Char, Text)
279487uncons t@(Text arr off len)
280488 | len <= 0 = Nothing
281− | otherwise = Just (c, Text arr (off+d) (len-d))
282− where (c,d) = iter t 0
283−{-# INLINE uncons #-}
489+ | otherwise = Just $ let !(Iter c d) = iter t 0
490+ in (c, text arr (off+d) (len-d))
491+{-# INLINE [1] uncons #-}
284492
493+-- | Lifted from Control.Arrow and specialized.
285494second :: (b -> c) -> (a,b) -> (a,c)
286495second f (a, b) = (a, f b)
287496
288−{-# RULES
289−"TEXT uncons -> fused" [~1] forall t.
290− uncons t = fmap (second unstream) (S.uncons (stream t))
291−"TEXT uncons -> unfused" [1] forall t.
292− fmap (second unstream) (S.uncons (stream t)) = uncons t
293− #-}
294−
295497-- | /O(1)/ Returns the last character of a 'Text', which must be
296−-- non-empty. Subject to array fusion.
498+-- non-empty. Subject to fusion.
297499last :: Text -> Char
298500last (Text arr off len)
299− | len <= 0 = errorEmptyList "last"
501+ | len <= 0 = emptyError "last"
300502 | n < 0xDC00 || n > 0xDFFF = unsafeChr n
301503 | otherwise = U16.chr2 n0 n
302504 where n = A.unsafeIndex arr (off+len-1)
@@ -310,19 +512,12 @@ last (Text arr off len)
310512 S.last (stream t) = last t
311513 #-}
312514
313−-- | Construct a 'Text' without invisibly pinning its byte array in
314−-- memory if its length has dwindled to zero.
315−textP :: A.Array Word16 -> Int -> Int -> Text
316−textP arr off len | len == 0 = empty
317− | otherwise = text arr off len
318−{-# INLINE textP #-}
319−
320515-- | /O(1)/ Returns all characters after the head of a 'Text', which
321−-- must be non-empty. Subject to array fusion.
516+-- must be non-empty. Subject to fusion.
322517tail :: Text -> Text
323518tail t@(Text arr off len)
324− | len <= 0 = errorEmptyList "tail"
325− | otherwise = textP arr (off+d) (len-d)
519+ | len <= 0 = emptyError "tail"
520+ | otherwise = text arr (off+d) (len-d)
326521 where d = iter_ t 0
327522{-# INLINE [1] tail #-}
328523
@@ -334,11 +529,11 @@ tail t@(Text arr off len)
334529 #-}
335530
336531-- | /O(1)/ Returns all but the last character of a 'Text', which must
337−-- be non-empty. Subject to array fusion.
532+-- be non-empty. Subject to fusion.
338533init :: Text -> Text
339−init (Text arr off len) | len <= 0 = errorEmptyList "init"
340− | n >= 0xDC00 && n <= 0xDFFF = textP arr off (len-2)
341− | otherwise = textP arr off (len-1)
534+init (Text arr off len) | len <= 0 = emptyError "init"
535+ | n >= 0xDC00 && n <= 0xDFFF = text arr off (len-2)
536+ | otherwise = text arr off (len-1)
342537 where
343538 n = A.unsafeIndex arr (off+len-1)
344539{-# INLINE [1] init #-}
@@ -350,10 +545,14 @@ init (Text arr off len) | len <= 0 = errorEmptyList "init"
350545 unstream (S.init (stream t)) = init t
351546 #-}
352547
353−-- | /O(1)/ Tests whether a 'Text' is empty or not. Subject to array
548+-- | /O(1)/ Tests whether a 'Text' is empty or not. Subject to
354549-- fusion.
355550null :: Text -> Bool
356−null (Text _arr _off len) = assert (len >= 0) $ len <= 0
551+null (Text _arr _off len) =
552+#if defined(ASSERTS)
553+ assert (len >= 0) $
554+#endif
555+ len <= 0
357556{-# INLINE [1] null #-}
358557
359558{-# RULES
@@ -363,41 +562,287 @@ null (Text _arr _off len) = assert (len >= 0) $ len <= 0
363562 S.null (stream t) = null t
364563 #-}
365564
565+-- | /O(1)/ Tests whether a 'Text' contains exactly one character.
566+-- Subject to fusion.
567+isSingleton :: Text -> Bool
568+isSingleton = S.isSingleton . stream
569+{-# INLINE isSingleton #-}
570+
366571-- | /O(n)/ Returns the number of characters in a 'Text'.
367−-- Subject to array fusion.
572+-- Subject to fusion.
368573length :: Text -> Int
369574length t = S.length (stream t)
370−{-# INLINE length #-}
575+{-# INLINE [0] length #-}
576+-- length needs to be phased after the compareN/length rules otherwise
577+-- it may inline before the rules have an opportunity to fire.
578+
579+-- | /O(n)/ Compare the count of characters in a 'Text' to a number.
580+-- Subject to fusion.
581+--
582+-- This function gives the same answer as comparing against the result
583+-- of 'length', but can short circuit if the count of characters is
584+-- greater than the number, and hence be more efficient.
585+compareLength :: Text -> Int -> Ordering
586+compareLength t n = S.compareLengthI (stream t) n
587+{-# INLINE [1] compareLength #-}
588+
589+{-# RULES
590+"TEXT compareN/length -> compareLength" [~1] forall t n.
591+ compare (length t) n = compareLength t n
592+ #-}
593+
594+{-# RULES
595+"TEXT ==N/length -> compareLength/==EQ" [~1] forall t n.
596+ eqInt (length t) n = compareLength t n == EQ
597+ #-}
598+
599+{-# RULES
600+"TEXT /=N/length -> compareLength//=EQ" [~1] forall t n.
601+ neInt (length t) n = compareLength t n /= EQ
602+ #-}
603+
604+{-# RULES
605+"TEXT <N/length -> compareLength/==LT" [~1] forall t n.
606+ ltInt (length t) n = compareLength t n == LT
607+ #-}
608+
609+{-# RULES
610+"TEXT <=N/length -> compareLength//=GT" [~1] forall t n.
611+ leInt (length t) n = compareLength t n /= GT
612+ #-}
613+
614+{-# RULES
615+"TEXT >N/length -> compareLength/==GT" [~1] forall t n.
616+ gtInt (length t) n = compareLength t n == GT
617+ #-}
618+
619+{-# RULES
620+"TEXT >=N/length -> compareLength//=LT" [~1] forall t n.
621+ geInt (length t) n = compareLength t n /= LT
622+ #-}
371623
372624-- -----------------------------------------------------------------------------
373625-- * Transformations
374−-- | /O(n)/ 'map' @f @xs is the 'Text' obtained by applying @f@ to
375−-- each element of @xs@. Subject to array fusion.
626+-- | /O(n)/ 'map' @f@ @t@ is the 'Text' obtained by applying @f@ to
627+-- each element of @t@. Subject to fusion. Performs replacement on
628+-- invalid scalar values.
376629map :: (Char -> Char) -> Text -> Text
377−map f t = unstream (S.map f (stream t))
630+map f t = unstream (S.map (safe . f) (stream t))
378631{-# INLINE [1] map #-}
379632
380633-- | /O(n)/ The 'intercalate' function takes a 'Text' and a list of
381634-- 'Text's and concatenates the list after interspersing the first
382635-- argument between each element of the list.
383636intercalate :: Text -> [Text] -> Text
384−intercalate t ts = unstream (S.intercalate (stream t) (L.map stream ts))
637+intercalate t = concat . (F.intersperse t)
385638{-# INLINE intercalate #-}
386639
387640-- | /O(n)/ The 'intersperse' function takes a character and places it
388−-- between the characters of a 'Text'. Subject to array fusion.
641+-- between the characters of a 'Text'. Subject to fusion. Performs
642+-- replacement on invalid scalar values.
389643intersperse :: Char -> Text -> Text
390−intersperse c t = unstream (S.intersperse c (stream t))
644+intersperse c t = unstream (S.intersperse (safe c) (stream t))
391645{-# INLINE intersperse #-}
392646
393−-- | /O(n)/ Reverse the characters of a string. Subject to array fusion.
647+-- | /O(n)/ Reverse the characters of a string. Subject to fusion.
394648reverse :: Text -> Text
395649reverse t = S.reverse (stream t)
396650{-# INLINE reverse #-}
397651
652+-- | /O(m+n)/ Replace every non-overlapping occurrence of @needle@ in
653+-- @haystack@ with @replacement@.
654+--
655+-- This function behaves as though it was defined as follows:
656+--
657+-- @
658+-- replace needle replacement haystack =
659+-- 'intercalate' replacement ('splitOn' needle haystack)
660+-- @
661+--
662+-- As this suggests, each occurrence is replaced exactly once. So if
663+-- @needle@ occurs in @replacement@, that occurrence will /not/ itself
664+-- be replaced recursively:
665+--
666+-- > replace "oo" "foo" "oo" == "foo"
667+--
668+-- In cases where several instances of @needle@ overlap, only the
669+-- first one will be replaced:
670+--
671+-- > replace "ofo" "bar" "ofofo" == "barfo"
672+--
673+-- In (unlikely) bad cases, this function's time complexity degrades
674+-- towards /O(n*m)/.
675+replace :: Text
676+ -- ^ @needle@ to search for. If this string is empty, an
677+ -- error will occur.
678+ -> Text
679+ -- ^ @replacement@ to replace @needle@ with.
680+ -> Text
681+ -- ^ @haystack@ in which to search.
682+ -> Text
683+replace needle@(Text _ _ neeLen)
684+ (Text repArr repOff repLen)
685+ haystack@(Text hayArr hayOff hayLen)
686+ | neeLen == 0 = emptyError "replace"
687+ | L.null ixs = haystack
688+ | len > 0 = Text (A.run x) 0 len
689+ | otherwise = empty
690+ where
691+ ixs = indices needle haystack
692+ len = hayLen - (neeLen - repLen) `mul` L.length ixs
693+ x :: ST s (A.MArray s)
694+ x = do
695+ marr <- A.new len
696+ let loop (i:is) o d = do
697+ let d0 = d + i - o
698+ d1 = d0 + repLen
699+ A.copyI marr d hayArr (hayOff+o) d0
700+ A.copyI marr d0 repArr repOff d1
701+ loop is (i + neeLen) d1
702+ loop [] o d = A.copyI marr d hayArr (hayOff+o) len
703+ loop ixs 0 0
704+ return marr
705+
706+-- ----------------------------------------------------------------------------
707+-- ** Case conversions (folds)
708+
709+-- $case
710+--
711+-- When case converting 'Text' values, do not use combinators like
712+-- @map toUpper@ to case convert each character of a string
713+-- individually, as this gives incorrect results according to the
714+-- rules of some writing systems. The whole-string case conversion
715+-- functions from this module, such as @toUpper@, obey the correct
716+-- case conversion rules. As a result, these functions may map one
717+-- input character to two or three output characters. For examples,
718+-- see the documentation of each function.
719+--
720+-- /Note/: In some languages, case conversion is a locale- and
721+-- context-dependent operation. The case conversion functions in this
722+-- module are /not/ locale sensitive. Programs that require locale
723+-- sensitivity should use appropriate versions of the
724+-- <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 >.
725+
726+-- | /O(n)/ Convert a string to folded case. Subject to fusion.
727+--
728+-- This function is mainly useful for performing caseless (also known
729+-- as case insensitive) string comparisons.
730+--
731+-- A string @x@ is a caseless match for a string @y@ if and only if:
732+--
733+-- @toCaseFold x == toCaseFold y@
734+--
735+-- The result string may be longer than the input string, and may
736+-- differ from applying 'toLower' to the input string. For instance,
737+-- the Armenian small ligature \"ﬓ\" (men now, U+FB13) is case
738+-- folded to the sequence \"մ\" (men, U+0574) followed by
739+-- \"ն\" (now, U+0576), while the Greek \"µ\" (micro sign,
740+-- U+00B5) is case folded to \"μ\" (small letter mu, U+03BC)
741+-- instead of itself.
742+toCaseFold :: Text -> Text
743+toCaseFold t = unstream (S.toCaseFold (stream t))
744+{-# INLINE toCaseFold #-}
745+
746+-- | /O(n)/ Convert a string to lower case, using simple case
747+-- conversion. Subject to fusion.
748+--
749+-- The result string may be longer than the input string. For
750+-- instance, \"İ\" (Latin capital letter I with dot above,
751+-- U+0130) maps to the sequence \"i\" (Latin small letter i, U+0069)
752+-- followed by \" ̇\" (combining dot above, U+0307).
753+toLower :: Text -> Text
754+toLower t = unstream (S.toLower (stream t))
755+{-# INLINE toLower #-}
756+
757+-- | /O(n)/ Convert a string to upper case, using simple case
758+-- conversion. Subject to fusion.
759+--
760+-- The result string may be longer than the input string. For
761+-- instance, the German \"ß\" (eszett, U+00DF) maps to the
762+-- two-letter sequence \"SS\".
763+toUpper :: Text -> Text
764+toUpper t = unstream (S.toUpper (stream t))
765+{-# INLINE toUpper #-}
766+
767+-- | /O(n)/ Convert a string to title case, using simple case
768+-- conversion. Subject to fusion.
769+--
770+-- The first letter of the input is converted to title case, as is
771+-- every subsequent letter that immediately follows a non-letter.
772+-- Every letter that immediately follows another letter is converted
773+-- to lower case.
774+--
775+-- The result string may be longer than the input string. For example,
776+-- the Latin small ligature fl (U+FB02) is converted to the
777+-- sequence Latin capital letter F (U+0046) followed by Latin small
778+-- letter l (U+006C).
779+--
780+-- /Note/: this function does not take language or culture specific
781+-- rules into account. For instance, in English, different style
782+-- guides disagree on whether the book name \"The Hill of the Red
783+-- Fox\" is correctly title cased—but this function will
784+-- capitalize /every/ word.
785+toTitle :: Text -> Text
786+toTitle t = unstream (S.toTitle (stream t))
787+{-# INLINE toTitle #-}
788+
789+-- | /O(n)/ Left-justify a string to the given length, using the
790+-- specified fill character on the right. Subject to fusion.
791+-- Performs replacement on invalid scalar values.
792+--
793+-- Examples:
794+--
795+-- > justifyLeft 7 'x' "foo" == "fooxxxx"
796+-- > justifyLeft 3 'x' "foobar" == "foobar"
797+justifyLeft :: Int -> Char -> Text -> Text
798+justifyLeft k c t
799+ | len >= k = t
800+ | otherwise = t `append` replicateChar (k-len) c
801+ where len = length t
802+{-# INLINE [1] justifyLeft #-}
803+
804+{-# RULES
805+"TEXT justifyLeft -> fused" [~1] forall k c t.
806+ justifyLeft k c t = unstream (S.justifyLeftI k c (stream t))
807+"TEXT justifyLeft -> unfused" [1] forall k c t.
808+ unstream (S.justifyLeftI k c (stream t)) = justifyLeft k c t
809+ #-}
810+
811+-- | /O(n)/ Right-justify a string to the given length, using the
812+-- specified fill character on the left. Performs replacement on
813+-- invalid scalar values.
814+--
815+-- Examples:
816+--
817+-- > justifyRight 7 'x' "bar" == "xxxxbar"
818+-- > justifyRight 3 'x' "foobar" == "foobar"
819+justifyRight :: Int -> Char -> Text -> Text
820+justifyRight k c t
821+ | len >= k = t
822+ | otherwise = replicateChar (k-len) c `append` t
823+ where len = length t
824+{-# INLINE justifyRight #-}
825+
826+-- | /O(n)/ Center a string to the given length, using the specified
827+-- fill character on either side. Performs replacement on invalid
828+-- scalar values.
829+--
830+-- Examples:
831+--
832+-- > center 8 'x' "HS" = "xxxHSxxx"
833+center :: Int -> Char -> Text -> Text
834+center k c t
835+ | len >= k = t
836+ | otherwise = replicateChar l c `append` t `append` replicateChar r c
837+ where len = length t
838+ d = k - len
839+ r = d `quot` 2
840+ l = d - r
841+{-# INLINE center #-}
842+
398843-- | /O(n)/ The 'transpose' function transposes the rows and columns
399844-- of its 'Text' argument. Note that this function uses 'pack',
400−-- 'unpack', and the 'List' version of transpose and is thus not very
845+-- 'unpack', and the list version of transpose, and is thus not very
401846-- efficient.
402847transpose :: [Text] -> [Text]
403848transpose ts = P.map pack (L.transpose (P.map unpack ts))
@@ -405,43 +850,40 @@ transpose ts = P.map pack (L.transpose (P.map unpack ts))
405850-- -----------------------------------------------------------------------------
406851-- * Reducing 'Text's (folds)
407852
408−-- | 'foldl', applied to a binary operator, a starting value
853+-- | /O(n)/ 'foldl', applied to a binary operator, a starting value
409854-- (typically the left-identity of the operator), and a 'Text',
410855-- reduces the 'Text' using the binary operator, from left to right.
411−-- Subject to array fusion.
412−foldl :: (b -> Char -> b) -> b -> Text -> b
856+-- Subject to fusion.
857+foldl :: (a -> Char -> a) -> a -> Text -> a
413858foldl f z t = S.foldl f z (stream t)
414859{-# INLINE foldl #-}
415860
416−-- | A strict version of 'foldl'.
417−-- Subject to array fusion.
418−foldl' :: (b -> Char -> b) -> b -> Text -> b
861+-- | /O(n)/ A strict version of 'foldl'. Subject to fusion.
862+foldl' :: (a -> Char -> a) -> a -> Text -> a
419863foldl' f z t = S.foldl' f z (stream t)
420864{-# INLINE foldl' #-}
421865
422−-- | A variant of 'foldl' that has no starting value argument, and
423−-- thus must be applied to a non-empty 'Text'. Subject to array
424−-- fusion.
866+-- | /O(n)/ A variant of 'foldl' that has no starting value argument,
867+-- and thus must be applied to a non-empty 'Text'. Subject to fusion.
425868foldl1 :: (Char -> Char -> Char) -> Text -> Char
426869foldl1 f t = S.foldl1 f (stream t)
427870{-# INLINE foldl1 #-}
428871
429−-- | A strict version of 'foldl1'.
430−-- Subject to array fusion.
872+-- | /O(n)/ A strict version of 'foldl1'. Subject to fusion.
431873foldl1' :: (Char -> Char -> Char) -> Text -> Char
432874foldl1' f t = S.foldl1' f (stream t)
433875{-# INLINE foldl1' #-}
434876
435−-- | 'foldr', applied to a binary operator, a starting value
877+-- | /O(n)/ 'foldr', applied to a binary operator, a starting value
436878-- (typically the right-identity of the operator), and a 'Text',
437879-- reduces the 'Text' using the binary operator, from right to left.
438−-- Subject to array fusion.
439−foldr :: (Char -> b -> b) -> b -> Text -> b
880+-- Subject to fusion.
881+foldr :: (Char -> a -> a) -> a -> Text -> a
440882foldr f z t = S.foldr f z (stream t)
441883{-# INLINE foldr #-}
442884
443−-- | A variant of 'foldr' that has no starting value argument, and
444−-- thust must be applied to a non-empty 'Text'. Subject to array
885+-- | /O(n)/ A variant of 'foldr' that has no starting value argument,
886+-- and thus must be applied to a non-empty 'Text'. Subject to
445887-- fusion.
446888foldr1 :: (Char -> Char -> Char) -> Text -> Char
447889foldr1 f t = S.foldr1 f (stream t)
@@ -450,40 +892,48 @@ foldr1 f t = S.foldr1 f (stream t)
450892-- -----------------------------------------------------------------------------
451893-- ** Special folds
452894
453−-- | /O(n)/ Concatenate a list of 'Text's. Subject to array fusion.
895+-- | /O(n)/ Concatenate a list of 'Text's.
454896concat :: [Text] -> Text
455−concat ts = unstream (S.concat (L.map stream ts))
456−{-# INLINE concat #-}
457−
458−-- | Map a function over a 'Text' that results in a 'Text', and concatenate the
459−-- results. This function is subject to array fusion.
460−--
461−-- Note: if in 'concatMap' @f @xs, @f@ is defined in terms of fusible
462−-- functions, it will also be fusible.
897+concat ts = case ts' of
898+ [] -> empty
899+ [t] -> t
900+ _ -> Text (A.run go) 0 len
901+ where
902+ ts' = L.filter (not . null) ts
903+ len = sumP "concat" $ L.map lengthWord16 ts'
904+ go :: ST s (A.MArray s)
905+ go = do
906+ arr <- A.new len
907+ let step i (Text a o l) =
908+ let !j = i + l in A.copyI arr i a o j >> return j
909+ foldM step 0 ts' >> return arr
910+
911+-- | /O(n)/ Map a function over a 'Text' that results in a 'Text', and
912+-- concatenate the results.
463913concatMap :: (Char -> Text) -> Text -> Text
464−concatMap f t = unstream (S.concatMap (stream . f) (stream t))
914+concatMap f = concat . foldr ((:) . f) []
465915{-# INLINE concatMap #-}
466916
467−-- | 'any' @p @xs determines whether any character in the 'Text' @xs@
468−-- satisifes the predicate @p@. Subject to array fusion.
917+-- | /O(n)/ 'any' @p@ @t@ determines whether any character in the
918+-- 'Text' @t@ satisfies the predicate @p@. Subject to fusion.
469919any :: (Char -> Bool) -> Text -> Bool
470920any p t = S.any p (stream t)
471921{-# INLINE any #-}
472922
473−-- | 'all' @p @xs determines whether all characters in the 'Text' @xs@
474−-- satisify the predicate @p@. Subject to array fusion.
923+-- | /O(n)/ 'all' @p@ @t@ determines whether all characters in the
924+-- 'Text' @t@ satisfy the predicate @p@. Subject to fusion.
475925all :: (Char -> Bool) -> Text -> Bool
476926all p t = S.all p (stream t)
477927{-# INLINE all #-}
478928
479929-- | /O(n)/ 'maximum' returns the maximum value from a 'Text', which
480−-- must be non-empty. Subject to array fusion.
930+-- must be non-empty. Subject to fusion.
481931maximum :: Text -> Char
482932maximum t = S.maximum (stream t)
483933{-# INLINE maximum #-}
484934
485935-- | /O(n)/ 'minimum' returns the minimum value from a 'Text', which
486−-- must be non-empty. Subject to array fusion.
936+-- must be non-empty. Subject to fusion.
487937minimum :: Text -> Char
488938minimum t = S.minimum (stream t)
489939{-# INLINE minimum #-}
@@ -492,8 +942,8 @@ minimum t = S.minimum (stream t)
492942-- * Building 'Text's
493943
494944-- | /O(n)/ 'scanl' is similar to 'foldl', but returns a list of
495−-- successive reduced values from the left. This function is subject
496−-- to array fusion.
945+-- successive reduced values from the left. Subject to fusion.
946+-- Performs replacement on invalid scalar values.
497947--
498948-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
499949--
@@ -501,72 +951,131 @@ minimum t = S.minimum (stream t)
501951--
502952-- > last (scanl f z xs) == foldl f z xs.
503953scanl :: (Char -> Char -> Char) -> Char -> Text -> Text
504−scanl f z t = unstream (S.scanl f z (stream t))
954+scanl f z t = unstream (S.scanl g z (stream t))
955+ where g a b = safe (f a b)
505956{-# INLINE scanl #-}
506957
507958-- | /O(n)/ 'scanl1' is a variant of 'scanl' that has no starting
508−-- value argument. This function is subject to array fusion.
959+-- value argument. Subject to fusion. Performs replacement on
960+-- invalid scalar values.
509961--
510962-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
511963scanl1 :: (Char -> Char -> Char) -> Text -> Text
512964scanl1 f t | null t = empty
513− | otherwise = scanl f (head t) (tail t)
965+ | otherwise = scanl f (unsafeHead t) (unsafeTail t)
514966{-# INLINE scanl1 #-}
515967
516−-- | /O(n)/ Like a combination of 'map' and 'foldl'. Applies a
517−-- function to each element of a 'Text', passing an accumulating
518−-- parameter from left to right, and returns a final 'Text'.
968+-- | /O(n)/ 'scanr' is the right-to-left dual of 'scanl'. Performs
969+-- replacement on invalid scalar values.
519970--
520−-- /Note/: Unlike the version over lists, this function does not return a
521−-- final value for the accumulator.
522−mapAccumL :: (a -> Char -> (a,Char)) -> a -> Text -> Text
523−mapAccumL f z t = unstream (S.mapAccumL f z (stream t))
971+-- > scanr f v == reverse . scanl (flip f) v . reverse
972+scanr :: (Char -> Char -> Char) -> Char -> Text -> Text
973+scanr f z = S.reverse . S.reverseScanr g z . reverseStream
974+ where g a b = safe (f a b)
975+{-# INLINE scanr #-}
976+
977+-- | /O(n)/ 'scanr1' is a variant of 'scanr' that has no starting
978+-- value argument. Subject to fusion. Performs replacement on
979+-- invalid scalar values.
980+scanr1 :: (Char -> Char -> Char) -> Text -> Text
981+scanr1 f t | null t = empty
982+ | otherwise = scanr f (last t) (init t)
983+{-# INLINE scanr1 #-}
984+
985+-- | /O(n)/ Like a combination of 'map' and 'foldl''. Applies a
986+-- function to each element of a 'Text', passing an accumulating
987+-- parameter from left to right, and returns a final 'Text'. Performs
988+-- replacement on invalid scalar values.
989+mapAccumL :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
990+mapAccumL f z0 = S.mapAccumL g z0 . stream
991+ where g a b = second safe (f a b)
524992{-# INLINE mapAccumL #-}
525993
994+-- | The 'mapAccumR' function behaves like a combination of 'map' and
995+-- a strict 'foldr'; it applies a function to each element of a
996+-- 'Text', passing an accumulating parameter from right to left, and
997+-- returning a final value of this accumulator together with the new
998+-- 'Text'.
999+-- Performs replacement on invalid scalar values.
1000+mapAccumR :: (a -> Char -> (a,Char)) -> a -> Text -> (a, Text)
1001+mapAccumR f z0 = second reverse . S.mapAccumL g z0 . reverseStream
1002+ where g a b = second safe (f a b)
1003+{-# INLINE mapAccumR #-}
1004+
5261005-- -----------------------------------------------------------------------------
5271006-- ** Generating and unfolding 'Text's
5281007
529−replicate :: Int -> Char -> Text
530−replicate n c = unstream (S.replicate n c)
531−{-# INLINE replicate #-}
1008+-- | /O(n*m)/ 'replicate' @n@ @t@ is a 'Text' consisting of the input
1009+-- @t@ repeated @n@ times.
1010+replicate :: Int -> Text -> Text
1011+replicate n t@(Text a o l)
1012+ | n <= 0 || l <= 0 = empty
1013+ | n == 1 = t
1014+ | isSingleton t = replicateChar n (unsafeHead t)
1015+ | otherwise = Text (A.run x) 0 len
1016+ where
1017+ len = l `mul` n
1018+ x :: ST s (A.MArray s)
1019+ x = do
1020+ arr <- A.new len
1021+ let loop !d !i | i >= n = return arr
1022+ | otherwise = let m = d + l
1023+ in A.copyI arr d a o m >> loop m (i+1)
1024+ loop 0 0
1025+{-# INLINE [1] replicate #-}
1026+
1027+{-# RULES
1028+"TEXT replicate/singleton -> replicateChar" [~1] forall n c.
1029+ replicate n (singleton c) = replicateChar n c
1030+ #-}
1031+
1032+-- | /O(n)/ 'replicateChar' @n@ @c@ is a 'Text' of length @n@ with @c@ the
1033+-- value of every element. Subject to fusion.
1034+replicateChar :: Int -> Char -> Text
1035+replicateChar n c = unstream (S.replicateCharI n (safe c))
1036+{-# INLINE replicateChar #-}
5321037
5331038-- | /O(n)/, where @n@ is the length of the result. The 'unfoldr'
5341039-- function is analogous to the List 'L.unfoldr'. 'unfoldr' builds a
5351040-- 'Text' from a seed value. The function takes the element and
5361041-- returns 'Nothing' if it is done producing the 'Text', otherwise
5371042-- 'Just' @(a,b)@. In this case, @a@ is the next 'Char' in the
538−-- string, and @b@ is the seed value for further production.
1043+-- string, and @b@ is the seed value for further production. Subject
1044+-- to fusion. Performs replacement on invalid scalar values.
5391045unfoldr :: (a -> Maybe (Char,a)) -> a -> Text
540−unfoldr f s = unstream (S.unfoldr f s)
1046+unfoldr f s = unstream (S.unfoldr (firstf safe . f) s)
5411047{-# INLINE unfoldr #-}
5421048
5431049-- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a 'Text' from a seed
5441050-- value. However, the length of the result should be limited by the
5451051-- first argument to 'unfoldrN'. This function is more efficient than
5461052-- 'unfoldr' when the maximum length of the result is known and
547−-- correct, otherwise its performance is similar to 'unfoldr'.
1053+-- correct, otherwise its performance is similar to 'unfoldr'. Subject
1054+-- to fusion. Performs replacement on invalid scalar values.
5481055unfoldrN :: Int -> (a -> Maybe (Char,a)) -> a -> Text
549−unfoldrN n f s = unstream (S.unfoldrN n f s)
1056+unfoldrN n f s = unstream (S.unfoldrN n (firstf safe . f) s)
5501057{-# INLINE unfoldrN #-}
5511058
5521059-- -----------------------------------------------------------------------------
5531060-- * Substrings
5541061
555−-- /O(n) 'take' @n@, applied to a 'Text', returns the prefix of the
1062+-- | /O(n)/ 'take' @n@, applied to a 'Text', returns the prefix of the
5561063-- 'Text' of length @n@, or the 'Text' itself if @n@ is greater than
557−-- the length of the Text.
1064+-- the length of the Text. Subject to fusion.
5581065take :: Int -> Text -> Text
5591066take n t@(Text arr off len)
5601067 | n <= 0 = empty
5611068 | n >= len = t
562− | otherwise = Text arr off (loop 0 0)
563− where
564− loop !i !count
565− | i >= len || count >= n = i
566− | otherwise = loop (i+d) (count+1)
567− where d = iter_ t i
1069+ | otherwise = text arr off (iterN n t)
5681070{-# INLINE [1] take #-}
5691071
1072+iterN :: Int -> Text -> Int
1073+iterN n t@(Text _arr _off len) = loop 0 0
1074+ where loop !i !cnt
1075+ | i >= len || cnt >= n = i
1076+ | otherwise = loop (i+d) (cnt+1)
1077+ where d = iter_ t i
1078+
5701079{-# RULES
5711080"TEXT take -> fused" [~1] forall n t.
5721081 take n t = unstream (S.take n (stream t))
@@ -574,19 +1083,36 @@ take n t@(Text arr off len)
5741083 unstream (S.take n (stream t)) = take n t
5751084 #-}
5761085
1086+-- | /O(n)/ 'takeEnd' @n@ @t@ returns the suffix remaining after
1087+-- taking @n@ characters from the end of @t@.
1088+--
1089+-- Examples:
1090+--
1091+-- > takeEnd 3 "foobar" == "bar"
1092+takeEnd :: Int -> Text -> Text
1093+takeEnd n t@(Text arr off len)
1094+ | n <= 0 = empty
1095+ | n >= len = t
1096+ | otherwise = text arr (off+i) (len-i)
1097+ where i = iterNEnd n t
1098+
1099+iterNEnd :: Int -> Text -> Int
1100+iterNEnd n t@(Text _arr _off len) = loop (len-1) n
1101+ where loop i !m
1102+ | i <= 0 = 0
1103+ | m <= 1 = i
1104+ | otherwise = loop (i+d) (m-1)
1105+ where d = reverseIter_ t i
1106+
5771107-- | /O(n)/ 'drop' @n@, applied to a 'Text', returns the suffix of the
578−-- 'Text' of length @n@, or the empty 'Text' if @n@ is greater than the
579−-- length of the 'Text'.
1108+-- 'Text' after the first @n@ characters, or the empty 'Text' if @n@
1109+-- is greater than the length of the 'Text'. Subject to fusion.
5801110drop :: Int -> Text -> Text
5811111drop n t@(Text arr off len)
5821112 | n <= 0 = t
5831113 | n >= len = empty
584− | otherwise = loop 0 0
585− where end = off + len
586− loop !i !count
587− | i >= end || count >= n = Text arr (off+i) (len-i)
588− | otherwise = loop (i+d) (count+1)
589− where d = iter_ t i
1114+ | otherwise = text arr (off+i) (len-i)
1115+ where i = iterN n t
5901116{-# INLINE [1] drop #-}
5911117
5921118{-# RULES
@@ -596,15 +1122,27 @@ drop n t@(Text arr off len)
5961122 unstream (S.drop n (stream t)) = drop n t
5971123 #-}
5981124
599−-- | /O(n)/ 'takeWhile', applied to a predicate @p@ and a 'Text', returns
600−-- the longest prefix (possibly empty) of elements that satisfy @p@.
601−-- This function is subject to array fusion.
1125+-- | /O(n)/ 'dropEnd' @n@ @t@ returns the prefix remaining after
1126+-- dropping @n@ characters from the end of @t@.
1127+--
1128+-- Examples:
1129+--
1130+-- > dropEnd 3 "foobar" == "foo"
1131+dropEnd :: Int -> Text -> Text
1132+dropEnd n t@(Text arr off len)
1133+ | n <= 0 = t
1134+ | n >= len = empty
1135+ | otherwise = text arr off (iterNEnd n t)
1136+
1137+-- | /O(n)/ 'takeWhile', applied to a predicate @p@ and a 'Text',
1138+-- returns the longest prefix (possibly empty) of elements that
1139+-- satisfy @p@. Subject to fusion.
6021140takeWhile :: (Char -> Bool) -> Text -> Text
6031141takeWhile p t@(Text arr off len) = loop 0
6041142 where loop !i | i >= len = t
6051143 | p c = loop (i+d)
606− | otherwise = textP arr off i
607− where (c,d) = iter t i
1144+ | otherwise = text arr off i
1145+ where Iter c d = iter t i
6081146{-# INLINE [1] takeWhile #-}
6091147
6101148{-# RULES
@@ -614,14 +1152,35 @@ takeWhile p t@(Text arr off len) = loop 0
6141152 unstream (S.takeWhile p (stream t)) = takeWhile p t
6151153 #-}
6161154
617−-- | /O(n)/ 'dropWhile' @p@ @xs@ returns the suffix remaining after
618−-- 'takeWhile' @p@ @xs@. This function is subject to array fusion.
1155+-- | /O(n)/ 'takeWhileEnd', applied to a predicate @p@ and a 'Text',
1156+-- returns the longest suffix (possibly empty) of elements that
1157+-- satisfy @p@. Subject to fusion.
1158+-- Examples:
1159+--
1160+-- > takeWhileEnd (=='o') "foo" == "oo"
1161+takeWhileEnd :: (Char -> Bool) -> Text -> Text
1162+takeWhileEnd p t@(Text arr off len) = loop (len-1) len
1163+ where loop !i !l | l <= 0 = t
1164+ | p c = loop (i+d) (l+d)
1165+ | otherwise = text arr (off+l) (len-l)
1166+ where (c,d) = reverseIter t i
1167+{-# INLINE [1] takeWhileEnd #-}
1168+
1169+{-# RULES
1170+"TEXT takeWhileEnd -> fused" [~1] forall p t.
1171+ takeWhileEnd p t = S.reverse (S.takeWhile p (S.reverseStream t))
1172+"TEXT takeWhileEnd -> unfused" [1] forall p t.
1173+ S.reverse (S.takeWhile p (S.reverseStream t)) = takeWhileEnd p t
1174+ #-}
1175+
1176+-- | /O(n)/ 'dropWhile' @p@ @t@ returns the suffix remaining after
1177+-- 'takeWhile' @p@ @t@. Subject to fusion.
6191178dropWhile :: (Char -> Bool) -> Text -> Text
6201179dropWhile p t@(Text arr off len) = loop 0 0
6211180 where loop !i !l | l >= len = empty
6221181 | p c = loop (i+d) (l+d)
6231182 | otherwise = Text arr (off+i) (len-l)
624− where (c,d) = iter t i
1183+ where Iter c d = iter t i
6251184{-# INLINE [1] dropWhile #-}
6261185
6271186{-# RULES
@@ -631,6 +1190,57 @@ dropWhile p t@(Text arr off len) = loop 0 0
6311190 unstream (S.dropWhile p (stream t)) = dropWhile p t
6321191 #-}
6331192
1193+-- | /O(n)/ 'dropWhileEnd' @p@ @t@ returns the prefix remaining after
1194+-- dropping characters that satisfy the predicate @p@ from the end of
1195+-- @t@. Subject to fusion.
1196+--
1197+-- Examples:
1198+--
1199+-- > dropWhileEnd (=='.') "foo..." == "foo"
1200+dropWhileEnd :: (Char -> Bool) -> Text -> Text
1201+dropWhileEnd p t@(Text arr off len) = loop (len-1) len
1202+ where loop !i !l | l <= 0 = empty
1203+ | p c = loop (i+d) (l+d)
1204+ | otherwise = Text arr off l
1205+ where (c,d) = reverseIter t i
1206+{-# INLINE [1] dropWhileEnd #-}
1207+
1208+{-# RULES
1209+"TEXT dropWhileEnd -> fused" [~1] forall p t.
1210+ dropWhileEnd p t = S.reverse (S.dropWhile p (S.reverseStream t))
1211+"TEXT dropWhileEnd -> unfused" [1] forall p t.
1212+ S.reverse (S.dropWhile p (S.reverseStream t)) = dropWhileEnd p t
1213+ #-}
1214+
1215+-- | /O(n)/ 'dropAround' @p@ @t@ returns the substring remaining after
1216+-- dropping characters that satisfy the predicate @p@ from both the
1217+-- beginning and end of @t@. Subject to fusion.
1218+dropAround :: (Char -> Bool) -> Text -> Text
1219+dropAround p = dropWhile p . dropWhileEnd p
1220+{-# INLINE [1] dropAround #-}
1221+
1222+-- | /O(n)/ Remove leading white space from a string. Equivalent to:
1223+--
1224+-- > dropWhile isSpace
1225+stripStart :: Text -> Text
1226+stripStart = dropWhile isSpace
1227+{-# INLINE [1] stripStart #-}
1228+
1229+-- | /O(n)/ Remove trailing white space from a string. Equivalent to:
1230+--
1231+-- > dropWhileEnd isSpace
1232+stripEnd :: Text -> Text
1233+stripEnd = dropWhileEnd isSpace
1234+{-# INLINE [1] stripEnd #-}
1235+
1236+-- | /O(n)/ Remove leading and trailing white space from a string.
1237+-- Equivalent to:
1238+--
1239+-- > dropAround isSpace
1240+strip :: Text -> Text
1241+strip = dropAround isSpace
1242+{-# INLINE [1] strip #-}
1243+
6341244-- | /O(n)/ 'splitAt' @n t@ returns a pair whose first element is a
6351245-- prefix of @t@ of length @n@, and whose second is the remainder of
6361246-- the string. It is equivalent to @('take' n t, 'drop' n t)@.
@@ -638,28 +1248,20 @@ splitAt :: Int -> Text -> (Text, Text)
6381248splitAt n t@(Text arr off len)
6391249 | n <= 0 = (empty, t)
6401250 | n >= len = (t, empty)
641− | otherwise = (Text arr off k, Text arr (off+k) (len-k))
642− where k = loop 0 0
643− loop !i !count
644− | i >= len || count >= n = i
645− | otherwise = loop (i+d) (count+1)
646− where d = iter_ t i
647−{-# INLINE splitAt #-}
648−
649−-- | /O(n)/ 'span', applied to a predicate @p@ and text @t@, returns a
650−-- pair whose first element is the longest prefix (possibly empty) of
651−-- @t@ of elements that satisfy @p@, and whose second is the remainder
652−-- of the list.
1251+ | otherwise = let k = iterN n t
1252+ in (text arr off k, text arr (off+k) (len-k))
1253+
1254+-- | /O(n)/ 'span', applied to a predicate @p@ and text @t@, returns
1255+-- a pair whose first element is the longest prefix (possibly empty)
1256+-- of @t@ of elements that satisfy @p@, and whose second is the
1257+-- remainder of the list.
6531258span :: (Char -> Bool) -> Text -> (Text, Text)
654−span p t@(Text arr off len) = (textP arr off k, textP arr (off+k) (len-k))
655− where k = loop 0
656− loop !i | i >= len || not (p c) = i
657− | otherwise = loop (i+d)
658− where (c,d) = iter t i
1259+span p t = case span_ p t of
1260+ (# hd,tl #) -> (hd,tl)
6591261{-# INLINE span #-}
6601262
661−-- | /O(n)/ 'break' is like 'span', but the prefix returned is over
662−-- elements that fail the predicate @p@.
1263+-- | /O(n)/ 'break' is like 'span', but the prefix returned is
1264+-- over elements that fail the predicate @p@.
6631265break :: (Char -> Bool) -> Text -> (Text, Text)
6641266break p = span (not . p)
6651267{-# INLINE break #-}
@@ -671,7 +1273,7 @@ groupBy p = loop
6711273 loop t@(Text arr off len)
6721274 | null t = []
6731275 | otherwise = text arr off n : loop (text arr (off+n) (len-n))
674− where (c,d) = iter t 0
1276+ where Iter c d = iter t 0
6751277 n = d + findAIndexOrEnd (not . p c) (Text arr (off+d) (len-d))
6761278
6771279-- | Returns the /array/ index (in units of 'Word16') at which a
@@ -681,8 +1283,8 @@ findAIndexOrEnd :: (Char -> Bool) -> Text -> Int
6811283findAIndexOrEnd q t@(Text _arr _off len) = go 0
6821284 where go !i | i >= len || q c = i
6831285 | otherwise = go (i+d)
684− where (c,d) = iter t i
685−
1286+ where Iter c d = iter t i
1287+
6861288-- | /O(n)/ Group characters in a string by equality.
6871289group :: Text -> [Text]
6881290group = groupBy (==)
@@ -698,64 +1300,93 @@ inits t@(Text arr off len) = loop 0
6981300-- first.
6991301tails :: Text -> [Text]
7001302tails t | null t = [empty]
701− | otherwise = t : tails (tail t)
1303+ | otherwise = t : tails (unsafeTail t)
7021304
703−-- | /O(n)/ Break a 'Text' into pieces separated by the 'Char'
704−-- argument, consuming the delimiter. I.e.
1305+-- $split
1306+--
1307+-- Splitting functions in this library do not perform character-wise
1308+-- copies to create substrings; they just construct new 'Text's that
1309+-- are slices of the original.
1310+
1311+-- | /O(m+n)/ Break a 'Text' into pieces separated by the first 'Text'
1312+-- argument (which cannot be empty), consuming the delimiter. An empty
1313+-- delimiter is invalid, and will cause an error to be raised.
1314+--
1315+-- Examples:
1316+--
1317+-- > splitOn "\r\n" "a\r\nb\r\nd\r\ne" == ["a","b","d","e"]
1318+-- > splitOn "aaa" "aaaXaaaXaaaXaaa" == ["","X","X","X",""]
1319+-- > splitOn "x" "x" == ["",""]
7051320--
706−-- > split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
707−-- > split 'a' "aXaXaXa" == ["","X","X","X",""]
708−-- > split 'x' "x" == ["",""]
709−--
7101321-- and
7111322--
712−-- > intercalate (singleton c) . split c == id
713−-- > split == splitWith . (==)
714−--
715−-- As for all splitting functions in this library, this function does
716−-- not copy the substrings, it just constructs new 'Text's that are
717−-- slices of the original.
718−split :: Char -> Text -> [Text]
719−split c = splitWith (==c)
720−{-# INLINE split #-}
1323+-- > intercalate s . splitOn s == id
1324+-- > splitOn (singleton c) == split (==c)
1325+--
1326+-- (Note: the string @s@ to split on above cannot be empty.)
1327+--
1328+-- In (unlikely) bad cases, this function's time complexity degrades
1329+-- towards /O(n*m)/.
1330+splitOn :: Text
1331+ -- ^ String to split on. If this string is empty, an error
1332+ -- will occur.
1333+ -> Text
1334+ -- ^ Input text.
1335+ -> [Text]
1336+splitOn pat@(Text _ _ l) src@(Text arr off len)
1337+ | l <= 0 = emptyError "splitOn"
1338+ | isSingleton pat = split (== unsafeHead pat) src
1339+ | otherwise = go 0 (indices pat src)
1340+ where
1341+ go !s (x:xs) = text arr (s+off) (x-s) : go (x+l) xs
1342+ go s _ = [text arr (s+off) (len-s)]
1343+{-# INLINE [1] splitOn #-}
1344+
1345+{-# RULES
1346+"TEXT splitOn/singleton -> split/==" [~1] forall c t.
1347+ splitOn (singleton c) t = split (==c) t
1348+ #-}
7211349
7221350-- | /O(n)/ Splits a 'Text' into components delimited by separators,
7231351-- where the predicate returns True for a separator element. The
7241352-- resulting components do not contain the separators. Two adjacent
7251353-- separators result in an empty component in the output. eg.
7261354--
727−-- > splitWith (=='a') "aabbaca" == ["","","bb","c",""]
728−-- > splitWith (=='a') [] == []
729−splitWith :: (Char -> Bool) -> Text -> [Text]
730−splitWith p = loop
731− where loop t@(Text arr off len)
732− | null t = [empty]
733− | otherwise = text arr off n : rest
734− where n = findAIndexOrEnd p t
735− m = n + iter_ t n
736− rest | n >= len = []
737− | otherwise = loop (text arr (off+m) (len-m))
738−{-# INLINE splitWith #-}
1355+-- > split (=='a') "aabbaca" == ["","","bb","c",""]
1356+-- > split (=='a') "" == [""]
1357+split :: (Char -> Bool) -> Text -> [Text]
1358+split _ t@(Text _off _arr 0) = [t]
1359+split p t = loop t
1360+ where loop s | null s' = [l]
1361+ | otherwise = l : loop (unsafeTail s')
1362+ where (# l, s' #) = span_ (not . p) s
1363+{-# INLINE split #-}
1364+
1365+-- | /O(n)/ Splits a 'Text' into components of length @k@. The last
1366+-- element may be shorter than the other chunks, depending on the
1367+-- length of the input. Examples:
1368+--
1369+-- > chunksOf 3 "foobarbaz" == ["foo","bar","baz"]
1370+-- > chunksOf 4 "haskell.org" == ["hask","ell.","org"]
1371+chunksOf :: Int -> Text -> [Text]
1372+chunksOf k = go
1373+ where
1374+ go t = case splitAt k t of
1375+ (a,b) | null a -> []
1376+ | otherwise -> a : go b
1377+{-# INLINE chunksOf #-}
7391378
7401379-- ----------------------------------------------------------------------------
7411380-- * Searching
7421381
743−-------------------------------------------------------------------------------
744−-- ** Searching by equality
745−
746−-- | /O(n)/ 'elem' is the 'Text' membership predicate.
747−elem :: Char -> Text -> Bool
748−elem c t = S.elem c (stream t)
749−{-# INLINE elem #-}
750−
7511382-------------------------------------------------------------------------------
7521383-- ** Searching with a predicate
7531384
754−-- | /O(n)/ The 'find' function takes a predicate and a 'Text',
755−-- and returns the first element in matching the predicate, or 'Nothing'
756−-- if there is no such element.
1385+-- | /O(n)/ The 'find' function takes a predicate and a 'Text', and
1386+-- returns the first element matching the predicate, or 'Nothing' if
1387+-- there is no such element.
7571388find :: (Char -> Bool) -> Text -> Maybe Char
758−find p t = S.find p (stream t)
1389+find p t = S.findBy p (stream t)
7591390{-# INLINE find #-}
7601391
7611392-- | /O(n)/ The 'partition' function takes a predicate and a 'Text',
@@ -767,90 +1398,157 @@ partition :: (Char -> Bool) -> Text -> (Text, Text)
7671398partition p t = (filter p t, filter (not . p) t)
7681399{-# INLINE partition #-}
7691400
770−-- | Break a string on a substring, returning a pair of the part of the
771−-- string prior to the match, and the rest of the string.
1401+-- | /O(n)/ 'filter', applied to a predicate and a 'Text',
1402+-- returns a 'Text' containing those characters that satisfy the
1403+-- predicate.
1404+filter :: (Char -> Bool) -> Text -> Text
1405+filter p t = unstream (S.filter p (stream t))
1406+{-# INLINE filter #-}
1407+
1408+-- | /O(n+m)/ Find the first instance of @needle@ (which must be
1409+-- non-'null') in @haystack@. The first element of the returned tuple
1410+-- is the prefix of @haystack@ before @needle@ is matched. The second
1411+-- is the remainder of @haystack@, starting with the match.
7721412--
773−-- The following relationships hold:
1413+-- Examples:
7741414--
775−-- > break (== c) l == breakSubstring (singleton c) l
1415+-- > breakOn "::" "a::b::c" ==> ("a", "::b::c")
1416+-- > breakOn "/" "foobar" ==> ("foobar", "")
7761417--
777−-- and:
1418+-- Laws:
7781419--
779−-- > findSubstring s l ==
780−-- > if null s then Just 0
781−-- > else case breakSubstring s l of
782−-- > (x,y) | null y -> Nothing
783−-- > | otherwise -> Just (length x)
1420+-- > append prefix match == haystack
1421+-- > where (prefix, match) = breakOn needle haystack
7841422--
785−-- For example, to tokenise a string, dropping delimiters:
1423+-- If you need to break a string by a substring repeatedly (e.g. you
1424+-- want to break on every instance of a substring), use 'breakOnAll'
1425+-- instead, as it has lower startup overhead.
7861426--
787−-- > tokenise x y = h : if null t then [] else tokenise x (drop (length x) t)
788−-- > where (h,t) = breakSubstring x y
1427+-- In (unlikely) bad cases, this function's time complexity degrades
1428+-- towards /O(n*m)/.
1429+breakOn :: Text -> Text -> (Text, Text)
1430+breakOn pat src@(Text arr off len)
1431+ | null pat = emptyError "breakOn"
1432+ | otherwise = case indices pat src of
1433+ [] -> (src, empty)
1434+ (x:_) -> (text arr off x, text arr (off+x) (len-x))
1435+{-# INLINE breakOn #-}
1436+
1437+-- | /O(n+m)/ Similar to 'breakOn', but searches from the end of the
1438+-- string.
7891439--
790−-- To skip to the first occurence of a string:
1440+-- The first element of the returned tuple is the prefix of @haystack@
1441+-- up to and including the last match of @needle@. The second is the
1442+-- remainder of @haystack@, following the match.
7911443--
792−-- > snd (breakSubstring x y)
1444+-- > breakOnEnd "::" "a::b::c" ==> ("a::b::", "c")
1445+breakOnEnd :: Text -> Text -> (Text, Text)
1446+breakOnEnd pat src = (reverse b, reverse a)
1447+ where (a,b) = breakOn (reverse pat) (reverse src)
1448+{-# INLINE breakOnEnd #-}
1449+
1450+-- | /O(n+m)/ Find all non-overlapping instances of @needle@ in
1451+-- @haystack@. Each element of the returned list consists of a pair:
7931452--
794−-- To take the parts of a string before a delimiter:
1453+-- * The entire string prior to the /k/th match (i.e. the prefix)
7951454--
796−-- > fst (breakSubstring x y)
1455+-- * The /k/th match, followed by the remainder of the string
7971456--
798−breakSubstring :: Text -- ^ String to search for
799− -> Text -- ^ String to search in
800− -> (Text,Text) -- ^ Head and tail of string broken at substring
801−
802−breakSubstring pat src = search 0 src
1457+-- Examples:
1458+--
1459+-- > breakOnAll "::" ""
1460+-- > ==> []
1461+-- > breakOnAll "/" "a/b/c/"
1462+-- > ==> [("a", "/b/c/"), ("a/b", "/c/"), ("a/b/c", "/")]
1463+--
1464+-- In (unlikely) bad cases, this function's time complexity degrades
1465+-- towards /O(n*m)/.
1466+--
1467+-- The @needle@ parameter may not be empty.
1468+breakOnAll :: Text -- ^ @needle@ to search for
1469+ -> Text -- ^ @haystack@ in which to search
1470+ -> [(Text, Text)]
1471+breakOnAll pat src@(Text arr off slen)
1472+ | null pat = emptyError "breakOnAll"
1473+ | otherwise = L.map step (indices pat src)
8031474 where
804− search !n !s
805− | null s = (src,empty) -- not found
806− | pat `isPrefixOf` s = (take n src,s)
807− | otherwise = search (n+1) (tail s)
808−{-# INLINE breakSubstring #-}
809−
810−-- | /O(n)/ 'filter', applied to a predicate and a 'Text',
811−-- returns a 'Text' containing those characters that satisfy the
812−-- predicate.
813−filter :: (Char -> Bool) -> Text -> Text
814−filter p t = unstream (S.filter p (stream t))
815−{-# INLINE filter #-}
816−
1475+ step x = (chunk 0 x, chunk x (slen-x))
1476+ chunk !n !l = text arr (n+off) l
1477+{-# INLINE breakOnAll #-}
8171478
8181479-------------------------------------------------------------------------------
8191480-- ** Indexing 'Text's
8201481
821−-- | /O(1)/ 'Text' index (subscript) operator, starting from 0.
1482+-- $index
1483+--
1484+-- If you think of a 'Text' value as an array of 'Char' values (which
1485+-- it is not), you run the risk of writing inefficient code.
1486+--
1487+-- An idiom that is common in some languages is to find the numeric
1488+-- offset of a character or substring, then use that number to split
1489+-- or trim the searched string. With a 'Text' value, this approach
1490+-- would require two /O(n)/ operations: one to perform the search, and
1491+-- one to operate from wherever the search ended.
1492+--
1493+-- For example, suppose you have a string that you want to split on
1494+-- the substring @\"::\"@, such as @\"foo::bar::quux\"@. Instead of
1495+-- searching for the index of @\"::\"@ and taking the substrings
1496+-- before and after that index, you would instead use @breakOnAll \"::\"@.
1497+
1498+-- | /O(n)/ 'Text' index (subscript) operator, starting from 0.
8221499index :: Text -> Int -> Char
8231500index t n = S.index (stream t) n
8241501{-# INLINE index #-}
8251502
8261503-- | /O(n)/ The 'findIndex' function takes a predicate and a 'Text'
8271504-- and returns the index of the first element in the 'Text' satisfying
828−-- the predicate. This function is subject to fusion.
1505+-- the predicate. Subject to fusion.
8291506findIndex :: (Char -> Bool) -> Text -> Maybe Int
8301507findIndex p t = S.findIndex p (stream t)
8311508{-# INLINE findIndex #-}
8321509
833−-- | The 'findIndices' function extends 'findIndex', by returning the
834−-- indices of all elements satisfying the predicate, in ascending
835−-- order. This function is subject to fusion.
836−findIndices :: (Char -> Bool) -> Text -> [Int]
837−findIndices p t = S.findIndices p (stream t)
838−{-# INLINE findIndices #-}
1510+-- | /O(n+m)/ The 'count' function returns the number of times the
1511+-- query string appears in the given 'Text'. An empty query string is
1512+-- invalid, and will cause an error to be raised.
1513+--
1514+-- In (unlikely) bad cases, this function's time complexity degrades
1515+-- towards /O(n*m)/.
1516+count :: Text -> Text -> Int
1517+count pat src
1518+ | null pat = emptyError "count"
1519+ | isSingleton pat = countChar (unsafeHead pat) src
1520+ | otherwise = L.length (indices pat src)
1521+{-# INLINE [1] count #-}
8391522
840−-- | /O(n)/ The 'elemIndex' function returns the index of the first
841−-- element in the given 'Text' which is equal to the query element, or
842−-- 'Nothing' if there is no such element. This function is subject to
843−-- fusion.
844−elemIndex :: Char -> Text -> Maybe Int
845−elemIndex c t = S.elemIndex c (stream t)
1523+{-# RULES
1524+"TEXT count/singleton -> countChar" [~1] forall c t.
1525+ count (singleton c) t = countChar c t
1526+ #-}
1527+
1528+-- | /O(n)/ The 'countChar' function returns the number of times the
1529+-- query element appears in the given 'Text'. Subject to fusion.
1530+countChar :: Char -> Text -> Int
1531+countChar c t = S.countChar c (stream t)
1532+{-# INLINE countChar #-}
8461533
8471534-------------------------------------------------------------------------------
8481535-- * Zipping
8491536
1537+-- | /O(n)/ 'zip' takes two 'Text's and returns a list of
1538+-- corresponding pairs of bytes. If one input 'Text' is short,
1539+-- excess elements of the longer 'Text' are discarded. This is
1540+-- equivalent to a pair of 'unpack' operations.
1541+zip :: Text -> Text -> [(Char,Char)]
1542+zip a b = S.unstreamList $ S.zipWith (,) (stream a) (stream b)
1543+{-# INLINE zip #-}
1544+
8501545-- | /O(n)/ 'zipWith' generalises 'zip' by zipping with the function
8511546-- given as the first argument, instead of a tupling function.
1547+-- Performs replacement on invalid scalar values.
8521548zipWith :: (Char -> Char -> Char) -> Text -> Text -> Text
853−zipWith f t1 t2 = unstream (S.zipWith f (stream t1) (stream t2))
1549+zipWith f t1 t2 = unstream (S.zipWith g (stream t1) (stream t2))
1550+ where g a b = safe (f a b)
1551+{-# INLINE zipWith #-}
8541552
8551553-- | /O(n)/ Breaks a 'Text' up into a list of words, delimited by 'Char's
8561554-- representing white space.
@@ -866,21 +1564,41 @@ words t@(Text arr off len) = loop 0 0
8661564 then loop (start+1) (start+1)
8671565 else Text arr (start+off) (n-start) : loop (n+d) (n+d)
8681566 | otherwise = loop start (n+d)
869− where (c,d) = iter t n
1567+ where Iter c d = iter t n
8701568{-# INLINE words #-}
8711569
8721570-- | /O(n)/ Breaks a 'Text' up into a list of 'Text's at
8731571-- newline 'Char's. The resulting strings do not contain newlines.
874−--
8751572lines :: Text -> [Text]
876−lines ps
877− | null ps = []
878− | otherwise = case search ps of
879− Nothing -> [ps]
880− Just n -> take n ps : lines (drop (n+1) ps)
881− where search = elemIndex '\n'
1573+lines ps | null ps = []
1574+ | otherwise = h : if null t
1575+ then []
1576+ else lines (unsafeTail t)
1577+ where (# h,t #) = span_ (/= '\n') ps
8821578{-# INLINE lines #-}
8831579
1580+{-
1581+-- | /O(n)/ Portably breaks a 'Text' up into a list of 'Text's at line
1582+-- boundaries.
1583+--
1584+-- A line boundary is considered to be either a line feed, a carriage
1585+-- return immediately followed by a line feed, or a carriage return.
1586+-- This accounts for both Unix and Windows line ending conventions,
1587+-- and for the old convention used on Mac OS 9 and earlier.
1588+lines' :: Text -> [Text]
1589+lines' ps | null ps = []
1590+ | otherwise = h : case uncons t of
1591+ Nothing -> []
1592+ Just (c,t')
1593+ | c == '\n' -> lines t'
1594+ | c == '\r' -> case uncons t' of
1595+ Just ('\n',t'') -> lines t''
1596+ _ -> lines t'
1597+ where (h,t) = span notEOL ps
1598+ notEOL c = c /= '\n' && c /= '\r'
1599+{-# INLINE lines' #-}
1600+-}
1601+
8841602-- | /O(n)/ Joins lines, after appending a terminating newline to
8851603-- each.
8861604unlines :: [Text] -> Text
@@ -893,8 +1611,7 @@ unwords = intercalate (singleton ' ')
8931611{-# INLINE unwords #-}
8941612
8951613-- | /O(n)/ The 'isPrefixOf' function takes two 'Text's and returns
896−-- 'True' iff the first is a prefix of the second. This function is
897−-- subject to fusion.
1614+-- 'True' iff the first is a prefix of the second. Subject to fusion.
8981615isPrefixOf :: Text -> Text -> Bool
8991616isPrefixOf a@(Text _ _ alen) b@(Text _ _ blen) =
9001617 alen <= blen && S.isPrefixOf (stream a) (stream b)
@@ -903,8 +1620,6 @@ isPrefixOf a@(Text _ _ alen) b@(Text _ _ blen) =
9031620{-# RULES
9041621"TEXT isPrefixOf -> fused" [~1] forall s t.
9051622 isPrefixOf s t = S.isPrefixOf (stream s) (stream t)
906−"TEXT isPrefixOf -> unfused" [1] forall s t.
907− S.isPrefixOf (stream s) (stream t) = isPrefixOf s t
9081623 #-}
9091624
9101625-- | /O(n)/ The 'isSuffixOf' function takes two 'Text's and returns
@@ -917,12 +1632,124 @@ isSuffixOf a@(Text _aarr _aoff alen) b@(Text barr boff blen) =
9171632 | otherwise = Text barr (boff+d) alen
9181633{-# INLINE isSuffixOf #-}
9191634
920−-- | /O(n)/ The 'isInfixOf' function takes two 'Text's and returns
1635+-- | /O(n+m)/ The 'isInfixOf' function takes two 'Text's and returns
9211636-- 'True' iff the first is contained, wholly and intact, anywhere
9221637-- within the second.
1638+--
1639+-- In (unlikely) bad cases, this function's time complexity degrades
1640+-- towards /O(n*m)/.
9231641isInfixOf :: Text -> Text -> Bool
924−isInfixOf needle haystack = L.any (isPrefixOf needle) (tails haystack)
925−{-# INLINE isInfixOf #-}
1642+isInfixOf needle haystack
1643+ | null needle = True
1644+ | isSingleton needle = S.elem (unsafeHead needle) . S.stream $ haystack
1645+ | otherwise = not . L.null . indices needle $ haystack
1646+{-# INLINE [1] isInfixOf #-}
9261647
927−errorEmptyList :: String -> a
928−errorEmptyList fun = error ("Data.Text." ++ fun ++ ": empty list")
1648+{-# RULES
1649+"TEXT isInfixOf/singleton -> S.elem/S.stream" [~1] forall n h.
1650+ isInfixOf (singleton n) h = S.elem n (S.stream h)
1651+ #-}
1652+
1653+-------------------------------------------------------------------------------
1654+-- * View patterns
1655+
1656+-- | /O(n)/ Return the suffix of the second string if its prefix
1657+-- matches the entire first string.
1658+--
1659+-- Examples:
1660+--
1661+-- > stripPrefix "foo" "foobar" == Just "bar"
1662+-- > stripPrefix "" "baz" == Just "baz"
1663+-- > stripPrefix "foo" "quux" == Nothing
1664+--
1665+-- This is particularly useful with the @ViewPatterns@ extension to
1666+-- GHC, as follows:
1667+--
1668+-- > {-# LANGUAGE ViewPatterns #-}
1669+-- > import Data.Text as T
1670+-- >
1671+-- > fnordLength :: Text -> Int
1672+-- > fnordLength (stripPrefix "fnord" -> Just suf) = T.length suf
1673+-- > fnordLength _ = -1
1674+stripPrefix :: Text -> Text -> Maybe Text
1675+stripPrefix p@(Text _arr _off plen) t@(Text arr off len)
1676+ | p `isPrefixOf` t = Just $! text arr (off+plen) (len-plen)
1677+ | otherwise = Nothing
1678+
1679+-- | /O(n)/ Find the longest non-empty common prefix of two strings
1680+-- and return it, along with the suffixes of each string at which they
1681+-- no longer match.
1682+--
1683+-- If the strings do not have a common prefix or either one is empty,
1684+-- this function returns 'Nothing'.
1685+--
1686+-- Examples:
1687+--
1688+-- > commonPrefixes "foobar" "fooquux" == Just ("foo","bar","quux")
1689+-- > commonPrefixes "veeble" "fetzer" == Nothing
1690+-- > commonPrefixes "" "baz" == Nothing
1691+commonPrefixes :: Text -> Text -> Maybe (Text,Text,Text)
1692+commonPrefixes t0@(Text arr0 off0 len0) t1@(Text arr1 off1 len1) = go 0 0
1693+ where
1694+ go !i !j | i < len0 && j < len1 && a == b = go (i+d0) (j+d1)
1695+ | i > 0 = Just (Text arr0 off0 i,
1696+ text arr0 (off0+i) (len0-i),
1697+ text arr1 (off1+j) (len1-j))
1698+ | otherwise = Nothing
1699+ where Iter a d0 = iter t0 i
1700+ Iter b d1 = iter t1 j
1701+
1702+-- | /O(n)/ Return the prefix of the second string if its suffix
1703+-- matches the entire first string.
1704+--
1705+-- Examples:
1706+--
1707+-- > stripSuffix "bar" "foobar" == Just "foo"
1708+-- > stripSuffix "" "baz" == Just "baz"
1709+-- > stripSuffix "foo" "quux" == Nothing
1710+--
1711+-- This is particularly useful with the @ViewPatterns@ extension to
1712+-- GHC, as follows:
1713+--
1714+-- > {-# LANGUAGE ViewPatterns #-}
1715+-- > import Data.Text as T
1716+-- >
1717+-- > quuxLength :: Text -> Int
1718+-- > quuxLength (stripSuffix "quux" -> Just pre) = T.length pre
1719+-- > quuxLength _ = -1
1720+stripSuffix :: Text -> Text -> Maybe Text
1721+stripSuffix p@(Text _arr _off plen) t@(Text arr off len)
1722+ | p `isSuffixOf` t = Just $! text arr off (len-plen)
1723+ | otherwise = Nothing
1724+
1725+-- | Add a list of non-negative numbers. Errors out on overflow.
1726+sumP :: String -> [Int] -> Int
1727+sumP fun = go 0
1728+ where go !a (x:xs)
1729+ | ax >= 0 = go ax xs
1730+ | otherwise = overflowError fun
1731+ where ax = a + x
1732+ go a _ = a
1733+
1734+emptyError :: String -> a
1735+emptyError fun = P.error $ "Data.Text." ++ fun ++ ": empty input"
1736+
1737+overflowError :: String -> a
1738+overflowError fun = P.error $ "Data.Text." ++ fun ++ ": size overflow"
1739+
1740+-- | /O(n)/ Make a distinct copy of the given string, sharing no
1741+-- storage with the original string.
1742+--
1743+-- As an example, suppose you read a large string, of which you need
1744+-- only a small portion. If you do not use 'copy', the entire original
1745+-- array will be kept alive in memory by the smaller string. Making a
1746+-- copy \"breaks the link\" to the original array, allowing it to be
1747+-- garbage collected if there are no other live references to it.
1748+copy :: Text -> Text
1749+copy (Text arr off len) = Text (A.run go) 0 len
1750+ where
1751+ go :: ST s (A.MArray s)
1752+ go = do
1753+ marr <- A.new len
1754+ A.copyI marr 0 arr off len
1755+ return marr