on 09cd408 help sign in
text/tests/Tests/SlowFunctions.hs
39 lines 1.3 kB history raw
1{-# LANGUAGE BangPatterns #-}
2module Tests.SlowFunctions
3 (
4 indices
5 , splitOn
6 ) where
8import qualified Data.Text as T
9import Data.Text.Internal (Text(..))
10import Data.Text.Unsafe (iter_, unsafeHead, unsafeTail)
12indices :: T.Text -- ^ Substring to search for (@needle@)
13 -> T.Text -- ^ Text to search in (@haystack@)
14 -> [Int]
15indices needle@(Text _narr _noff nlen) haystack@(Text harr hoff hlen)
16 | T.null needle = []
17 | otherwise = scan 0
18 where
19 scan i | i >= hlen = []
20 | needle `T.isPrefixOf` t = i : scan (i+nlen)
21 | otherwise = scan (i+d)
22 where t = Text harr (hoff+i) (hlen-i)
23 d = iter_ haystack i
25splitOn :: T.Text -- ^ Text to split on
26 -> T.Text -- ^ Input text
27 -> [T.Text]
28splitOn pat src0
29 | T.null pat = error "splitOn: empty"
30 | l == 1 = T.split (== (unsafeHead pat)) src0
31 | otherwise = go src0
32 where
33 l = T.length pat
34 go src = search 0 src
35 where
36 search !n !s
37 | T.null s = [src] -- not found
38 | pat `T.isPrefixOf` s = T.take n src : go (T.drop l s)
39 | otherwise = search (n+1) (unsafeTail s)