From cae572e800b1aac6eeace26b4afe9ec7425abd0f Mon Sep 17 00:00:00 2001 From: Hans-Peter Deifel <hpd@hpdeifel.de> Date: Sun, 9 Sep 2018 08:55:38 +0200 Subject: [PATCH] Add `toList` and `clear` functions to BlockQueue These are both useful for testing. --- src/Data/BlockQueue.hs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/Data/BlockQueue.hs b/src/Data/BlockQueue.hs index a60ed88..2d7c21a 100644 --- a/src/Data/BlockQueue.hs +++ b/src/Data/BlockQueue.hs @@ -15,11 +15,14 @@ module Data.BlockQueue , enqueue , dequeue , elem + , clear + , toList ) where import Prelude hiding (null, elem) import Control.Monad.ST +import qualified Data.Foldable as Foldable import Data.Primitive.MutVar import Data.Sequence (Seq) @@ -68,7 +71,7 @@ enqueue q block = unlessM (elem block q) $ do modifyMutVar (q^.queue) $ \s -> s Seq.|> block UnboxedV.write (q^.presence) (fromBlock block) True --- | Read and delete the first element in the queue +-- | Read and delete the first element in the queue. -- -- Returns 'Nothing' and doesn't modify the queue if it was empty. -- @@ -81,8 +84,23 @@ dequeue q = Seq.viewl <$> readMutVar (q^.queue) >>= \case writeMutVar (q^.queue) rest return (Just x) --- | Tests whether an element is in the queue +-- | Tests whether an element is in the queue. -- -- Runtime: O(1) elem :: Block -> BlockQueue s -> ST s Bool elem (Block block) !q = UnboxedV.read (q^.presence) block + +-- | Removes all items from the queue. +-- +-- Runtime: O(max size of queue) +clear :: BlockQueue s -> ST s () +clear q = do + writeMutVar (q^.queue) Seq.empty + UnboxedV.set (q^.presence) False + +-- | Return a list of currently queued items in the order in which they were +-- added to the queue. +-- +-- Runtime: O(n) +toList :: BlockQueue s -> ST s [Block] +toList q = Foldable.toList <$> readMutVar (q^.queue) -- GitLab