Skip to content

Commit

Permalink
Make deserialiseFromRawBytesBase16 return 'Either String a'
Browse files Browse the repository at this point in the history
  • Loading branch information
newhoggy committed Mar 21, 2023
1 parent 7f52046 commit e3f2d9e
Showing 1 changed file with 7 additions and 9 deletions.
16 changes: 7 additions & 9 deletions cardano-api/src/Cardano/Api/SerialiseUsing.hs
Expand Up @@ -61,15 +61,15 @@ instance SerialiseAsRawBytes a => Show (UsingRawBytesHex a) where
show (UsingRawBytesHex x) = show (serialiseToRawBytesHex x)

instance SerialiseAsRawBytes a => IsString (UsingRawBytesHex a) where
fromString = either error id . deserialiseFromRawBytesBase16 . BSC.pack
fromString = either error id . fmap UsingRawBytesHex . deserialiseFromRawBytesBase16 . BSC.pack

instance SerialiseAsRawBytes a => ToJSON (UsingRawBytesHex a) where
toJSON (UsingRawBytesHex x) = toJSON (serialiseToRawBytesHexText x)

instance SerialiseAsRawBytes a => FromJSON (UsingRawBytesHex a) where
parseJSON =
Aeson.withText tname $
either fail pure . deserialiseFromRawBytesBase16 . Text.encodeUtf8
either fail pure . fmap UsingRawBytesHex . deserialiseFromRawBytesBase16 . Text.encodeUtf8
where
tname = (tyConName . typeRepTyCon . typeRep) (Proxy :: Proxy a)

Expand All @@ -78,19 +78,17 @@ instance SerialiseAsRawBytes a => ToJSONKey (UsingRawBytesHex a) where
Aeson.toJSONKeyText $ \(UsingRawBytesHex x) -> serialiseToRawBytesHexText x

instance SerialiseAsRawBytes a => FromJSONKey (UsingRawBytesHex a) where

fromJSONKey =
Aeson.FromJSONKeyTextParser $
either fail pure . deserialiseFromRawBytesBase16 . Text.encodeUtf8
either fail pure . fmap UsingRawBytesHex . deserialiseFromRawBytesBase16 . Text.encodeUtf8

deserialiseFromRawBytesBase16 ::
SerialiseAsRawBytes a => ByteString -> Either String (UsingRawBytesHex a)
deserialiseFromRawBytesBase16 :: SerialiseAsRawBytes a => ByteString -> Either String a
deserialiseFromRawBytesBase16 str =
case Base16.decode str of
Right raw -> case deserialiseFromRawBytes ttoken raw of
Right x -> Right (UsingRawBytesHex x)
Left (SerialiseAsRawBytesError msg) -> Left ("cannot deserialise " ++ show str ++ ". The error was: " <> msg)
Left msg -> Left ("invalid hex " ++ show str ++ ", " ++ msg)
Right a -> Right a
Left (SerialiseAsRawBytesError msg) -> Left ("cannot deserialise " <> show str <> ". The error was: " <> msg)
Left msg -> Left ("invalid hex " <> show str <> ", " <> msg)
where
ttoken = proxyToAsType (Proxy :: Proxy a)

Expand Down

0 comments on commit e3f2d9e

Please sign in to comment.