@@ -5,6 +5,7 @@ import Control.Concurrent.STM (STM, TQueue, flushTQueue,
5
5
import Control.Concurrent.STM.TQueue (readTQueue , writeTQueue )
6
6
import Control.Monad (when )
7
7
import Data.Hashable (Hashable )
8
+ import qualified Data.HashSet
8
9
import qualified Focus
9
10
import qualified ListT as LT
10
11
import qualified StmContainers.Set as S
@@ -13,6 +14,14 @@ import StmContainers.Set (Set)
13
14
14
15
type OrderedSet a = (TQueue a , Set a )
15
16
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.
16
25
insert :: Hashable a => a -> OrderedSet a -> STM ()
17
26
insert a (que, s) = do
18
27
(_, inserted) <- S. focus (Focus. testingIfInserts $ Focus. insert () ) a s
@@ -23,14 +32,16 @@ insert a (que, s) = do
23
32
mapM_ (writeTQueue que) items
24
33
return ()
25
34
writeTQueue que a
26
- -- when que $ writeTQueue que a
27
35
28
36
newIO :: Hashable a => IO (OrderedSet a )
29
37
newIO = do
30
38
que <- newTQueueIO
31
39
s <- S. newIO
32
40
return (que, s)
33
41
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.
34
45
readQueue :: Hashable a => OrderedSet a -> STM a
35
46
readQueue rs@ (que, s) = do
36
47
f <- readTQueue que
@@ -41,8 +52,11 @@ readQueue rs@(que, s) = do
41
52
lookup :: Hashable a => a -> OrderedSet a -> STM Bool
42
53
lookup a (_, s) = S. lookup a s
43
54
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').
44
58
delete :: Hashable a => a -> OrderedSet a -> STM ()
45
59
delete a (_, s) = S. delete a s
46
60
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