Codec for text values with custom error messages for parsing.
Example:
We have the following type that represents the image format:
data Format
= Jpeg
| Png
| Gif
deriving (Show, Read, Enum)
But we want to be able to decode and encode this data type through the custom text representation, that can be formilised in the following functions:
showFormat :: Format -> Text
showFormat = case
Jpeg -> ".jpeg"
Png -> ".png"
Gif -> ".gif"
parseFormat :: Text -> Either Text Format
parseFormat = case
".jpeg" -> Right Jpeg
".png" -> Right Png
".gif" -> Right Gif
other -> Left $ "Unsupported format: " <> other
To write the codec for Format data type using the above rules we can use
textBy combinator:
formatCodec :: Key -> TomlCodec Format
formatCodec = textBy showFormat parseFormat
And now with the formatCodec "foo" we can have the following line in our
TOML perfectly encoded:
foo = ".gif"
But the foo = "jif" will lead to the following error:
tomland decode error: Unsupported format: jif