From 09be5e002138aaa4d0f4d1fc2d6c61420a3f4188 Mon Sep 17 00:00:00 2001 From: Sunli Date: Thu, 2 Dec 2021 20:19:17 +0800 Subject: [PATCH] Fix panic on f32-64::INFINITE/f32-64::NEG_INFINITE/f32-64::NAN output. #735 --- CHANGELOG.md | 4 ++++ src/types/external/floats.rs | 10 ++++++++-- tests/scalar.rs | 23 +++++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a6f4793..1a1a3758 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +- Fix panic on f32-64::INFINITE/f32-64::NEG_INFINITE/f32-64::NAN output. [#735](https://github.com/async-graphql/async-graphql/issues/735) + ## [3.0.10] 2021-11-30 - Fix the custom validator cannot work on `Option>`. diff --git a/src/types/external/floats.rs b/src/types/external/floats.rs index ff1d92b2..4ea74ae3 100644 --- a/src/types/external/floats.rs +++ b/src/types/external/floats.rs @@ -18,7 +18,10 @@ impl ScalarType for f32 { } fn to_value(&self) -> Value { - Value::Number(Number::from_f64(*self as f64).unwrap()) + match Number::from_f64(*self as f64) { + Some(n) => Value::Number(n), + None => Value::Null, + } } } @@ -40,6 +43,9 @@ impl ScalarType for f64 { } fn to_value(&self) -> Value { - Value::Number(Number::from_f64(*self as f64).unwrap()) + match Number::from_f64(*self as f64) { + Some(n) => Value::Number(n), + None => Value::Null, + } } } diff --git a/tests/scalar.rs b/tests/scalar.rs index 410d37bb..9cdf9e0a 100644 --- a/tests/scalar.rs +++ b/tests/scalar.rs @@ -45,3 +45,26 @@ pub async fn test_scalar_macro() { }) ); } + +#[tokio::test] +pub async fn test_float_inf() { + struct Query; + + #[Object] + impl Query { + async fn value(&self) -> f32 { + f32::INFINITY + } + } + + let schema = Schema::new(Query, EmptyMutation, EmptySubscription); + assert_eq!( + schema + .execute("{ value }") + .await + .into_result() + .unwrap() + .data, + value!({ "value": null }) + ); +}