fix(napi): convert u64 to u32 in serialization (#1478)

https://github.com/napi-rs/napi-rs/issues/1470
serde_json::Value parses positive integers to u64 types by default. When converting serde_json::Value to a js value, those numbers are converted to BigInts, even if they are within the bounds of the number primitive. The added checks converts an u64 to an u32 if possible to prevent this behavior.

Co-authored-by: m1212e <->
This commit is contained in:
m1212e 2023-02-08 15:25:03 +01:00 committed by GitHub
parent 80ec3dd2d9
commit a7dcf2a838
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -95,11 +95,19 @@ impl<'env> Serializer for Ser<'env> {
#[cfg(feature = "napi6")]
fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
// https://github.com/napi-rs/napi-rs/issues/1470
// serde_json::Value by default uses u64 for positive integers. This results in napirs using a BigInt instead of a number when converting to a js value.
// To avoid this, we need to check if the value fits into a smaller number type.
// If this is the case, we use the smaller type instead.
if v <= u32::MAX.into() {
self.serialize_u32(v as u32)
} else {
self
.0
.create_bigint_from_u64(v)
.map(|js_number| js_number.raw)
}
}
#[cfg(all(
any(