Skip to content
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

🐛 zv: Allow f32::NAN to be decoded too #1148

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion zvariant/src/dbus/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,13 @@ impl<'de, 'd, 'sig, 'f, #[cfg(unix)] F: AsFd, #[cfg(not(unix))] F> de::Deseriali
.endian()
.read_f64(self.0.next_const_size_slice::<f64>()?);

visitor.visit_f32(f64_to_f32(v))
if v.is_finite() && v > (f32::MAX as f64) {
zeenix marked this conversation as resolved.
Show resolved Hide resolved
return Err(de::Error::invalid_value(
de::Unexpected::Float(v),
&"Too large for f32",
));
}
visitor.visit_f32(v as f32)
}

fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
Expand Down
22 changes: 22 additions & 0 deletions zvariant/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2017,6 +2017,28 @@ mod tests {
let _: ZVStruct<'_> = encoded.deserialize_for_signature(signature).unwrap().0;
}

#[test]
fn issue_1145() {
// Ensure f32::NAN can be encoded and decoded.
let ctxt = Context::new_dbus(LE, 0);
{
let encoded = to_bytes(ctxt, &f32::NAN).unwrap();
let result: f32 = encoded.deserialize().unwrap().0;
assert!(result.is_nan());
}
// Ensure f32::INFINITY can be encoded and decoded.
{
let encoded = to_bytes(ctxt, &f32::INFINITY).unwrap();
let result: f32 = encoded.deserialize().unwrap().0;
assert!(result.is_infinite());
}
{
let encoded = to_bytes(ctxt, &f32::NEG_INFINITY).unwrap();
let result: f32 = encoded.deserialize().unwrap().0;
assert!(result.is_infinite());
}
}

#[cfg(feature = "ostree-tests")]
#[test]
fn ostree_de() {
Expand Down
6 changes: 0 additions & 6 deletions zvariant/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,6 @@ pub(crate) fn usize_to_u8(value: usize) -> u8 {
value as u8
}

pub(crate) fn f64_to_f32(value: f64) -> f32 {
assert!(value <= (f32::MAX as f64), "{} too large for `f32`", value,);

value as f32
}

/// Slice the given slice of bytes safely and return an error if the slice is too small.
pub(crate) fn subslice<I, T>(input: &[T], index: I) -> Result<&I::Output>
where
Expand Down
Loading