author | unc0rr |
Sun, 27 Apr 2008 16:12:20 +0000 | |
changeset 886 | c712272b2770 |
parent 852 | f756a1d3324c |
child 889 | 3bf9dc791f45 |
permissions | -rw-r--r-- |
849 | 1 |
module Miscutils where |
2 |
||
3 |
import IO |
|
4 |
import System.IO |
|
5 |
import Control.Concurrent |
|
6 |
import Control.Concurrent.STM |
|
7 |
import Control.Exception (finally) |
|
8 |
||
851 | 9 |
data ClientInfo = |
10 |
ClientInfo |
|
11 |
{ |
|
12 |
handle :: Handle, |
|
13 |
nick :: String, |
|
14 |
room :: String, |
|
15 |
isMaster :: Bool |
|
16 |
} |
|
17 |
||
18 |
data RoomInfo = |
|
19 |
RoomInfo |
|
20 |
{ |
|
21 |
name :: String, |
|
22 |
password :: String |
|
23 |
} |
|
24 |
||
25 |
||
849 | 26 |
sendMsg :: Handle -> String -> IO() |
27 |
sendMsg clientHandle str = finally (return ()) (hPutStrLn clientHandle str >> hFlush clientHandle) -- catch exception when client tries to send to other |
|
28 |
||
29 |
sendAll :: [Handle] -> String -> IO[()] |
|
30 |
sendAll clientsList str = mapM (\x -> sendMsg x str) clientsList |
|
31 |
||
32 |
sendOthers :: [Handle] -> Handle -> String -> IO[()] |
|
33 |
sendOthers clientsList clientHandle str = sendAll (filter (/= clientHandle) clientsList) str |
|
34 |
||
35 |
extractCmd :: String -> (String, [String]) |
|
36 |
extractCmd str = if ws == [] then ("", []) else (head ws, tail ws) |
|
37 |
where ws = words str |
|
38 |
||
39 |
manipState :: TVar[a] -> ([a] -> [a]) -> IO() |
|
40 |
manipState state op = |
|
41 |
atomically $ do |
|
42 |
ls <- readTVar state |
|
43 |
writeTVar state $ op ls |
|
44 |
||
852
f756a1d3324c
Handle the case when the room is already created by someone else
unc0rr
parents:
851
diff
changeset
|
45 |
manipState2 :: TVar[ClientInfo] -> TVar[RoomInfo] -> ([ClientInfo] -> [RoomInfo] -> ([ClientInfo], [RoomInfo], Bool)) -> IO Bool |
851 | 46 |
manipState2 state1 state2 op = |
47 |
atomically $ do |
|
48 |
ls1 <- readTVar state1 |
|
49 |
ls2 <- readTVar state2 |
|
852
f756a1d3324c
Handle the case when the room is already created by someone else
unc0rr
parents:
851
diff
changeset
|
50 |
let (ol1, ol2, res) = op ls1 ls2 |
851 | 51 |
writeTVar state1 ol1 |
52 |
writeTVar state2 ol2 |
|
852
f756a1d3324c
Handle the case when the room is already created by someone else
unc0rr
parents:
851
diff
changeset
|
53 |
return res |
851 | 54 |