aboutsummaryrefslogtreecommitdiff
path: root/Utility/TSet.hs
blob: c5ee22c8952f4b70966b0dc88a88ac2a00740a35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
{- Transactional sets
 -
 - Copyright 2012, 2013 Joey Hess <joey@kitenet.net>
 -}

module Utility.TSet where

import Common

import Control.Concurrent.STM

type TSet = TChan

newTSet :: STM (TSet a)
newTSet = newTChan

{- Gets the contents of the TSet. Blocks until at least one item is
 - present. -}
getTSet :: TSet a -> STM [a]
getTSet tset = do
	c <- readTChan tset
	l <- readTSet tset
	return $ c:l

{- Gets anything currently in the TSet, without blocking. -}
readTSet :: TSet a -> STM [a]
readTSet tset = go []
  where
	go l = do
		v <- tryReadTChan tset
		case v of
			Nothing -> return l
			Just c -> go (c:l)

{- Puts items into a TSet. -}
putTSet :: TSet a -> [a] -> STM ()
putTSet tset vs = mapM_ (writeTChan tset) vs

{- Put a single item into a TSet. -}
putTSet1 :: TSet a -> a -> STM ()
putTSet1 tset v = void $ writeTChan tset v