Skip to content

Commit 81d63a4

Browse files
committed
Change API for providing custom entities
Instead of providing unescaping functions with an entity mapping via a data structure, instead provide a closure which maps the entity with replacement text.
1 parent 57cd104 commit 81d63a4

File tree

6 files changed

+81
-127
lines changed

6 files changed

+81
-127
lines changed

Changelog.md

+3
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@
107107
|`read_event_unbuffered` |`read_event`
108108
|`read_to_end_unbuffered` |`read_to_end`
109109
- [#412]: Change `read_to_end*` and `read_text_into` to accept `QName` instead of `AsRef<[u8]>`
110+
- [#415]: Changed custom entity unescaping API to accept closures rather than a mapping of entity to
111+
replacement text. This avoids needing to allocate a map and provides the user with more flexibility.
110112

111113
### New Tests
112114

@@ -131,6 +133,7 @@
131133
[#403]: https://github.com/tafia/quick-xml/pull/403
132134
[#407]: https://github.com/tafia/quick-xml/pull/407
133135
[#412]: https://github.com/tafia/quick-xml/pull/412
136+
[#415]: https://github.com/tafia/quick-xml/pull/415
134137

135138
## 0.23.0 -- 2022-05-08
136139

examples/custom_entities.rs

+21-16
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@
77
//! * the regex in this example is simple but brittle;
88
//! * it does not support the use of entities in entity declaration.
99
10+
use std::collections::HashMap;
11+
1012
use quick_xml::events::Event;
1113
use quick_xml::Reader;
1214
use regex::bytes::Regex;
13-
use std::collections::HashMap;
1415

1516
const DATA: &str = r#"
1617
@@ -27,35 +28,39 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
2728
reader.trim_text(true);
2829

2930
let mut buf = Vec::new();
30-
let mut custom_entities = HashMap::new();
31+
let mut custom_entities: HashMap<Vec<u8>, String> = HashMap::new();
3132
let entity_re = Regex::new(r#"<!ENTITY\s+([^ \t\r\n]+)\s+"([^"]*)"\s*>"#)?;
3233

3334
loop {
3435
match reader.read_event_into(&mut buf) {
3536
Ok(Event::DocType(ref e)) => {
3637
for cap in entity_re.captures_iter(&e) {
37-
custom_entities.insert(cap[1].to_vec(), cap[2].to_vec());
38+
custom_entities.insert(cap[1].to_vec(), String::from_utf8(cap[2].to_vec())?);
3839
}
3940
}
4041
Ok(Event::Start(ref e)) => match e.name().as_ref() {
41-
b"test" => println!(
42-
"attributes values: {:?}",
43-
e.attributes()
44-
.map(|a| a
45-
.unwrap()
46-
.unescape_and_decode_value_with_custom_entities(
47-
&reader,
48-
&custom_entities
49-
)
50-
.unwrap())
51-
.collect::<Vec<_>>()
52-
),
42+
b"test" => {
43+
let lookup_custom_entity = |ent| custom_entities.get(ent).map(|s| s.as_str());
44+
let attributes = e
45+
.attributes()
46+
.map(|a| {
47+
a.unwrap()
48+
.unescape_and_decode_value_with_custom_entities(
49+
&reader,
50+
lookup_custom_entity,
51+
)
52+
.unwrap()
53+
})
54+
.collect::<Vec<_>>();
55+
println!("attributes values: {:?}", attributes);
56+
}
5357
_ => (),
5458
},
5559
Ok(Event::Text(ref e)) => {
60+
let lookup_custom_entity = |ent| custom_entities.get(ent).map(|s| s.as_str());
5661
println!(
5762
"text value: {}",
58-
e.unescape_and_decode_with_custom_entities(&reader, &custom_entities)
63+
e.unescape_and_decode_with_custom_entities(&reader, lookup_custom_entity)
5964
.unwrap()
6065
);
6166
}

src/escapei.rs

+30-53
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
33
use memchr;
44
use std::borrow::Cow;
5-
use std::collections::HashMap;
65
use std::ops::Range;
76

87
#[cfg(test)]
@@ -66,31 +65,15 @@ impl std::error::Error for EscapeError {}
6665
/// Escapes a `&[u8]` and replaces all xml special characters (<, >, &, ', ") with their
6766
/// corresponding xml escaped value.
6867
pub fn escape(raw: &[u8]) -> Cow<[u8]> {
69-
#[inline]
70-
fn to_escape(b: u8) -> bool {
71-
match b {
72-
b'<' | b'>' | b'\'' | b'&' | b'"' => true,
73-
_ => false,
74-
}
75-
}
76-
77-
_escape(raw, to_escape)
68+
_escape(raw, |ch| matches!(ch, b'<' | b'>' | b'&' | b'\'' | b'\"'))
7869
}
7970

8071
/// Should only be used for escaping text content. In xml text content, it is allowed
8172
/// (though not recommended) to leave the quote special characters " and ' unescaped.
8273
/// This function escapes a `&[u8]` and replaces xml special characters (<, >, &) with
8374
/// their corresponding xml escaped value, but does not escape quote characters.
8475
pub fn partial_escape(raw: &[u8]) -> Cow<[u8]> {
85-
#[inline]
86-
fn to_escape(b: u8) -> bool {
87-
match b {
88-
b'<' | b'>' | b'&' => true,
89-
_ => false,
90-
}
91-
}
92-
93-
_escape(raw, to_escape)
76+
_escape(raw, |ch| matches!(ch, b'<' | b'>' | b'&'))
9477
}
9578

9679
/// Escapes a `&[u8]` and replaces a subset of xml special characters (<, >, &, ', ") with their
@@ -130,32 +113,22 @@ fn _escape<F: Fn(u8) -> bool>(raw: &[u8], escape_chars: F) -> Cow<[u8]> {
130113
/// Unescape a `&[u8]` and replaces all xml escaped characters ('&...;') into their corresponding
131114
/// value
132115
pub fn unescape(raw: &[u8]) -> Result<Cow<[u8]>, EscapeError> {
133-
do_unescape(raw, None)
116+
unescape_with(raw, |_| None)
134117
}
135118

136119
/// Unescape a `&[u8]` and replaces all xml escaped characters ('&...;') into their corresponding
137-
/// value, using a dictionnary of custom entities.
120+
/// value, using a dictionary of custom entities.
138121
///
139122
/// # Pre-condition
140123
///
141-
/// The keys and values of `custom_entities`, if any, must be valid UTF-8.
142-
pub fn unescape_with<'a>(
124+
/// The implementation of `lookup_custom_entity` is expected to operate over UTF-8 inputs.
125+
pub fn unescape_with<'a, 'b>(
143126
raw: &'a [u8],
144-
custom_entities: &HashMap<Vec<u8>, Vec<u8>>,
145-
) -> Result<Cow<'a, [u8]>, EscapeError> {
146-
do_unescape(raw, Some(custom_entities))
147-
}
148-
149-
/// Unescape a `&[u8]` and replaces all xml escaped characters ('&...;') into their corresponding
150-
/// value, using an optional dictionary of custom entities.
151-
///
152-
/// # Pre-condition
153-
///
154-
/// The keys and values of `custom_entities`, if any, must be valid UTF-8.
155-
pub fn do_unescape<'a>(
156-
raw: &'a [u8],
157-
custom_entities: Option<&HashMap<Vec<u8>, Vec<u8>>>,
158-
) -> Result<Cow<'a, [u8]>, EscapeError> {
127+
lookup_custom_entity: impl Fn(&'b [u8]) -> Option<&'b str>,
128+
) -> Result<Cow<'a, [u8]>, EscapeError>
129+
where
130+
'a: 'b,
131+
{
159132
let mut unescaped = None;
160133
let mut last_end = 0;
161134
let mut iter = memchr::memchr2_iter(b'&', b';', raw);
@@ -171,12 +144,14 @@ pub fn do_unescape<'a>(
171144

172145
// search for character correctness
173146
let pat = &raw[start + 1..end];
174-
if let Some(s) = named_entity(pat) {
175-
unescaped.extend_from_slice(s.as_bytes());
176-
} else if pat.starts_with(b"#") {
177-
push_utf8(unescaped, parse_number(&pat[1..], start..end)?);
178-
} else if let Some(value) = custom_entities.and_then(|hm| hm.get(pat)) {
179-
unescaped.extend_from_slice(&value);
147+
if pat.starts_with(b"#") {
148+
let entity = &pat[1..]; // starts after the #
149+
let codepoint = parse_number(entity, start..end)?;
150+
push_utf8(unescaped, codepoint);
151+
} else if let Some(value) = named_entity(pat) {
152+
unescaped.extend_from_slice(value.as_bytes());
153+
} else if let Some(value) = lookup_custom_entity(pat) {
154+
unescaped.extend_from_slice(value.as_bytes());
180155
} else {
181156
return Err(EscapeError::UnrecognizedSymbol(
182157
start + 1..end,
@@ -1740,18 +1715,20 @@ fn test_unescape() {
17401715

17411716
#[test]
17421717
fn test_unescape_with() {
1743-
let custom_entities = vec![(b"foo".to_vec(), b"BAR".to_vec())]
1744-
.into_iter()
1745-
.collect();
1746-
assert_eq!(&*unescape_with(b"test", &custom_entities).unwrap(), b"test");
1718+
let custom_entities = |ent: &[u8]| match ent {
1719+
b"foo" => Some("BAR"),
1720+
_ => None,
1721+
};
1722+
1723+
assert_eq!(&*unescape_with(b"test", custom_entities).unwrap(), b"test");
17471724
assert_eq!(
1748-
&*unescape_with(b"&lt;test&gt;", &custom_entities).unwrap(),
1725+
&*unescape_with(b"&lt;test&gt;", custom_entities).unwrap(),
17491726
b"<test>"
17501727
);
1751-
assert_eq!(&*unescape_with(b"&#x30;", &custom_entities).unwrap(), b"0");
1752-
assert_eq!(&*unescape_with(b"&#48;", &custom_entities).unwrap(), b"0");
1753-
assert_eq!(&*unescape_with(b"&foo;", &custom_entities).unwrap(), b"BAR");
1754-
assert!(unescape_with(b"&fop;", &custom_entities).is_err());
1728+
assert_eq!(&*unescape_with(b"&#x30;", custom_entities).unwrap(), b"0");
1729+
assert_eq!(&*unescape_with(b"&#48;", custom_entities).unwrap(), b"0");
1730+
assert_eq!(&*unescape_with(b"&foo;", custom_entities).unwrap(), b"BAR");
1731+
assert!(unescape_with(b"&fop;", custom_entities).is_err());
17551732
}
17561733

17571734
#[test]

src/events/attributes.rs

+11-28
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
//! Provides an iterator over attributes key/value pairs
44
55
use crate::errors::{Error, Result as XmlResult};
6-
use crate::escape::{do_unescape, escape};
6+
use crate::escape::{escape, unescape_with};
77
use crate::name::QName;
88
use crate::reader::{is_whitespace, Reader};
99
use crate::utils::{write_byte_string, write_cow_string, Bytes};
1010
use std::fmt::{self, Debug, Display, Formatter};
1111
use std::iter::FusedIterator;
12-
use std::{borrow::Cow, collections::HashMap, ops::Range};
12+
use std::{borrow::Cow, ops::Range};
1313

1414
/// A struct representing a key/value XML attribute.
1515
///
@@ -41,7 +41,7 @@ impl<'a> Attribute<'a> {
4141
///
4242
/// See also [`unescaped_value_with_custom_entities()`](#method.unescaped_value_with_custom_entities)
4343
pub fn unescaped_value(&self) -> XmlResult<Cow<[u8]>> {
44-
self.make_unescaped_value(None)
44+
self.unescaped_value_with_custom_entities(|_| None)
4545
}
4646

4747
/// Returns the unescaped value, using custom entities.
@@ -57,18 +57,11 @@ impl<'a> Attribute<'a> {
5757
/// # Pre-condition
5858
///
5959
/// The keys and values of `custom_entities`, if any, must be valid UTF-8.
60-
pub fn unescaped_value_with_custom_entities(
61-
&self,
62-
custom_entities: &HashMap<Vec<u8>, Vec<u8>>,
63-
) -> XmlResult<Cow<[u8]>> {
64-
self.make_unescaped_value(Some(custom_entities))
65-
}
66-
67-
fn make_unescaped_value(
68-
&self,
69-
custom_entities: Option<&HashMap<Vec<u8>, Vec<u8>>>,
70-
) -> XmlResult<Cow<[u8]>> {
71-
do_unescape(&*self.value, custom_entities).map_err(Error::EscapeError)
60+
pub fn unescaped_value_with_custom_entities<'s>(
61+
&'s self,
62+
lookup_custom_entity: impl Fn(&[u8]) -> Option<&str>,
63+
) -> XmlResult<Cow<'s, [u8]>> {
64+
unescape_with(&*self.value, lookup_custom_entity).map_err(Error::EscapeError)
7265
}
7366

7467
/// Decode then unescapes the value
@@ -82,7 +75,7 @@ impl<'a> Attribute<'a> {
8275
/// [`unescaped_value()`]: #method.unescaped_value
8376
/// [`Reader::decode()`]: ../../reader/struct.Reader.html#method.decode
8477
pub fn unescape_and_decode_value<B>(&self, reader: &Reader<B>) -> XmlResult<String> {
85-
self.do_unescape_and_decode_value(reader, None)
78+
self.unescape_and_decode_value_with_custom_entities(reader, |_| None)
8679
}
8780

8881
/// Decode then unescapes the value with custom entities
@@ -102,20 +95,10 @@ impl<'a> Attribute<'a> {
10295
pub fn unescape_and_decode_value_with_custom_entities<B>(
10396
&self,
10497
reader: &Reader<B>,
105-
custom_entities: &HashMap<Vec<u8>, Vec<u8>>,
106-
) -> XmlResult<String> {
107-
self.do_unescape_and_decode_value(reader, Some(custom_entities))
108-
}
109-
110-
/// The keys and values of `custom_entities`, if any, must be valid UTF-8.
111-
fn do_unescape_and_decode_value<B>(
112-
&self,
113-
reader: &Reader<B>,
114-
custom_entities: Option<&HashMap<Vec<u8>, Vec<u8>>>,
98+
lookup_custom_entity: impl Fn(&[u8]) -> Option<&str>,
11599
) -> XmlResult<String> {
116100
let decoded = reader.decoder().decode(&*self.value)?;
117-
118-
let unescaped = do_unescape(decoded.as_bytes(), custom_entities)?;
101+
let unescaped = unescape_with(decoded.as_bytes(), lookup_custom_entity)?;
119102
Ok(String::from_utf8(unescaped.into_owned())?)
120103
}
121104
}

0 commit comments

Comments
 (0)