Skip to content

Commit d4eaecc

Browse files
committed
Expose encoders/decoders for Maybe
1 parent 1121579 commit d4eaecc

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

binary/src/Cardano/Binary/FromCBOR.hs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ module Cardano.Binary.FromCBOR
1313
, enforceSize
1414
, matchSize
1515
, module D
16+
, fromCBORMaybe
1617
)
1718
where
1819

@@ -298,15 +299,15 @@ instance FromCBOR a => FromCBOR (NonEmpty a) where
298299
Just xs -> Right xs
299300

300301
instance FromCBOR a => FromCBOR (Maybe a) where
301-
fromCBOR = decodeMaybe fromCBOR
302+
fromCBOR = fromCBORMaybe fromCBOR
302303

303-
decodeMaybe :: D.Decoder s a -> D.Decoder s (Maybe a)
304-
decodeMaybe decoder = do
304+
fromCBORMaybe :: D.Decoder s a -> D.Decoder s (Maybe a)
305+
fromCBORMaybe fromCBORA = do
305306
n <- D.decodeListLen
306307
case n of
307308
0 -> return Nothing
308309
1 -> do
309-
!x <- decoder
310+
!x <- fromCBORA
310311
return (Just x)
311312
_ -> cborError $ DecoderErrorUnknownTag "Maybe" (fromIntegral n)
312313

binary/src/Cardano/Binary/ToCBOR.hs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ module Cardano.Binary.ToCBOR
1414
( ToCBOR(..)
1515
, withWordSize
1616
, module E
17+
, toCBORMaybe
1718

1819
-- * Size of expressions
1920
, Range(..)
@@ -584,12 +585,15 @@ instance ToCBOR a => ToCBOR (NonEmpty a) where
584585
encodedSizeExpr size _ = size (Proxy @[a]) -- MN TODO make 0 count impossible
585586

586587
instance ToCBOR a => ToCBOR (Maybe a) where
587-
toCBOR Nothing = E.encodeListLen 0
588-
toCBOR (Just x) = E.encodeListLen 1 <> toCBOR x
588+
toCBOR = toCBORMaybe toCBOR
589589

590590
encodedSizeExpr size _ =
591591
szCases [Case "Nothing" 1, Case "Just" (1 + size (Proxy @a))]
592592

593+
toCBORMaybe :: (a -> Encoding) -> Maybe a -> Encoding
594+
toCBORMaybe encodeA = \case
595+
Nothing -> E.encodeListLen 0
596+
Just x -> E.encodeListLen 1 <> encodeA x
593597

594598
encodeContainerSkel
595599
:: (Word -> E.Encoding)

0 commit comments

Comments
 (0)