Skip to content

Commit

Permalink
implement dropAround
Browse files Browse the repository at this point in the history
  • Loading branch information
hvr committed Jan 22, 2018
1 parent a44695d commit f0708ba
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
1 change: 1 addition & 0 deletions src-test/Tests.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/Data/Text/Short.hs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ module Data.Text.Short
, dropWhile
, dropWhileEnd

, dropAround

-- ** Pair-valued functions
, splitAt
, splitAtEnd
Expand Down
30 changes: 27 additions & 3 deletions src/Data/Text/Short/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ module Data.Text.Short.Internal
, intersperse
, intercalate
, reverse
, filter
, replicate

, filter
, dropAround

-- * Conversions
-- ** 'Char'
, singleton
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down

0 comments on commit f0708ba

Please sign in to comment.