Skip to content

Commit 401bb77

Browse files
committed
Properly normalize attribute values
closes tafia#371
1 parent 8a74258 commit 401bb77

File tree

1 file changed

+119
-1
lines changed

1 file changed

+119
-1
lines changed

src/events/attributes.rs

Lines changed: 119 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,97 @@ impl<'a> From<(&'a str, &'a str)> for Attribute<'a> {
331331
}
332332
}
333333

334+
///
335+
///
336+
/// 1) All line breaks MUST have been normalized on input to #xA as described in 2.11 End-of-Line Handling, so the rest of this algorithm operates on text normalized in this way.
337+
/// 2) Begin with a normalized value consisting of the empty string.
338+
/// 3) For each character, entity reference, or character reference in the unnormalized attribute value, beginning with the first and continuing to the last, do the following:
339+
/// * For a character reference, append the referenced character to the normalized value.
340+
/// * For an entity reference, recursively apply step 3 of this algorithm to the replacement text of the entity.
341+
/// * For a white space character (#x20, #xD, #xA, #x9), append a space character (#x20) to the normalized value.
342+
/// * For another character, append the character to the normalized value.
343+
///
344+
/// If the attribute type is not CDATA, then the XML processor MUST further process the normalized attribute value by discarding any leading and trailing space (#x20) characters,
345+
/// and by replacing sequences of space (#x20) characters by a single space (#x20) character.
346+
///
347+
/// Note that if the unnormalized attribute value contains a character reference to a white space character other than space (#x20), the normalized value contains the referenced
348+
/// character itself (#xD, #xA or #x9). This contrasts with the case where the unnormalized value contains a white space character (not a reference), which is replaced with a
349+
/// space character (#x20) in the normalized value and also contrasts with the case where the unnormalized value contains an entity reference whose replacement text contains a
350+
/// white space character; being recursively processed, the white space character is replaced with a space character (#x20) in the normalized value.
351+
fn normalize_attribute_value(attr: &[u8]) -> Cow<[u8]> {
352+
// TODO: character references, entity references, error handling associated with those
353+
354+
#[derive(PartialEq)]
355+
enum ParseState {
356+
Space,
357+
CDATA,
358+
}
359+
360+
let is_whitespace_like = |c| matches!(c, b'\n' | b'\r' | b'\t' | b' ');
361+
362+
let first_non_space_char = attr.iter().position(|c| !is_whitespace_like(*c));
363+
364+
if first_non_space_char.is_none() {
365+
// The entire value was whitespace-like characters
366+
return Cow::Borrowed(b"");
367+
}
368+
369+
let last_non_space_char = attr.iter().rposition(|c| !is_whitespace_like(*c));
370+
371+
// Trim all whitespace-like characters away from the beginning and end of the attribute value.
372+
let begin = first_non_space_char.unwrap();
373+
let end = last_non_space_char.unwrap_or(attr.len());
374+
let trimmed_attr = &attr[begin..=end];
375+
376+
// A new buffer is only created when we encounter a situation that requires it.
377+
let mut normalized: Option<Vec<u8>> = None;
378+
// We start on character data because all whitespace-like characters are already trimmed away.
379+
let mut current_state = ParseState::CDATA;
380+
381+
// Perform a single pass over the trimmed attribute value. If we encounter a character / entity reference
382+
// or whitespace-like characters that need to be substituted, copy everything processed thus far to a new
383+
// buffer and continue using this buffer.
384+
for (idx, ch) in trimmed_attr.iter().enumerate() {
385+
match ch {
386+
b'\n' | b'\r' | b'\t' | b' ' => match current_state {
387+
ParseState::Space => match normalized {
388+
Some(_) => continue,
389+
None => normalized = Some(Vec::from(&trimmed_attr[..idx])),
390+
},
391+
ParseState::CDATA => {
392+
current_state = ParseState::Space;
393+
match normalized.as_mut() {
394+
Some(buf) => buf.push(b' '),
395+
None => {
396+
let mut buf = Vec::from(&trimmed_attr[..idx]);
397+
buf.push(b' ');
398+
normalized = Some(buf);
399+
}
400+
}
401+
}
402+
},
403+
c @ _ => match current_state {
404+
ParseState::Space => {
405+
current_state = ParseState::CDATA;
406+
if let Some(normalized) = normalized.as_mut() {
407+
normalized.push(*c);
408+
}
409+
}
410+
ParseState::CDATA => {
411+
if let Some(normalized) = normalized.as_mut() {
412+
normalized.push(*c);
413+
}
414+
}
415+
},
416+
}
417+
}
418+
419+
match normalized {
420+
Some(normalized) => Cow::Owned(normalized),
421+
None => Cow::Borrowed(trimmed_attr),
422+
}
423+
}
424+
334425
impl<'a> Iterator for Attributes<'a> {
335426
type Item = Result<Attribute<'a>>;
336427
fn next(&mut self) -> Option<Self::Item> {
@@ -355,7 +446,7 @@ impl<'a> Iterator for Attributes<'a> {
355446
($key:expr, $val:expr) => {
356447
Some(Ok(Attribute {
357448
key: &self.bytes[$key],
358-
value: Cow::Borrowed(&self.bytes[$val]),
449+
value: normalize_attribute_value(&self.bytes[$val]),
359450
}))
360451
};
361452
}
@@ -513,4 +604,31 @@ mod tests {
513604
assert_eq!(&*a.value, b"ee");
514605
assert!(attributes.next().is_none());
515606
}
607+
608+
#[test]
609+
fn attribute_value_normalization() {
610+
// empty value
611+
assert_eq!(normalize_attribute_value(b"").as_ref(), b"");
612+
// return, tab, and newline characters (0xD, 0x9, 0xA) must be replaced with a space character
613+
assert_eq!(
614+
normalize_attribute_value(b"\rfoo\rbar\tbaz\ndelta\n").as_ref(),
615+
b"foo bar baz delta"
616+
);
617+
// leading and trailing spaces must be stripped
618+
assert_eq!(normalize_attribute_value(b" foo ").as_ref(), b"foo");
619+
// leading space
620+
assert_eq!(normalize_attribute_value(b" bar").as_ref(), b"bar");
621+
// trailing space
622+
assert_eq!(normalize_attribute_value(b"baz ").as_ref(), b"baz");
623+
// sequences of spaces must be replaced with a single space
624+
assert_eq!(
625+
normalize_attribute_value(b" foo bar baz ").as_ref(),
626+
b"foo bar baz"
627+
);
628+
// sequence replacement mixed with characters treated as whitespace (\t \r \n)
629+
assert_eq!(
630+
normalize_attribute_value(b" \tfoo\tbar \rbaz \n\ndelta\n\t\r echo foxtrot\r").as_ref(),
631+
b"foo bar baz delta echo foxtrot"
632+
);
633+
}
516634
}

0 commit comments

Comments
 (0)