Skip to content

Commit

Permalink
fix(bytes): remove redundant Visitor
Browse files Browse the repository at this point in the history
serde::Deserialize is already specialized for &[u8], so we simply
forward to that and transform the result.
  • Loading branch information
Xiretza committed May 27, 2022
1 parent 20f4214 commit d919de7
Showing 1 changed file with 2 additions and 26 deletions.
28 changes: 2 additions & 26 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use alloc::boxed::Box;
#[cfg(any(feature = "std", feature = "alloc"))]
use crate::ByteBuf;

use serde::de::{Deserialize, Deserializer, Error, Visitor};
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};

/// Wrapper around `[u8]` to serialize and deserialize efficiently.
Expand Down Expand Up @@ -161,35 +161,11 @@ impl Serialize for Bytes {
}
}

struct BytesVisitor;

impl<'de> Visitor<'de> for BytesVisitor {
type Value = &'de Bytes;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a borrowed byte array")
}

fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Bytes::new(v))
}

fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Bytes::new(v.as_bytes()))
}
}

impl<'a, 'de: 'a> Deserialize<'de> for &'a Bytes {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_bytes(BytesVisitor)
Deserialize::deserialize(deserializer).map(Bytes::new)
}
}

0 comments on commit d919de7

Please sign in to comment.