serde/test_suite/tests/bytes/mod.rs

59 lines
1.2 KiB
Rust
Raw Normal View History

2018-04-30 03:41:22 -05:00
use serde::de::{Deserializer, Error, SeqAccess, Visitor};
use std::fmt;
pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
2018-04-30 03:41:22 -05:00
where
D: Deserializer<'de>,
{
deserializer.deserialize_byte_buf(ByteBufVisitor)
}
struct ByteBufVisitor;
impl<'de> Visitor<'de> for ByteBufVisitor {
type Value = Vec<u8>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("byte array")
}
fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
2018-04-30 03:41:22 -05:00
where
V: SeqAccess<'de>,
{
let mut values = Vec::new();
2018-12-31 20:46:14 -06:00
while let Some(value) = visitor.next_element()? {
values.push(value);
}
Ok(values)
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
2018-04-30 03:41:22 -05:00
where
E: Error,
{
Ok(v.to_vec())
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
2018-04-30 03:41:22 -05:00
where
E: Error,
{
Ok(v)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
2018-04-30 03:41:22 -05:00
where
E: Error,
{
Ok(v.as_bytes().to_vec())
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
2018-04-30 03:41:22 -05:00
where
E: Error,
{
Ok(v.into_bytes())
}
}