module Graphics.Vty.Input.Classify.Parse
( Parser
, runParser
, failParse
, readInt
, readChar
, expectChar
)
where
import Graphics.Vty.Input.Events
import Graphics.Vty.Input.Classify.Types
import Control.Monad.Trans.Maybe
import Control.Monad.State
import qualified Data.ByteString.Char8 as BS8
import Data.ByteString.Char8 (ByteString)
type Parser a = MaybeT (State ByteString) a
runParser :: ByteString -> Parser Event -> KClass
runParser :: ByteString -> Parser Event -> KClass
runParser ByteString
s Parser Event
parser =
case forall s a. State s a -> s -> (a, s)
runState (forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT Parser Event
parser) ByteString
s of
(Maybe Event
Nothing, ByteString
_) -> KClass
Invalid
(Just Event
e, ByteString
remaining) -> Event -> ByteString -> KClass
Valid Event
e ByteString
remaining
failParse :: Parser a
failParse :: forall a. Parser a
failParse = forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"invalid parse"
readInt :: Parser Int
readInt :: Parser Int
readInt = do
String
s <- ByteString -> String
BS8.unpack forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall s (m :: * -> *). MonadState s m => m s
get
case (forall a. Read a => ReadS a
reads :: ReadS Int) String
s of
[(Int
i, String
rest)] -> forall s (m :: * -> *). MonadState s m => s -> m ()
put (String -> ByteString
BS8.pack String
rest) forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> forall (m :: * -> *) a. Monad m => a -> m a
return Int
i
[(Int, String)]
_ -> forall a. Parser a
failParse
readChar :: Parser Char
readChar :: Parser Char
readChar = do
ByteString
s <- forall s (m :: * -> *). MonadState s m => m s
get
case ByteString -> Maybe (Char, ByteString)
BS8.uncons ByteString
s of
Just (Char
c,ByteString
rest) -> forall s (m :: * -> *). MonadState s m => s -> m ()
put ByteString
rest forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> forall (m :: * -> *) a. Monad m => a -> m a
return Char
c
Maybe (Char, ByteString)
Nothing -> forall a. Parser a
failParse
expectChar :: Char -> Parser ()
expectChar :: Char -> Parser ()
expectChar Char
c = do
Char
c' <- Parser Char
readChar
if Char
c' forall a. Eq a => a -> a -> Bool
== Char
c then forall (m :: * -> *) a. Monad m => a -> m a
return () else forall a. Parser a
failParse