diff --git a/src-test/Tests.hs b/src-test/Tests.hs index e36b7ef..8317e99 100644 --- a/src-test/Tests.hs +++ b/src-test/Tests.hs @@ -78,6 +78,7 @@ qcProps = testGroup "Properties" , QC.testProperty "reverse" $ \t -> IUT.reverse (IUT.fromText t) == IUT.fromText (T.reverse t) , QC.testProperty "filter" $ \p t -> IUT.filter p (IUT.fromText t) == IUT.fromText (T.filter p t) , QC.testProperty "replicate" $ \n t -> IUT.replicate n (IUT.fromText t) == IUT.fromText (T.replicate n t) + , QC.testProperty "dropAround" $ \p t -> IUT.dropAround p (IUT.fromText t) == IUT.fromText (T.dropAround p t) , QC.testProperty "splitAtEnd" $ \t -> let t' = IUT.fromText t diff --git a/src/Data/Text/Short.hs b/src/Data/Text/Short.hs index 9f2ddd6..6e3e90a 100644 --- a/src/Data/Text/Short.hs +++ b/src/Data/Text/Short.hs @@ -66,6 +66,8 @@ module Data.Text.Short , dropWhile , dropWhileEnd + , dropAround + -- ** Pair-valued functions , splitAt , splitAtEnd diff --git a/src/Data/Text/Short/Internal.hs b/src/Data/Text/Short/Internal.hs index 9f5008e..fdd9448 100644 --- a/src/Data/Text/Short/Internal.hs +++ b/src/Data/Text/Short/Internal.hs @@ -52,9 +52,11 @@ module Data.Text.Short.Internal , intersperse , intercalate , reverse - , filter , replicate + , filter + , dropAround + -- * Conversions -- ** 'Char' , singleton @@ -947,8 +949,8 @@ filter p t t1sz <- go mba ofs2 ofs1 return t1sz where - mofs1 = findOfs (not . p) t 0 -- first non-accepted Char - mofs2 = findOfs p t (fromMaybe 0 mofs1) -- first accepted Char + mofs1 = findOfs (not . p) t (B 0) -- first non-accepted Char + mofs2 = findOfs p t (fromMaybe (B 0) mofs1) -- first accepted Char t0sz = toB t @@ -962,6 +964,28 @@ filter p t go mba (t0ofs+cpsz) (t1ofs+cpsz) else go mba (t0ofs+cpsz) t1ofs -- skip code-point +-- | \(\mathcal{O}(n)\) Strip characters from the beginning end and of 'ShortText' which satisfy given predicate. +-- +-- >>> dropAround (== ' ') " white space " +-- "white space" +-- +-- >>> dropAround (> 'a') "bcdefghi" +-- "" +-- +-- @since 0.1.2 +dropAround :: (Char -> Bool) -> ShortText -> ShortText +dropAround p t0 = case (mofs1,mofs2) of + (Nothing,_) -> mempty + (Just ofs1,Just ofs2) + | ofs1 == 0, ofs2 == t0sz -> t0 + | ofs1 < ofs2 -> create (ofs2-ofs1) $ \mba -> do + copyByteArray t0 ofs1 mba (B 0) (ofs2-ofs1) + (_,_) -> error "dropAround: the impossible happened" + where + mofs1 = findOfs (not . p) t0 (B 0) + mofs2 = findOfsRev (not . p) t0 t0sz + t0sz = toB t0 + ---------------------------------------------------------------------------- -- | Construct a new 'ShortText' from an existing one by slicing