Skip to content

Commit f69b2f8

Browse files
authored
Merge pull request #232 from elrnv/deserialize_bytes
Deserialize bytes
2 parents c640883 + baec844 commit f69b2f8

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

src/de/mod.rs

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -332,11 +332,15 @@ impl<'de, 'a, R: BufRead> de::Deserializer<'de> for &'a mut Deserializer<R> {
332332
}
333333

334334
fn deserialize_bytes<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, DeError> {
335-
self.deserialize_string(visitor)
335+
let text = self.next_text()?;
336+
let value = text.escaped();
337+
visitor.visit_bytes(value)
336338
}
337339

338340
fn deserialize_byte_buf<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, DeError> {
339-
self.deserialize_string(visitor)
341+
let text = self.next_text()?;
342+
let value = text.into_inner().into_owned();
343+
visitor.visit_byte_buf(value)
340344
}
341345

342346
fn deserialize_unit<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, DeError> {
@@ -566,4 +570,45 @@ mod tests {
566570
}
567571
);
568572
}
573+
574+
#[test]
575+
fn deserialize_bytes() {
576+
#[derive(Debug, PartialEq)]
577+
struct Item {
578+
bytes: Vec<u8>,
579+
}
580+
581+
impl<'de> Deserialize<'de> for Item {
582+
fn deserialize<D>(d: D) -> Result<Self, D::Error>
583+
where
584+
D: serde::de::Deserializer<'de>,
585+
{
586+
struct ItemVisitor;
587+
588+
impl<'de> de::Visitor<'de> for ItemVisitor {
589+
type Value = Item;
590+
591+
fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
592+
fmt.write_str("byte data")
593+
}
594+
595+
fn visit_byte_buf<E: de::Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
596+
Ok(Item { bytes: v })
597+
}
598+
}
599+
600+
Ok(d.deserialize_byte_buf(ItemVisitor)?)
601+
}
602+
}
603+
604+
let s = r#"<item>bytes</item>"#;
605+
let item: Item = from_reader(s.as_bytes()).unwrap();
606+
607+
assert_eq!(
608+
item,
609+
Item {
610+
bytes: "bytes".as_bytes().to_vec(),
611+
}
612+
);
613+
}
569614
}

src/events/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,13 @@ impl<'a> BytesText<'a> {
472472
}
473473
}
474474

475+
/// Extracts the inner `Cow` from the `BytesText` event container.
476+
#[cfg(feature = "serialize")]
477+
#[inline]
478+
pub(crate) fn into_inner(self) -> Cow<'a, [u8]> {
479+
self.content
480+
}
481+
475482
/// gets escaped content
476483
///
477484
/// Searches for '&' into content and try to escape the coded character if possible

0 commit comments

Comments
 (0)