Skip to content

Adds support for [u8; N] #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] {
}
}

impl<'de, const N: usize> Deserialize<'de> for [u8; N] {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// serde::Deserialize for &[u8] is already optimized, so simply forward to that.
let as_ref: &[u8] = serde::Deserialize::deserialize(deserializer)?;
let mut owned = [0u8; N];
// DO NOT SUBMIT: This can panic, so what error should I return
// instead?
owned.copy_from_slice(as_ref);
Ok(owned)
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de> Deserialize<'de> for Vec<u8> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
Expand Down
9 changes: 9 additions & 0 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ impl Serialize for [u8] {
}
}

impl<const N: usize> Serialize for [u8; N] {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bytes(self)
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl Serialize for Vec<u8> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
Expand Down