-
Notifications
You must be signed in to change notification settings - Fork 58
impl(wkt): helper type for i32
deserialization
#2334
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
coryan
merged 5 commits into
googleapis:main
from
coryan:feat-wkt-support-custom-i32-encoding
May 31, 2025
+431
−0
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7cca4ce
impl(wkt): helper type for `i32` deserialization
coryan 14fe676
More test cases
coryan 6aecb1c
Support floating point numbers that are integers
coryan 16cd950
Address review comments.
coryan 9068aad
Addressed review comments.
coryan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
// Copyright 2025 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
//! Implement custom serializers for `i32`. | ||
//! | ||
//! In ProtoJSON 32-bit integers can be serialized as either strings or numbers. | ||
|
||
use serde::de::Unexpected::Other; | ||
|
||
pub struct I32; | ||
|
||
impl<'de> serde_with::DeserializeAs<'de, i32> for I32 { | ||
fn deserialize_as<D>(deserializer: D) -> Result<i32, D::Error> | ||
where | ||
D: serde::de::Deserializer<'de>, | ||
{ | ||
deserializer.deserialize_any(I32Visitor) | ||
} | ||
} | ||
|
||
const ERRMSG: &str = "a 32-bit signed integer"; | ||
|
||
struct I32Visitor; | ||
|
||
impl serde::de::Visitor<'_> for I32Visitor { | ||
type Value = i32; | ||
|
||
fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E> | ||
where | ||
E: serde::de::Error, | ||
{ | ||
// ProtoJSON says that both strings and numbers are accepted. Parse the | ||
// string as a `f64` number (all JSON numbers are `f64`) and then try to | ||
// parse that as an `i32`. | ||
let number = value.parse::<f64>().map_err(E::custom)?; | ||
self.visit_f64(number) | ||
} | ||
|
||
fn visit_i64<E>(self, value: i64) -> std::result::Result<Self::Value, E> | ||
where | ||
E: serde::de::Error, | ||
{ | ||
match value { | ||
_ if value < i32::MIN as i64 => Err(self::value_error(value)), | ||
_ if value > i32::MAX as i64 => Err(self::value_error(value)), | ||
_ => Ok(value as i32), | ||
} | ||
} | ||
|
||
fn visit_u64<E>(self, value: u64) -> std::result::Result<Self::Value, E> | ||
where | ||
E: serde::de::Error, | ||
{ | ||
match value { | ||
_ if value > i32::MAX as u64 => Err(self::value_error(value)), | ||
_ => Ok(value as i32), | ||
} | ||
} | ||
|
||
fn visit_f64<E>(self, value: f64) -> std::result::Result<Self::Value, E> | ||
where | ||
E: serde::de::Error, | ||
{ | ||
match value { | ||
_ if value < i32::MIN as f64 => Err(self::value_error(value)), | ||
_ if value > i32::MAX as f64 => Err(self::value_error(value)), | ||
_ if value.fract().abs() > 0.0 => Err(self::value_error(value)), | ||
// The number is "rounded towards zero". Because we are in range, | ||
// and the fractional part is 0, this conversion should be safe. | ||
// See https://doc.rust-lang.org/reference/expressions/operator-expr.html#r-expr.as.numeric.float-as-int | ||
_ => Ok(value as i32), | ||
} | ||
} | ||
|
||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { | ||
formatter.write_str("a 32-bit integer in ProtoJSON format") | ||
} | ||
} | ||
|
||
fn value_error<T, E>(value: T) -> E | ||
where | ||
T: std::fmt::Display, | ||
E: serde::de::Error, | ||
{ | ||
E::invalid_value(Other(&format!("{value}")), &ERRMSG) | ||
} | ||
|
||
impl serde_with::SerializeAs<i32> for I32 { | ||
fn serialize_as<S>(source: &i32, serializer: S) -> Result<S::Ok, S::Error> | ||
where | ||
S: serde::Serializer, | ||
{ | ||
serializer.serialize_i32(*source) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use super::*; | ||
use anyhow::Result; | ||
use serde_json::{Value, json}; | ||
use serde_with::{DeserializeAs, SerializeAs}; | ||
use test_case::test_case; | ||
|
||
#[test_case(0, 0)] | ||
#[test_case("0", 0; "zero string")] | ||
#[test_case("2.0", 2)] | ||
#[test_case(3e5, 300_000)] | ||
#[test_case(-4e4, -40_000)] | ||
#[test_case("5e4", 50_000)] | ||
#[test_case("-6e5", -600_000)] | ||
#[test_case(-42, -42)] | ||
#[test_case("-7", -7)] | ||
#[test_case(84, 84)] | ||
#[test_case(168.0, 168)] | ||
#[test_case("21", 21)] | ||
#[test_case(i32::MAX, i32::MAX; "max")] | ||
#[test_case(i32::MAX as f64, i32::MAX; "max as f64")] | ||
#[test_case(format!("{}", i32::MAX), i32::MAX; "max as string")] | ||
#[test_case(format!("{}.0", i32::MAX), i32::MAX; "max as f64 string")] | ||
#[test_case(i32::MIN, i32::MIN; "min")] | ||
#[test_case(i32::MIN as f64, i32::MIN; "min as f64")] | ||
#[test_case(format!("{}", i32::MIN), i32::MIN; "min as string")] | ||
#[test_case(format!("{}.0", i32::MIN), i32::MIN; "min as f64 string")] | ||
// Not quite a roundtrip test because we always serialize as numbers. | ||
fn deser_and_ser<T: serde::Serialize>(input: T, want: i32) -> Result<()> { | ||
let got = I32::deserialize_as(json!(input))?; | ||
assert_eq!(got, want); | ||
|
||
let serialized = I32::serialize_as(&got, serde_json::value::Serializer)?; | ||
assert_eq!(serialized, json!(got)); | ||
Ok(()) | ||
} | ||
|
||
#[test_case(json!(i64::MAX))] | ||
#[test_case(json!(i64::MIN))] | ||
#[test_case(json!(i32::MAX as i64 + 2))] | ||
#[test_case(json!(i32::MIN as i64 - 2))] | ||
#[test_case(json!(format!("{}", i64::MAX)))] | ||
#[test_case(json!(format!("{}", i64::MIN)))] | ||
#[test_case(json!("abc"))] | ||
#[test_case(json!(123.4))] | ||
#[test_case(json!("234.5"))] | ||
#[test_case(json!({}))] | ||
fn deser_error(input: Value) { | ||
let got = I32::deserialize_as(input).unwrap_err(); | ||
assert!(got.is_data(), "{got:?}"); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.