module Net.Utils where
import Net.Concurrent
import Net.Bits
import Data.List(unfoldr)
import Data.Array.IArray
class Functor f => Container f where contents :: f a -> a
replace x b = fmap (const b) x
emap f p= fmap (replace p) (f (contents p))
emap2 f = emap (emap f)
lift p = fmap (replace p) (contents p)
lift2 p = lift (fmap lift p)
doReq reqChan req =
do ans <- newEmptyMVar
writeChan reqChan (req (putMVar ans))
takeMVar ans
foldlArray :: (IArray arr elem, Ix ix, Enum ix)
=> arr ix elem -> (elem -> a -> a) -> a -> a
foldlArray arr add zero = loop min zero
where
(min,max) = bounds arr
loop ix tot
| ix <= max = loop (succ ix) (add (arr ! ix) tot)
| otherwise = tot
arraySize a = max min + 1
where
(min,max) = bounds a
checksum :: [Word16] -> Word16
checksum ws = let total = sum (map fromIntegral ws) :: Word32
in complement (fromIntegral total + fromIntegral (total `shiftR` 16))
pairs :: a -> [a] -> [[a]]
pairs a = unfoldr mk
where
mk (x:y:zs) = Just ([x,y],zs)
mk [x] = Just ([x,a],[])
mk [] = Nothing
bytes_to_words_big :: [Word8] -> [Word16]
bytes_to_words_big = map catBits . pairs 0
bytes_to_words_lil :: [Word8] -> [Word16]
bytes_to_words_lil = map (catBits . reverse) . pairs 0
words_to_bytes_big :: [Word16] -> [Word8]
words_to_bytes_big ws = concat [ [w .!. 1, w .!. 0] | w <- ws ]
words_to_bytes_lil :: [Word16] -> [Word8]
words_to_bytes_lil ws = concat [ [w .!. 0, w .!. 1] | w <- ws ]