Skip to content

Add HasPolyCborCodec #430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,17 @@ trait CborAdtInstances[T] {
def cborCodec: GenObjectCodec[T] =
metadata.setup(_.validate()).adjustCodec(stdCodec)
}

trait CborAdtPolyInstances[C[_]] {
def stdCodec[T: GenCodec]: GenObjectCodec[C[T]]
def metadata[T]: CborAdtMetadata[C[T]]
}

/**
* Like [[HasCborCodec]] but for parameterized (generic) data types.
*/
abstract class HasPolyCborCodec[C[_]](implicit instances: MacroInstances[CborOptimizedCodecs, CborAdtPolyInstances[C]]) {
private lazy val validatedInstances = instances(CborOptimizedCodecs, this).setup(_.metadata[Nothing].validate())

implicit def codec[T: GenCodec]: GenObjectCodec[C[T]] = validatedInstances.metadata[T].adjustCodec(validatedInstances.stdCodec[T])
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ case class CustomKeysRecord(
)
object CustomKeysRecord extends HasCborCodec[CustomKeysRecord]

@cborDiscriminator(0)
sealed trait GenericSealedTrait[+T]
object GenericSealedTrait extends HasPolyCborCodec[GenericSealedTrait] {
@cborKey(0)
case class Success[+T](@cborKey(1) value: T) extends GenericSealedTrait[T]
@cborKey(1)
case class Failure(@cborKey(1) message: String) extends GenericSealedTrait[Nothing]
}

@cborDiscriminator(0)
sealed trait CustomKeysFlatUnion extends Product with Serializable
object CustomKeysFlatUnion extends HasCborCodec[CustomKeysFlatUnion] {
Expand Down Expand Up @@ -211,6 +220,9 @@ class CborInputOutputTest extends AnyFunSuite {
test("chunked byte string") {
assert(CborInput.readRawCbor[Bytes](RawCbor.fromHex("5F426162426162426162FF")) == Bytes("ababab"))
}

roundtrip[GenericSealedTrait[Int]](GenericSealedTrait.Success[Int](234), "A200000118EA")
roundtrip[GenericSealedTrait[Boolean]](GenericSealedTrait.Failure("error"), "A2000101656572726F72")
}

class CborGenCodecRoundtripTest extends GenCodecRoundtripTest {
Expand Down