-
Notifications
You must be signed in to change notification settings - Fork 742
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Lenient byte and string deserialization from buffered content
- Loading branch information
Showing
3 changed files
with
352 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
use serde::de::{Deserializer, Visitor, SeqAccess, Error}; | ||
use std::fmt; | ||
|
||
pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error> | ||
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> | ||
where V: SeqAccess<'de> | ||
{ | ||
let mut values = Vec::new(); | ||
while let Some(value) = try!(visitor.next_element()) { | ||
values.push(value); | ||
} | ||
Ok(values) | ||
} | ||
|
||
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> | ||
where E: Error | ||
{ | ||
Ok(v.to_vec()) | ||
} | ||
|
||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> | ||
where E: Error | ||
{ | ||
Ok(v) | ||
} | ||
|
||
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> | ||
where E: Error | ||
{ | ||
Ok(v.as_bytes().to_vec()) | ||
} | ||
|
||
fn visit_string<E>(self, v: String) -> Result<Self::Value, E> | ||
where E: Error | ||
{ | ||
Ok(v.into_bytes()) | ||
} | ||
} |
Oops, something went wrong.