Closed misos1 closed 5 years ago
I have this workaround for deserializers that support visit_borrowed_bytes
, ie formats where the bytes can be sourced directly from the data:
use std::fmt;
use std::marker::PhantomData;
use serde::de::{Deserializer, Error, Visitor};
use serde::ser::Serializer;
struct BorrowedBytesVisitor<T>(PhantomData<T>);
impl<'de, T> Visitor<'de> for BorrowedBytesVisitor<T> where &'de [u8]: Into<T> {
type Value = T;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a borrowed byte array")
}
#[inline]
fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<T, E>
where E: Error
{
Ok(v.into())
}
}
pub fn serialize<S, T>(bytes: &T, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer, T: AsRef<[u8]>
{
serializer.serialize_bytes(bytes.as_ref())
}
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where D: Deserializer<'de>, &'de [u8]: Into<T>
{
Ok(deserializer.deserialize_bytes(BorrowedBytesVisitor(PhantomData))?.into())
}
In the general case I guess serde_bytes has to go via Vec<u8>
to support formats like JSON where bytes must be parsed from a string or similar in the input data.
Fixed in 0.11.0 -- both of the following should now work:
#[derive(Serialize, Deserialize)]
struct TestSlice<'a> {
#[serde(with = "serde_bytes")]
a: &'a [u8]
}
#[derive(Serialize, Deserialize)]
struct TestBytes<'a> {
#[serde(borrow)]
a: &'a Bytes,
}
When I try to use:
I am getting compile errors:
When I try:
Then:
It would be more efficient to support deserialisation into &[u8] to avoid copies similarly as I can deserialise into &str. Or I am missing something?