hydra-prelude
Safe HaskellSafe-Inferred
LanguageGHC2021

Hydra.CBOR.Generic

Description

Generic derivation of ToCBOR / FromCBOR instances in the constructor-name-tagged format used for hydra-node persistence and API messages.

The encoding of a value is the constructor name as a CBOR text string, followed by the encodings of the constructor fields in declaration order, concatenated without any list framing:

toCBOR (ConstructorName :: Text) <> toCBOR field1 <> toCBOR field2 <> ...

Every constructor is tagged, including the single constructor of records and newtypes. Tagging by name (instead of by declaration index like the serialise package) means adding or reordering constructors does not change the encoding of existing data; removing or renaming a constructor, or changing the order or type of its fields, does and requires a migration of persisted data.

Since the field encodings come from the data type declaration, the declaration itself becomes the wire format: reordering record fields is a format change that the type checker will not flag. Golden tests (see CBORSpec in hydra-node) are the guard against that.

Decoding fails with "<tag>" is not a proper CBOR-encoded <TypeName> when the decoded tag matches no constructor.

Synopsis

Documentation

genericToCBOR :: (Generic a, GToCBOR (Rep a)) => a -> Encoding Source #

Encode a value in the constructor-name-tagged CBOR format:

instance ToCBOR MyType where
  toCBOR = genericToCBOR

genericFromCBOR :: (Generic a, GFromCBOR (Rep a)) => Decoder s a Source #

Decode a value from the constructor-name-tagged CBOR format produced by genericToCBOR:

instance FromCBOR MyType where
  fromCBOR = genericFromCBOR