Commit b24d4c02 authored by Hans-Peter Deifel's avatar Hans-Peter Deifel
Browse files

Add `delete` function to BlockQueue

parent 3e14dd33
......@@ -15,6 +15,7 @@ module Data.BlockQueue
, enqueue
, dequeue
, elem
, delete
, clear
, toList
) where
......@@ -104,3 +105,20 @@ clear q = do
-- Runtime: O(n)
toList :: BlockQueue s -> ST s [Block]
toList q = Foldable.toList <$> readMutVar (q^.queue)
-- | Delete the given block from the queue if it is queued or do nothing
-- otherwise.
--
-- The block id must be smaller than the maximum size of the queue.
--
-- Runtime: O(current size of queue)
delete :: Block -> BlockQueue s -> ST s ()
delete (Block b) q = do
UnboxedV.write (q ^. presence) b False
modifyMutVar (q ^. queue) deleteFromSeq
where
deleteFromSeq s = case Seq.elemIndexL (Block b) s of
Nothing -> s
Just idx -> Seq.deleteAt idx s
......@@ -8,7 +8,7 @@ import Test.Hspec
import Test.QuickCheck
import Control.Monad.ST
import Data.List (delete)
import qualified Data.List as List (delete)
import Data.Vector (Vector)
import qualified Data.Vector as V
......@@ -33,28 +33,28 @@ emptySpec = describe "empty" $ do
enqueueSpec :: Spec
enqueueSpec = describe "enqueue" $ do
it "makes an empty queue non-empty" $
runST (empty 2 >>= \q -> enqueue q 0 >> null q) `shouldBe` False
it "is inverse to enqueue" $
let enqdeq a b = do
q <- empty 10
enqueue q a
enqueue q b
(,) <$> dequeue q <*> dequeue q
in
property $ forAll (elements [0..9]) $ \a -> forAll (elements (delete a [0..9])) $ \b ->
runST (enqdeq a b) === (Just a, Just b)
it "doesn't insert blocks twice" $
let enqtwice = do
q <- empty 5
enqueue q 0
enqueue q 0
Just 0 <- dequeue q
null q
in
runST enqtwice `shouldBe` True
it "makes an empty queue non-empty"
$ runST (empty 2 >>= \q -> enqueue q 0 >> null q)
`shouldBe` False
it "is inverse to enqueue"
$ let enqdeq a b = do
q <- empty 10
enqueue q a
enqueue q b
(,) <$> dequeue q <*> dequeue q
in property $ forAll (elements [0 .. 9]) $ \a ->
forAll (elements (List.delete a [0 .. 9]))
$ \b -> runST (enqdeq a b) === (Just a, Just b)
it "doesn't insert blocks twice"
$ let enqtwice = do
q <- empty 5
enqueue q 0
enqueue q 0
Just 0 <- dequeue q
null q
in runST enqtwice `shouldBe` True
instance Arbitrary a => Arbitrary (Vector a) where
arbitrary = V.fromList <$> arbitrary
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment