Skip to content

Commit

Permalink
fix(rust): use zero as the fallback for empty strings when parsing to…
Browse files Browse the repository at this point in the history
… a number.
  • Loading branch information
nkaz001 committed Oct 29, 2024
1 parent d0b50a4 commit 949d74e
Showing 1 changed file with 19 additions and 17 deletions.
36 changes: 19 additions & 17 deletions connector/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::bybit::BybitError;
struct I64Visitor;

impl<'de> Visitor<'de> for I64Visitor {
type Value = i64;
type Value = Option<i64>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string containing an i64 number")
Expand All @@ -33,7 +33,11 @@ impl<'de> Visitor<'de> for I64Visitor {
where
E: de::Error,
{
s.parse::<i64>().map_err(Error::custom)
if s.is_empty() {
Ok(Some(0))
} else {
Ok(Some(s.parse::<i64>().map_err(Error::custom)?))
}
}
}

Expand All @@ -57,24 +61,14 @@ impl<'de> Visitor<'de> for OptionF64Visitor {
where
D: Deserializer<'de>,
{
match deserializer.deserialize_str(F64Visitor) {
Ok(num) => Ok(Some(num)),
Err(e) => {
// fixme: dirty
if format!("{e:?}").starts_with("Error(\"cannot parse float from empty string\"") {
Ok(None)
} else {
Err(e)
}
}
}
deserializer.deserialize_str(F64Visitor)
}
}

struct F64Visitor;

impl<'de> Visitor<'de> for F64Visitor {
type Value = f64;
type Value = Option<f64>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string containing an f64 number")
Expand All @@ -84,22 +78,30 @@ impl<'de> Visitor<'de> for F64Visitor {
where
E: de::Error,
{
s.parse::<f64>().map_err(Error::custom)
if s.is_empty() {
Ok(None)
} else {
Ok(Some(s.parse::<f64>().map_err(Error::custom)?))
}
}
}

pub fn from_str_to_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(I64Visitor)
deserializer
.deserialize_str(I64Visitor)
.map(|value| value.unwrap_or(0))
}

pub fn from_str_to_f64<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(F64Visitor)
deserializer
.deserialize_str(F64Visitor)
.map(|value| value.unwrap_or(0.0))
}

pub fn from_str_to_f64_opt<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
Expand Down

0 comments on commit 949d74e

Please sign in to comment.