File tree Expand file tree Collapse file tree 2 files changed +37
-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 +37
-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 : GenCodec ]: CborAdtMetadata [C [T ]]
260+ def cborCodec [T : GenCodec ]: GenObjectCodec [C [T ]] =
261+ metadata.setup(_.validate()).adjustCodec(stdCodec)
262+ }
263+
264+ /**
265+ * Like [[HasCborCodec ]] but for parameterized (generic) data types.
266+ */
267+ abstract class HasPolyCborCodec [C [_]](implicit instances : MacroInstances [CborOptimizedCodecs , CborAdtPolyInstances [C ]]) {
268+ implicit def codec [T : GenCodec ]: GenObjectCodec [C [T ]] = instances(CborOptimizedCodecs , this ).cborCodec
269+ }
Original file line number Diff line number Diff line change @@ -28,6 +28,16 @@ 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 ](value : T ) extends GenericSealedTrait [T ]
36+ @ cborKey(1 )
37+ case class Failure (message : String ) extends GenericSealedTrait [Nothing ]
38+
39+ }
40+
3141@ cborDiscriminator(0 )
3242sealed trait CustomKeysFlatUnion extends Product with Serializable
3343object CustomKeysFlatUnion extends HasCborCodec [CustomKeysFlatUnion ] {
@@ -211,6 +221,19 @@ class CborInputOutputTest extends AnyFunSuite {
211221 test(" chunked byte string" ) {
212222 assert(CborInput .readRawCbor[Bytes ](RawCbor .fromHex(" 5F426162426162426162FF" )) == Bytes (" ababab" ))
213223 }
224+
225+ test(" generic sealed trait" ) {
226+ val success = GenericSealedTrait .Success [Int ](234 )
227+ val successCbor = CborOutput .writeRawCbor[GenericSealedTrait [Int ]](success)
228+ val decodedSuccess = CborInput .readRawCbor[GenericSealedTrait [Int ]](successCbor)
229+ assert(success == decodedSuccess)
230+
231+ val failure = GenericSealedTrait .Failure (" error" )
232+ val failureCbor = CborOutput .writeRawCbor[GenericSealedTrait [String ]](failure)
233+ val decodedFailure = CborInput .readRawCbor[GenericSealedTrait [String ]](failureCbor)
234+ assert(failure == decodedFailure)
235+ }
236+
214237}
215238
216239class CborGenCodecRoundtripTest extends GenCodecRoundtripTest {
You can’t perform that action at this time.
0 commit comments