Skip to content

Commit 5e355f1

Browse files
committed
Fix CallId codec
1 parent 80556bc commit 5e355f1

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

core/src/jsonrpclib/CallId.scala

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package jsonrpclib
22

33
import com.github.plokhotnyuk.jsoniter_scala.core._
4-
import scala.util.Try
54

65
sealed trait CallId
76
object CallId {
@@ -10,12 +9,20 @@ object CallId {
109
case object NullId extends CallId
1110

1211
implicit val callIdRW: JsonValueCodec[CallId] = new JsonValueCodec[CallId] {
13-
def decodeValue(in: JsonReader, default: CallId): CallId =
14-
Try(in.readLong())
15-
.map(NumberId(_): CallId)
16-
.orElse(Try(in.readString(null)).map(StringId(_): CallId))
17-
.orElse(scala.util.Success(default))
18-
.get
12+
def decodeValue(in: JsonReader, default: CallId): CallId = {
13+
try {
14+
NumberId(in.readLong())
15+
} catch {
16+
case _: JsonReaderException =>
17+
in.rollbackToken()
18+
try {
19+
StringId(in.readString(null))
20+
} catch {
21+
case _: JsonReaderException =>
22+
in.readNullOrError(default, "expected null")
23+
}
24+
}
25+
}
1926

2027
def encodeValue(x: CallId, out: JsonWriter): Unit = x match {
2128
case NumberId(long) => out.writeVal(long)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package jsonrpclib
2+
3+
import munit._
4+
import com.github.plokhotnyuk.jsoniter_scala.core._
5+
6+
class CallIdSpec() extends FunSuite {
7+
test("json parsing") {
8+
val strJson = """ "25" """.trim
9+
assertEquals(readFromString[CallId](strJson), CallId.StringId("25"))
10+
11+
val intJson = "25"
12+
assertEquals(readFromString[CallId](intJson), CallId.NumberId(25))
13+
14+
val longJson = Long.MaxValue.toString
15+
assertEquals(readFromString[CallId](longJson), CallId.NumberId(Long.MaxValue))
16+
17+
val nullJson = "null"
18+
assertEquals(readFromString[CallId](nullJson), CallId.NullId)
19+
}
20+
}

0 commit comments

Comments
 (0)