module PState (
putState,
getState,
updateState
) where
import System.IO
import Data.Maybe
import Data.Binary
import Control.Monad
import System.FilePath
import System.Directory
putState :: Binary a => String -> String -> a -> IO (Maybe String)
putState n k v = do
let file = foldr1 combine ["State",n,(k++".st")]
dir = takeDirectory file
b <- doesFileExist file
if b then
return (Just $ "State already exists: " ++ file)
else do
unlessM (doesDirectoryExist dir) (createDirectory dir)
encodeFile file v
return Nothing
getState :: Binary a => String -> String -> IO (Either String a)
getState n k = do
let file = foldr1 combine ["State",n,(k++".st")]
b <- doesFileExist file
if b == False then
return $ Left ("State doesn't exist: " ++ file)
else decodeFile file >>= return . Right
updateState :: Binary a => String -> String -> a -> IO (Maybe String)
updateState n k v = do
let file = foldr1 combine ["State",n,(k++".st")]
b <- doesFileExist file
if b == False then
return (Just $ "State doesn't exist: " ++ file)
else encodeFile file v >> return Nothing
-- convenience
create f = (openFile f WriteMode) >>= hClose
unlessM b f = b >>= \x -> unless x f