Skip to content

Commit

Permalink
Use the serde_cow crate (#2814)
Browse files Browse the repository at this point in the history
This replaces a manual implementation of deserialising strings into `Cow<str>`s.
  • Loading branch information
GnomedDev authored Mar 25, 2024
1 parent 808e952 commit 5fc5acf
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 42 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ dep_time = { version = "0.3.30", package = "time", features = ["formatting", "pa
base64 = { version = "0.21.5" }
secrecy = { version = "0.8.0", features = ["serde"] }
arrayvec = { version = "0.7.4", features = ["serde"] }
serde_cow = { version = "0.1.0" }
# Optional dependencies
fxhash = { version = "0.2.1", optional = true }
simd-json = { version = "0.13.4", optional = true }
Expand Down
3 changes: 2 additions & 1 deletion src/model/channel/attachment.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
#[cfg(feature = "model")]
use reqwest::Client as ReqwestClient;
use serde_cow::CowStr;

#[cfg(feature = "model")]
use crate::internal::prelude::*;
use crate::model::prelude::*;
use crate::model::utils::{is_false, CowStr};
use crate::model::utils::is_false;

fn base64_bytes<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
where
Expand Down
42 changes: 1 addition & 41 deletions src/model/utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::borrow::Cow;
use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;
Expand Down Expand Up @@ -83,44 +82,6 @@ where
}
}

pub(super) struct CowStr<'de>(pub Cow<'de, str>);

impl<'de> serde::Deserialize<'de> for CowStr<'de> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
struct CowStrVisitor;
impl<'de> serde::de::Visitor<'de> for CowStrVisitor {
type Value = CowStr<'de>;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a string")
}

fn visit_borrowed_str<E>(self, val: &'de str) -> StdResult<Self::Value, E>
where
E: serde::de::Error,
{
Ok(CowStr(Cow::Borrowed(val)))
}

fn visit_str<E>(self, val: &str) -> StdResult<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_string(val.into())
}

fn visit_string<E>(self, val: String) -> StdResult<Self::Value, E>
where
E: serde::de::Error,
{
Ok(CowStr(Cow::Owned(val)))
}
}

deserializer.deserialize_string(CowStrVisitor)
}
}

pub(super) enum StrOrInt<'de> {
String(String),
Str(&'de str),
Expand Down Expand Up @@ -320,8 +281,7 @@ pub mod stickers {
/// Used with `#[serde(with = "comma_separated_string")]`
pub mod comma_separated_string {
use serde::{Deserialize, Deserializer, Serializer};

use super::CowStr;
use serde_cow::CowStr;

pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
Expand Down

0 comments on commit 5fc5acf

Please sign in to comment.