File tree Expand file tree Collapse file tree 2 files changed +26
-0
lines changed
main/scala/com/avsystem/commons/serialization/cbor
test/scala/com/avsystem/commons/serialization/cbor Expand file tree Collapse file tree 2 files changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -253,3 +253,17 @@ trait CborAdtInstances[T] {
253253 def cborCodec : GenObjectCodec [T ] =
254254 metadata.setup(_.validate()).adjustCodec(stdCodec)
255255}
256+
257+ trait CborAdtPolyInstances [C [_]] {
258+ def stdCodec [T : GenCodec ]: GenObjectCodec [C [T ]]
259+ def metadata [T ]: CborAdtMetadata [C [T ]]
260+ }
261+
262+ /**
263+ * Like [[HasCborCodec ]] but for parameterized (generic) data types.
264+ */
265+ abstract class HasPolyCborCodec [C [_]](implicit instances : MacroInstances [CborOptimizedCodecs , CborAdtPolyInstances [C ]]) {
266+ private lazy val validatedInstances = instances(CborOptimizedCodecs , this ).setup(_.metadata[Nothing ].validate())
267+
268+ implicit def codec [T : GenCodec ]: GenObjectCodec [C [T ]] = validatedInstances.metadata[T ].adjustCodec(validatedInstances.stdCodec[T ])
269+ }
Original file line number Diff line number Diff line change @@ -28,6 +28,15 @@ case class CustomKeysRecord(
2828)
2929object CustomKeysRecord extends HasCborCodec [CustomKeysRecord ]
3030
31+ @ cborDiscriminator(0 )
32+ sealed trait GenericSealedTrait [+ T ]
33+ object GenericSealedTrait extends HasPolyCborCodec [GenericSealedTrait ] {
34+ @ cborKey(0 )
35+ case class Success [+ T ](@ cborKey(1 ) value : T ) extends GenericSealedTrait [T ]
36+ @ cborKey(1 )
37+ case class Failure (@ cborKey(1 ) message : String ) extends GenericSealedTrait [Nothing ]
38+ }
39+
3140@ cborDiscriminator(0 )
3241sealed trait CustomKeysFlatUnion extends Product with Serializable
3342object CustomKeysFlatUnion extends HasCborCodec [CustomKeysFlatUnion ] {
@@ -211,6 +220,9 @@ class CborInputOutputTest extends AnyFunSuite {
211220 test(" chunked byte string" ) {
212221 assert(CborInput .readRawCbor[Bytes ](RawCbor .fromHex(" 5F426162426162426162FF" )) == Bytes (" ababab" ))
213222 }
223+
224+ roundtrip[GenericSealedTrait [Int ]](GenericSealedTrait .Success [Int ](234 ), " A200000118EA" )
225+ roundtrip[GenericSealedTrait [Boolean ]](GenericSealedTrait .Failure (" error" ), " A2000101656572726F72" )
214226}
215227
216228class CborGenCodecRoundtripTest extends GenCodecRoundtripTest {
You can’t perform that action at this time.
0 commit comments