Skip to content

Commit

Permalink
feat: Add JsonSerialize and ValueDeserialize impls for f32, f64
Browse files Browse the repository at this point in the history
  • Loading branch information
fasterthanlime committed Sep 20, 2024
1 parent 1843f29 commit 2a7d6a4
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 3 deletions.
28 changes: 28 additions & 0 deletions merde_core/src/deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,34 @@ impl<'s> ValueDeserialize<'s> for isize {
}
}

impl<'s> ValueDeserialize<'s> for f32 {
fn from_value_ref<'val>(value: Option<&'val Value<'s>>) -> Result<Self, MerdeError> {
match value {
Some(Value::Float(f)) => Ok(*f as f32),
Some(Value::Int(i)) => Ok(*i as f32),
Some(v) => Err(MerdeError::MismatchedType {
expected: ValueType::Float,
found: v.value_type(),
}),
None => Err(MerdeError::MissingValue),
}
}
}

impl<'s> ValueDeserialize<'s> for f64 {
fn from_value_ref<'val>(value: Option<&'val Value<'s>>) -> Result<Self, MerdeError> {
match value {
Some(Value::Float(f)) => Ok(*f),
Some(Value::Int(i)) => Ok(*i as f64),
Some(v) => Err(MerdeError::MismatchedType {
expected: ValueType::Float,
found: v.value_type(),
}),
None => Err(MerdeError::MissingValue),
}
}
}

impl<'s> ValueDeserialize<'s> for bool {
fn from_value_ref<'val>(value: Option<&'val Value<'s>>) -> Result<Self, MerdeError> {
match value {
Expand Down
2 changes: 1 addition & 1 deletion merde_core/src/into_static.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ macro_rules! impl_into_static_passthru {
}

impl_into_static_passthru!(
String, u128, u64, u32, u16, u8, i128, i64, i32, i16, i8, bool, char, f32, f64, usize, isize
String, u128, u64, u32, u16, u8, i128, i64, i32, i16, i8, bool, char, usize, isize, f32, f64
);

impl<T: IntoStatic> IntoStatic for Option<T> {
Expand Down
4 changes: 2 additions & 2 deletions merde_core/src/with_lifetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@ impl_with_lifetime!(
i8,
bool,
char,
f32,
f64,
usize,
isize,
f32,
f64,
);

impl<'s> WithLifetime<'s> for () {
Expand Down
12 changes: 12 additions & 0 deletions merde_json/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,18 @@ impl JsonSerialize for isize {
}
}

impl JsonSerialize for f32 {
fn json_serialize(&self, serializer: &mut JsonSerializer) {
serializer.write_f64(*self as f64);
}
}

impl JsonSerialize for f64 {
fn json_serialize(&self, serializer: &mut JsonSerializer) {
serializer.write_f64(*self);
}
}

impl JsonSerialize for bool {
fn json_serialize(&self, serializer: &mut JsonSerializer) {
serializer.write_bool(*self);
Expand Down

0 comments on commit 2a7d6a4

Please sign in to comment.