Skip to content

Commit

Permalink
Add a custom codec test for com.epam.deltix.dfp.Decimal64 values th…
Browse files Browse the repository at this point in the history
…rough `scala.BigDecimal` as a possible workaround for #1046
  • Loading branch information
plokhotnyuk committed Jan 25, 2024
1 parent 8119a5f commit 6e512db
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ lazy val `jsoniter-scala-macros` = crossProject(JVMPlatform, JSPlatform, NativeP
)
case _ => Seq()
}) ++ Seq(
"com.epam.deltix" % "dfp" % "1.0.1" % Test,
"org.scalatest" %%% "scalatest" % "3.2.17" % Test,
"org.scala-lang.modules" %%% "scala-collection-compat" % "2.11.0" % Test
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.github.plokhotnyuk.jsoniter_scala.macros

import com.epam.deltix.dfp.{Decimal64, Decimal64Utils}
import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker._

class JsonCodecMakerDecimal64Spec extends VerifyingSpec {
import Decimal64Codec._

"Decimal64Codec" should {
"deserialize both numeric and string representation of numbers to canonized Decimal64 values" in {
verifyDeser(make[List[Decimal64]],
List(Decimal64.ONE_TENTH, Decimal64.MILLION, Decimal64.fromLong(4503599627370497L), Decimal64.MAX_VALUE),
"""[0.1,"001000000",4503599627370497,"9999999999999999e+369"]""")
}
"serialize Decimal64 values into numeric or string representation depending on number of mantissa bits of canonized in-memory representation" in {
verifySer(make[List[Decimal64]],
List(Decimal64.ONE_TENTH, Decimal64.MILLION, Decimal64.fromLong(4503599627370497L), Decimal64.MAX_VALUE),
"""[0.1,1E+6,"4503599627370497","9.999999999999999E+384"]""")
}
}
}

object Decimal64Codec {
implicit val codec: JsonValueCodec[Decimal64] = new JsonValueCodec[Decimal64] {
override def decodeValue(in: JsonReader, default: Decimal64): Decimal64 =
Decimal64.fromUnderlying(Decimal64Utils.canonize(Decimal64Utils.fromBigDecimal((if (in.isNextToken('"')) {
in.rollbackToken()
in.readStringAsBigDecimal(null)
} else {
in.rollbackToken()
in.readBigDecimal(null)
}).bigDecimal)))

override def encodeValue(x: Decimal64, out: JsonWriter): Unit = {
val cx = Decimal64Utils.canonize(Decimal64.toUnderlying(x))
val bd = new BigDecimal(Decimal64Utils.toBigDecimal(cx))
val m = Decimal64Utils.getUnscaledValue(cx)
if (m > 4503599627370496L || m < -4503599627370496L) out.writeValAsString(bd)
else out.writeVal(bd)
}

override def nullValue: Decimal64 = null
}
}

0 comments on commit 6e512db

Please sign in to comment.