Skip to content

Commit

Permalink
Optimize filter
Browse files Browse the repository at this point in the history
  • Loading branch information
hasufell committed Feb 7, 2022
1 parent fd83ec2 commit 3834ed8
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion Data/ByteString/Short/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ import Prelude ( Eq(..), Ord(..), Ordering(..), Read(..), Show(..)
, Maybe(..)
, not
, snd
, fst
)

import qualified Language.Haskell.TH.Lib as TH
Expand Down Expand Up @@ -1350,7 +1351,27 @@ elem c = \sbs -> case elemIndex c sbs of Nothing -> False ; _ -> True
filter :: (Word8 -> Bool) -> ShortByteString -> ShortByteString
filter k = \sbs -> if
| null sbs -> sbs
| otherwise -> pack . List.filter k . unpack $ sbs
| otherwise -> fst $ createAndTrim (length sbs) $ \mba -> go mba (asBA sbs) (length sbs)
where
go :: forall s. MBA s -- mutable output bytestring
-> BA -- input bytestring
-> Int -- length of input bytestring
-> ST s (Int, ())
go !mba ba !l = go' 0 0
where
go' :: Int -- bytes read
-> Int -- bytes written
-> ST s (Int, ())
go' !br !bw
| br >= l = return (bw, ())
| otherwise = do
let w = indexWord8Array ba br
if k w
then do
writeWord8Array mba bw w
go' (br+1) (bw+1)
else
go' (br+1) bw

-- | /O(n)/ The 'find' function takes a predicate and a ByteString,
-- and returns the first element in matching the predicate, or 'Nothing'
Expand Down

0 comments on commit 3834ed8

Please sign in to comment.