@@ -5,6 +5,7 @@ import Control.Concurrent.STM (STM, TQueue, flushTQueue,
55import Control.Concurrent.STM.TQueue (readTQueue , writeTQueue )
66import Control.Monad (when )
77import Data.Hashable (Hashable )
8+ import qualified Data.HashSet
89import qualified Focus
910import qualified ListT as LT
1011import qualified StmContainers.Set as S
@@ -13,6 +14,14 @@ import StmContainers.Set (Set)
1314
1415type OrderedSet a = (TQueue a , Set a )
1516
17+ -- | Insert an element into the ordered set.
18+ -- If the element is not already present, it is added to both the queue and set.
19+ -- If the element already exists, it is moved to the end of the queue to maintain
20+ -- most-recently-inserted ordering semantics.
21+ -- It take O(n), not very good.
22+
23+ -- Alternative: could preserve original position.
24+ -- I am not sure which one is better.
1625insert :: Hashable a => a -> OrderedSet a -> STM ()
1726insert a (que, s) = do
1827 (_, inserted) <- S. focus (Focus. testingIfInserts $ Focus. insert () ) a s
@@ -23,14 +32,16 @@ insert a (que, s) = do
2332 mapM_ (writeTQueue que) items
2433 return ()
2534 writeTQueue que a
26- -- when que $ writeTQueue que a
2735
2836newIO :: Hashable a => IO (OrderedSet a )
2937newIO = do
3038 que <- newTQueueIO
3139 s <- S. newIO
3240 return (que, s)
3341
42+ -- | Read the first element from the queue.
43+ -- If an element is not in the set, it means it has been deleted,
44+ -- so we retry until we find a valid element that exists in the set.
3445readQueue :: Hashable a => OrderedSet a -> STM a
3546readQueue rs@ (que, s) = do
3647 f <- readTQueue que
@@ -41,8 +52,11 @@ readQueue rs@(que, s) = do
4152lookup :: Hashable a => a -> OrderedSet a -> STM Bool
4253lookup a (_, s) = S. lookup a s
4354
55+ -- | Delete an element from the set.
56+ -- The queue is not modified directly; stale entries are filtered out lazily
57+ -- during reading operations (see 'readQueue').
4458delete :: Hashable a => a -> OrderedSet a -> STM ()
4559delete a (_, s) = S. delete a s
4660
47- toUnOrderedList :: Hashable a => OrderedSet a -> STM [ a ]
48- toUnOrderedList (_, s) = LT. toList $ S. listT s
61+ toHashSet :: Hashable a => OrderedSet a -> Data. HashSet a
62+ toHashSet (_, s) = TreeSet. fromList $ LT. toList $ S. listT s
0 commit comments