Skip to content

Commit

Permalink
refactor(model): simplify auto_archive_duration de/serialize
Browse files Browse the repository at this point in the history
  • Loading branch information
Erk- committed Oct 6, 2024
1 parent 6584104 commit 1d68617
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 57 deletions.
27 changes: 8 additions & 19 deletions twilight-model/src/channel/thread/auto_archive_duration.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use crate::visitor::U16EnumVisitor;
use serde::{
de::{Deserialize, Deserializer},
ser::{Serialize, Serializer},
};
use serde::{Deserialize, Serialize};
use std::time::Duration;

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
#[serde(from = "u16", into = "u16")]
pub enum AutoArchiveDuration {
Hour,
Day,
Expand Down Expand Up @@ -47,23 +44,15 @@ impl From<u16> for AutoArchiveDuration {
}
}

impl From<AutoArchiveDuration> for Duration {
impl From<AutoArchiveDuration> for u16 {
fn from(value: AutoArchiveDuration) -> Self {
Self::from_secs(u64::from(value.number()) * 60)
}
}

impl<'de> Deserialize<'de> for AutoArchiveDuration {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer
.deserialize_u16(U16EnumVisitor::new("auto archive duration"))
.map(u16::into)
value.number()
}
}

impl Serialize for AutoArchiveDuration {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_u16(self.number())
impl From<AutoArchiveDuration> for Duration {
fn from(value: AutoArchiveDuration) -> Self {
Self::from_secs(u64::from(value.number()) * 60)
}
}

Expand Down
38 changes: 0 additions & 38 deletions twilight-model/src/visitor.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
use serde::de::{Error as DeError, Visitor};
use std::{
fmt::{Formatter, Result as FmtResult},
marker::PhantomData,
};

/// Deserializers for optional nullable fields.
///
/// Some booleans in the Discord API are null when true, and not present when
Expand Down Expand Up @@ -137,35 +131,3 @@ pub mod zeroable_id {
})
}
}

pub struct U16EnumVisitor<'a> {
description: &'a str,
phantom: PhantomData<u16>,
}

impl<'a> U16EnumVisitor<'a> {
pub const fn new(description: &'a str) -> Self {
Self {
description,
phantom: PhantomData,
}
}
}

impl<'de> Visitor<'de> for U16EnumVisitor<'_> {
type Value = u16;

fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str(self.description)
}

fn visit_u16<E: DeError>(self, value: u16) -> Result<Self::Value, E> {
Ok(value)
}

fn visit_u64<E: DeError>(self, value: u64) -> Result<Self::Value, E> {
let smaller = u16::try_from(value).map_err(E::custom)?;

self.visit_u16(smaller)
}
}

0 comments on commit 1d68617

Please sign in to comment.