From 71eef676d30f0958dd97850431530d9f404259c4 Mon Sep 17 00:00:00 2001 From: TotallyNot <44345987+TotallyNot@users.noreply.github.com> Date: Tue, 21 Feb 2023 16:00:55 +0100 Subject: [PATCH] added territory coordinates --- torn-api/Cargo.toml | 2 +- torn-api/src/common.rs | 8 ++++++++ torn-api/src/de_util.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/torn-api/Cargo.toml b/torn-api/Cargo.toml index 4699994..bba6c97 100644 --- a/torn-api/Cargo.toml +++ b/torn-api/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "torn-api" -version = "0.5.8" +version = "0.5.9" edition = "2021" authors = ["Pyrit [2111649]"] license = "MIT" diff --git a/torn-api/src/common.rs b/torn-api/src/common.rs index 412bcd2..3cc948a 100644 --- a/torn-api/src/common.rs +++ b/torn-api/src/common.rs @@ -47,4 +47,12 @@ pub struct Territory { pub density: i16, pub daily_respect: i16, pub faction: i32, + + #[cfg(feature = "decimal")] + #[serde(deserialize_with = "de_util::string_or_decimal")] + pub coordinate_x: rust_decimal::Decimal, + + #[cfg(feature = "decimal")] + #[serde(deserialize_with = "de_util::string_or_decimal")] + pub coordinate_y: rust_decimal::Decimal, } diff --git a/torn-api/src/de_util.rs b/torn-api/src/de_util.rs index 7a79b33..4be10e6 100644 --- a/torn-api/src/de_util.rs +++ b/torn-api/src/de_util.rs @@ -37,7 +37,8 @@ where if i == 0 { Ok(None) } else { - let naive = NaiveDateTime::from_timestamp(i, 0); + let naive = NaiveDateTime::from_timestamp_opt(i, 0) + .ok_or_else(|| D::Error::invalid_value(Unexpected::Signed(i), &"Epoch timestamp"))?; Ok(Some(DateTime::from_utc(naive, Utc))) } } @@ -90,3 +91,42 @@ where deserializer.deserialize_any(DumbVisitor) } + +#[cfg(feature = "decimal")] +pub(crate) fn string_or_decimal<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + struct DumbVisitor; + + impl<'de> Visitor<'de> for DumbVisitor { + type Value = rust_decimal::Decimal; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(formatter, "integer or float as string") + } + + fn visit_u64(self, v: u64) -> Result + where + E: Error, + { + Ok(v.into()) + } + + fn visit_i64(self, v: i64) -> Result + where + E: Error, + { + Ok(v.into()) + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + rust_decimal::Decimal::from_str_exact(v).map_err(E::custom) + } + } + + deserializer.deserialize_any(DumbVisitor) +}