Skip to content

Commit 6f06b72

Browse files
committed
WIP: Tests.Properties.Substrings: add genOrdSubseq
1 parent b363387 commit 6f06b72

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

tests/Tests/Properties/Substrings.hs

+43
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import qualified Data.Text.Internal.Fusion.Common as S
1919
import qualified Data.Text.Internal.Lazy.Fusion as SL
2020
import qualified Data.Text.Lazy as TL
2121
import qualified Tests.SlowFunctions as Slow
22+
import Control.Monad (replicateM)
23+
import Data.List (nub, sort)
2224

2325
s_take n = L.take n `eqP` (unpackS . S.take n)
2426
s_take_s (Small n) = L.take n `eqP` (unpackS . S.unstream . S.take n)
@@ -226,6 +228,47 @@ tl_isSuffixOf s = L.isSuffixOf s`eqP` TL.isSuffixOf (packS s)
226228
t_isInfixOf s = L.isInfixOf s `eqP` T.isInfixOf (packS s)
227229
tl_isInfixOf s = L.isInfixOf s `eqP` TL.isInfixOf (packS s)
228230

231+
-- | Generator for substrings that keeps the element order.
232+
-- Aka: "1234567890" -> "245680"
233+
genOrdSubseq :: T.Text -> Gen T.Text
234+
genOrdSubseq txt =
235+
T.pack . transform <$> genTransformMap
236+
where
237+
238+
pickN :: Gen Int
239+
pickN =
240+
choose (0, T.length txt)
241+
242+
pickNs :: Gen [Int]
243+
pickNs =
244+
fmap (sort . nub) $ (`replicateM` pickN) =<< pickN
245+
246+
growInst :: [Bool] -> Int -> [Bool]
247+
growInst ls n =
248+
ls
249+
<> take (length ls - pred n) [True ..]
250+
<> [False]
251+
252+
mkTransformInst :: [Bool] -> [Int] -> [Bool]
253+
mkTransformInst bls [] =
254+
bls
255+
<> take (T.length txt - length bls) [True ..]
256+
mkTransformInst bls (i:is) =
257+
mkTransformInst
258+
(growInst bls i)
259+
is
260+
261+
mkTransformMap :: [a] -> [Int] -> [(a, Bool)]
262+
mkTransformMap ls ixs =
263+
zip ls (mkTransformInst mempty ixs)
264+
265+
genTransformMap :: (Gen [(Char, Bool)])
266+
genTransformMap = fmap (mkTransformMap $ T.unpack txt) pickNs
267+
268+
transform :: [(Char, Bool)] -> [Char]
269+
transform =
270+
foldr (\ (c, b) as -> as <> if b then [c] else mempty) mempty
271+
229272
t_stripPrefix s = (fmap packS . L.stripPrefix s) `eqP` T.stripPrefix (packS s)
230273
tl_stripPrefix s = (fmap packS . L.stripPrefix s) `eqP` TL.stripPrefix (packS s)
231274

0 commit comments

Comments
 (0)