Skip to content

Commit 6ff0029

Browse files
committed
Accept ints as doubles in Bson inputs
1 parent 28f66d3 commit 6ff0029

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

commons-mongo/jvm/src/main/scala/com/avsystem/commons/mongo/BsonReaderInput.scala

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,14 @@ class BsonReaderInput(br: BsonReader, override val legacyOptionEncoding: Boolean
3737
override def readTimestamp(): Long =
3838
expect(BsonType.DATE_TIME, br.readDateTime())
3939

40-
override def readDouble(): Double =
41-
expect(BsonType.DOUBLE, br.readDouble())
40+
override def readDouble(): Double = handleFailures {
41+
bsonType match {
42+
case BsonType.DOUBLE => br.readDouble()
43+
case BsonType.INT32 => br.readInt32().toDouble
44+
case BsonType.INT64 => br.readInt64().toDouble
45+
case _ => wrongType(BsonType.DOUBLE, BsonType.INT32, BsonType.INT64)
46+
}
47+
}
4248

4349
override def readBinary(): Array[Byte] =
4450
expect(BsonType.BINARY, br.readBinaryData().getData)

commons-mongo/jvm/src/main/scala/com/avsystem/commons/mongo/BsonValueInput.scala

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,14 @@ class BsonValueInput(bsonValue: BsonValue, override val legacyOptionEncoding: Bo
3333
override def readTimestamp(): Long =
3434
expect(BsonType.DATE_TIME, bsonValue.asDateTime().getValue)
3535

36-
def readDouble(): Double =
37-
expect(BsonType.DOUBLE, bsonValue.asDouble().getValue)
36+
override def readDouble(): Double = handleFailures {
37+
bsonType match {
38+
case BsonType.DOUBLE => bsonValue.asDouble().getValue
39+
case BsonType.INT32 => readInt().toDouble
40+
case BsonType.INT64 => bsonValue.asInt64().getValue.toDouble
41+
case _ => wrongType(BsonType.DOUBLE, BsonType.INT32, BsonType.INT64)
42+
}
43+
}
3844

3945
def readBinary(): Array[Byte] =
4046
expect(BsonType.BINARY, bsonValue.asBinary().getData)

commons-mongo/jvm/src/test/scala/com/avsystem/commons/mongo/BsonInputOutputTest.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,18 @@ class BsonValueGenCodecRoundtripTest extends GenCodecRoundtripTest {
7575
val result = input.readSimple().readLong()
7676
assert(result == 42L)
7777
}
78+
79+
test("Int32 to Double decoding") {
80+
val input = createInput(new BsonInt32(43))
81+
val result = input.readSimple().readDouble()
82+
assert(result == 43D)
83+
}
84+
85+
test("Int64 to Double decoding") {
86+
val input = createInput(new BsonInt64(44))
87+
val result = input.readSimple().readDouble()
88+
assert(result == 44D)
89+
}
7890
}
7991

8092
class BsonInputOutputTest extends AnyFunSuite with ScalaCheckPropertyChecks {

0 commit comments

Comments
 (0)