Skip to content

Commit

Permalink
Fix IggyDuration (de)serialization (#967)
Browse files Browse the repository at this point in the history
  • Loading branch information
spetz authored May 28, 2024
1 parent eed2199 commit c0bf739
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions sdk/src/utils/duration.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use humantime::format_duration;
use humantime::Duration as HumanDuration;
use serde::{Deserialize, Serialize};
use serde::de::Visitor;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{
fmt::{Display, Formatter},
ops::Add,
str::FromStr,
time::Duration,
};

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Eq, PartialEq)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct IggyDuration {
duration: Duration,
}
Expand Down Expand Up @@ -133,6 +134,41 @@ impl Add for IggyDuration {
}
}

impl Serialize for IggyDuration {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.as_secs())
}
}

struct IggyDurationVisitor;

impl<'de> Deserialize<'de> for IggyDuration {
fn deserialize<D>(deserializer: D) -> Result<IggyDuration, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_u64(IggyDurationVisitor)
}
}

impl<'de> Visitor<'de> for IggyDurationVisitor {
type Value = IggyDuration;

fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a duration in seconds")
}

fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(IggyDuration::new(Duration::from_secs(value)))
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit c0bf739

Please sign in to comment.