Skip to content

Commit a947024

Browse files
authored
fix: cast double Inf and NaN to float (#2304)
Casting a FLOAT64 value containing either Inf or NaN to a Java float failed, while Java itself allows the same conversion from a double Inf or NaN to the corresponding float Inf or NaN. Fixes #2256
1 parent 0606883 commit a947024

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapper.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ static int checkedCastToInt(BigInteger val) throws SQLException {
291291

292292
/** Cast value and throw {@link SQLException} if out-of-range. */
293293
static float checkedCastToFloat(double val) throws SQLException {
294-
if (val > Float.MAX_VALUE || val < -Float.MAX_VALUE) {
294+
if (Double.isFinite(val) && (val > Float.MAX_VALUE || val < -Float.MAX_VALUE)) {
295295
throw JdbcSqlExceptionFactory.of(
296296
String.format(OUT_OF_RANGE_MSG, "float", val), com.google.rpc.Code.OUT_OF_RANGE);
297297
}

src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapperTest.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ public void testCheckedCastFromBigIntegerToLong() {
256256
}
257257

258258
@Test
259-
public void testCheckedCastToFloat() {
259+
public void testCheckedCastToFloat() throws SQLException {
260260
final CheckedCastChecker<Double> checker =
261261
new CheckedCastChecker<>(AbstractJdbcWrapper::checkedCastToFloat);
262262
assertThat(checker.cast(0D)).isTrue();
@@ -268,6 +268,16 @@ public void testCheckedCastToFloat() {
268268
assertThat(checker.cast((double) Float.MIN_VALUE)).isTrue();
269269
assertThat(checker.cast(-Float.MAX_VALUE * 2d)).isFalse();
270270
assertThat(checker.cast(-Double.MAX_VALUE)).isFalse();
271+
272+
assertEquals(
273+
Float.POSITIVE_INFINITY,
274+
AbstractJdbcWrapper.checkedCastToFloat(Double.POSITIVE_INFINITY),
275+
0.0d);
276+
assertEquals(
277+
Float.NEGATIVE_INFINITY,
278+
AbstractJdbcWrapper.checkedCastToFloat(Double.NEGATIVE_INFINITY),
279+
0.0d);
280+
assertEquals(Float.NaN, AbstractJdbcWrapper.checkedCastToFloat(Double.NaN), 0.0d);
271281
}
272282

273283
@Test

0 commit comments

Comments
 (0)