From 19777d1c6f0ecbe63ac167c3d494cc980cc21d3a Mon Sep 17 00:00:00 2001 From: Joey Hess Date: Wed, 9 Dec 2020 15:28:11 -0400 Subject: [PATCH] minor improvements Adding new instance for Integer, and some parsers for more parameters. The conversion of readish to readMaybe is done because a serialized exit code cannot contain additional text after the number. --- Utility/SimpleProtocol.hs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/Utility/SimpleProtocol.hs b/Utility/SimpleProtocol.hs index e3b3a5b7ba..acd2439290 100644 --- a/Utility/SimpleProtocol.hs +++ b/Utility/SimpleProtocol.hs @@ -1,6 +1,6 @@ {- Simple line-based protocols. - - - Copyright 2013-2016 Joey Hess + - Copyright 2013-2020 Joey Hess - - License: BSD-2-clause -} @@ -19,12 +19,15 @@ module Utility.SimpleProtocol ( parse1, parse2, parse3, + parse4, + parse5, dupIoHandles, getProtocolLine, ) where import Data.Char import GHC.IO.Handle +import Text.Read import Common @@ -52,11 +55,15 @@ instance Serializable [Char] where serialize = id deserialize = Just +instance Serializable Integer where + serialize = show + deserialize = readMaybe + instance Serializable ExitCode where serialize ExitSuccess = "0" serialize (ExitFailure n) = show n deserialize "0" = Just ExitSuccess - deserialize s = ExitFailure <$> readish s + deserialize s = ExitFailure <$> readMaybe s {- Parsing the parameters of messages. Using the right parseN ensures - that the string is split into exactly the requested number of words, @@ -86,6 +93,21 @@ parse3 mk s = mk <$> deserialize p1 <*> deserialize p2 <*> deserialize p3 (p1, rest) = splitWord s (p2, p3) = splitWord rest +parse4 :: (Serializable p1, Serializable p2, Serializable p3, Serializable p4) => (p1 -> p2 -> p3 -> p4 -> a) -> Parser a +parse4 mk s = mk <$> deserialize p1 <*> deserialize p2 <*> deserialize p3 <*> deserialize p4 + where + (p1, rest) = splitWord s + (p2, rest') = splitWord rest + (p3, p4) = splitWord rest' + +parse5 :: (Serializable p1, Serializable p2, Serializable p3, Serializable p4, Serializable p5) => (p1 -> p2 -> p3 -> p4 -> p5 -> a) -> Parser a +parse5 mk s = mk <$> deserialize p1 <*> deserialize p2 <*> deserialize p3 <*> deserialize p4 <*> deserialize p5 + where + (p1, rest) = splitWord s + (p2, rest') = splitWord rest + (p3, rest'') = splitWord rest' + (p4, p5) = splitWord rest'' + splitWord :: String -> (String, String) splitWord = separate isSpace