|
| 1 | +use std::cell::Cell; |
| 2 | +use std::fmt; |
| 3 | +use std::marker::PhantomData; |
| 4 | +use std::mem::transmute; |
| 5 | +use std::ops::Deref; |
| 6 | +use std::ptr; |
| 7 | + |
| 8 | +use roxmltree::Node; |
| 9 | +use serde::de; |
| 10 | + |
| 11 | +use crate::{Deserializer, Source}; |
| 12 | + |
| 13 | +/// Captures subtrees from the source |
| 14 | +/// |
| 15 | +/// This type must borrow from the source during serialization and therefore requires the use of the [`from_doc`][crate::from_doc] or [`from_node`][crate::from_node] entry points. |
| 16 | +/// It will however recover only the source `document` or `node` lifetime and not the full `input` lifetime. |
| 17 | +/// |
| 18 | +/// ``` |
| 19 | +/// use roxmltree::Document; |
| 20 | +/// use serde::Deserialize; |
| 21 | +/// use serde_roxmltree::{from_doc, RawNode}; |
| 22 | +/// |
| 23 | +/// #[derive(Deserialize)] |
| 24 | +/// struct Record<'a> { |
| 25 | +/// #[serde(borrow)] |
| 26 | +/// subtree: RawNode<'a>, |
| 27 | +/// } |
| 28 | +/// |
| 29 | +/// let document = Document::parse(r#"<document><subtree><field attribute="bar">foo</field></subtree></document>"#)?; |
| 30 | +/// |
| 31 | +/// let record = from_doc::<Record>(&document)?; |
| 32 | +/// assert!(record.subtree.has_tag_name("subtree")); |
| 33 | +/// # |
| 34 | +/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 35 | +/// ``` |
| 36 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 37 | +pub struct RawNode<'a>(pub Node<'a, 'a>); |
| 38 | + |
| 39 | +impl<'a> Deref for RawNode<'a> { |
| 40 | + type Target = Node<'a, 'a>; |
| 41 | + |
| 42 | + fn deref(&self) -> &Self::Target { |
| 43 | + &self.0 |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl<'de, 'a> de::Deserialize<'de> for RawNode<'a> |
| 48 | +where |
| 49 | + 'de: 'a, |
| 50 | +{ |
| 51 | + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 52 | + where |
| 53 | + D: de::Deserializer<'de>, |
| 54 | + { |
| 55 | + struct Visitor<'a>(PhantomData<&'a ()>); |
| 56 | + |
| 57 | + impl<'de, 'a> de::Visitor<'de> for Visitor<'a> |
| 58 | + where |
| 59 | + 'de: 'a, |
| 60 | + { |
| 61 | + type Value = RawNode<'a>; |
| 62 | + |
| 63 | + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 64 | + fmt.write_str("struct RawNode") |
| 65 | + } |
| 66 | + |
| 67 | + fn visit_map<M>(self, _map: M) -> Result<Self::Value, M::Error> |
| 68 | + where |
| 69 | + M: de::MapAccess<'de>, |
| 70 | + { |
| 71 | + match CURR_NODE.get() { |
| 72 | + #[allow(unsafe_code)] |
| 73 | + // SAFETY: This is set only while `deserialize_struct` is active. |
| 74 | + Some(curr_node) => Ok(RawNode(unsafe { |
| 75 | + transmute::<Node<'static, 'static>, Node<'a, 'a>>(curr_node) |
| 76 | + })), |
| 77 | + None => Err(de::Error::custom("no current node")), |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + deserializer.deserialize_struct(RAW_NODE_NAME, &[], Visitor(PhantomData)) |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +pub fn deserialize_struct<'de, 'input, 'temp, O, F, R>( |
| 87 | + this: Deserializer<'de, 'input, 'temp, O>, |
| 88 | + name: &'static str, |
| 89 | + f: F, |
| 90 | +) -> R |
| 91 | +where |
| 92 | + F: FnOnce(Deserializer<'de, 'input, 'temp, O>) -> R, |
| 93 | +{ |
| 94 | + let _reset_curr_node = match &this.source { |
| 95 | + Source::Node(node) if ptr::eq(name, RAW_NODE_NAME) => { |
| 96 | + #[allow(unsafe_code)] |
| 97 | + // SAFETY: The guard will reset this before `deserialize_struct` returns. |
| 98 | + CURR_NODE.set(Some(unsafe { |
| 99 | + transmute::<Node<'de, 'input>, Node<'static, 'static>>(*node) |
| 100 | + })); |
| 101 | + |
| 102 | + Some(ResetCurrNode) |
| 103 | + } |
| 104 | + _ => None, |
| 105 | + }; |
| 106 | + |
| 107 | + f(this) |
| 108 | +} |
| 109 | + |
| 110 | +static RAW_NODE_NAME: &str = "RawNode"; |
| 111 | + |
| 112 | +thread_local! { |
| 113 | + static CURR_NODE: Cell<Option<Node<'static, 'static>>> = const { Cell::new(None) }; |
| 114 | +} |
| 115 | + |
| 116 | +struct ResetCurrNode; |
| 117 | + |
| 118 | +impl Drop for ResetCurrNode { |
| 119 | + fn drop(&mut self) { |
| 120 | + CURR_NODE.set(None); |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +#[cfg(test)] |
| 125 | +mod tests { |
| 126 | + use super::*; |
| 127 | + |
| 128 | + use roxmltree::Document; |
| 129 | + use serde::Deserialize; |
| 130 | + |
| 131 | + use crate::from_doc; |
| 132 | + |
| 133 | + #[test] |
| 134 | + fn raw_node_captures_subtree() { |
| 135 | + #[derive(Debug, Deserialize)] |
| 136 | + struct Root<'a> { |
| 137 | + #[serde(borrow)] |
| 138 | + foo: RawNode<'a>, |
| 139 | + } |
| 140 | + |
| 141 | + let doc = Document::parse(r#"<root><foo><bar qux="42">23</bar>baz</foo></root>"#).unwrap(); |
| 142 | + let val = from_doc::<Root>(&doc).unwrap(); |
| 143 | + |
| 144 | + assert!(val.foo.0.is_element()); |
| 145 | + assert!(val.foo.0.has_tag_name("foo")); |
| 146 | + |
| 147 | + let children = val.foo.0.children().collect::<Vec<_>>(); |
| 148 | + assert_eq!(children.len(), 2); |
| 149 | + assert!(children[0].is_element()); |
| 150 | + assert!(children[0].has_tag_name("bar")); |
| 151 | + assert_eq!(children[0].attribute("qux").unwrap(), "42"); |
| 152 | + assert!(children[1].is_text()); |
| 153 | + assert_eq!(children[1].text().unwrap(), "baz"); |
| 154 | + } |
| 155 | +} |
0 commit comments