Skip to content

Commit

Permalink
Merge pull request #46 from serde-rs/refbytearray
Browse files Browse the repository at this point in the history
Support deserializing `&'de [u8; N]`
  • Loading branch information
dtolnay authored Dec 27, 2023
2 parents 677457b + e1f53b2 commit 0d92965
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/bytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use serde::ser::{Serialize, Serializer};
/// # }
/// ```
#[derive(Copy, Clone, Eq, Ord)]
#[cfg_attr(not(doc), repr(transparent))]
pub struct ByteArray<const N: usize> {
bytes: [u8; N],
}
Expand All @@ -49,6 +50,10 @@ impl<const N: usize> ByteArray<N> {
pub fn into_array(self) -> [u8; N] {
self.bytes
}

fn from_ref(bytes: &[u8; N]) -> &Self {
unsafe { &*(bytes as *const [u8; N] as *const ByteArray<N>) }
}
}

impl<const N: usize> Debug for ByteArray<N> {
Expand Down Expand Up @@ -218,3 +223,39 @@ impl<'de, const N: usize> Deserialize<'de> for ByteArray<N> {
deserializer.deserialize_bytes(ByteArrayVisitor::<N>)
}
}

struct BorrowedByteArrayVisitor<const N: usize>;

impl<'de, const N: usize> Visitor<'de> for BorrowedByteArrayVisitor<N> {
type Value = &'de ByteArray<N>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a borrowed byte array of length {}", N)
}

fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
where
E: Error,
{
let borrowed_byte_array: &'de [u8; N] = v
.try_into()
.map_err(|_| E::invalid_length(v.len(), &self))?;
Ok(ByteArray::from_ref(borrowed_byte_array))
}

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

impl<'a, 'de: 'a, const N: usize> Deserialize<'de> for &'a ByteArray<N> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_bytes(BorrowedByteArrayVisitor::<N>)
}
}
10 changes: 10 additions & 0 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,16 @@ impl<'de, const N: usize> Deserialize<'de> for ByteArray<N> {
}
}

impl<'de: 'a, 'a, const N: usize> Deserialize<'de> for &'a ByteArray<N> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Via the serde::Deserialize impl for &ByteArray.
serde::Deserialize::deserialize(deserializer)
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de> Deserialize<'de> for ByteBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
Expand Down
8 changes: 7 additions & 1 deletion tests/test_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ struct Test<'a> {
#[serde(with = "serde_bytes")]
byte_array: ByteArray<314>,

#[serde(with = "serde_bytes")]
borrowed_byte_array: &'a ByteArray<314>,

#[serde(with = "serde_bytes")]
byte_buf: ByteBuf,

Expand Down Expand Up @@ -67,6 +70,7 @@ fn test() {
vec: b"...".to_vec(),
bytes: Bytes::new(b"..."),
byte_array: ByteArray::new([0; 314]),
borrowed_byte_array: &ByteArray::new([0; 314]),
byte_buf: ByteBuf::from(b"...".as_ref()),
cow_slice: Cow::Borrowed(b"..."),
cow_bytes: Cow::Borrowed(Bytes::new(b"...")),
Expand All @@ -84,7 +88,7 @@ fn test() {
&[
Token::Struct {
name: "Test",
len: 15,
len: 16,
},
Token::Str("slice"),
Token::BorrowedBytes(b"..."),
Expand All @@ -96,6 +100,8 @@ fn test() {
Token::BorrowedBytes(b"..."),
Token::Str("byte_array"),
Token::Bytes(&[0; 314]),
Token::Str("borrowed_byte_array"),
Token::BorrowedBytes(&[0; 314]),
Token::Str("byte_buf"),
Token::Bytes(b"..."),
Token::Str("cow_slice"),
Expand Down

0 comments on commit 0d92965

Please sign in to comment.