Skip to content

Commit ce7d3d4

Browse files
committed
Properly normalize attribute values
closes tafia#371
1 parent d872771 commit ce7d3d4

File tree

1 file changed

+137
-1
lines changed

1 file changed

+137
-1
lines changed

src/events/attributes.rs

+137-1
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,96 @@ impl<'a> From<(&'a str, &'a str)> for Attribute<'a> {
331331
}
332332
}
333333

334+
// 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.
335+
// 2) Begin with a normalized value consisting of the empty string.
336+
// 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:
337+
// * For a character reference, append the referenced character to the normalized value.
338+
// * For an entity reference, recursively apply step 3 of this algorithm to the replacement text of the entity.
339+
// * For a white space character (#x20, #xD, #xA, #x9), append a space character (#x20) to the normalized value.
340+
// * For another character, append the character to the normalized value.
341+
//
342+
// 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,
343+
// and by replacing sequences of space (#x20) characters by a single space (#x20) character.
344+
//
345+
// 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
346+
// 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
347+
// 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
348+
// white space character; being recursively processed, the white space character is replaced with a space character (#x20) in the normalized value.
349+
fn normalize_attribute_value(attr: Cow<[u8]>) -> Cow<[u8]> {
350+
// TODO: character references, entity references
351+
// TODO: don't allocated unless needed?
352+
353+
#[derive(PartialEq)]
354+
enum ParseState {
355+
SpaceOrStart,
356+
CDATA,
357+
}
358+
359+
let mut value: Vec<u8> = Vec::new();
360+
// Starting in the state where we think we've added a space means we implicitly skip leading spaces
361+
let mut current_state = ParseState::SpaceOrStart;
362+
// Used for trimming trailing spaces
363+
let mut last_cdata_idx = 0;
364+
365+
// In one pass, strip leading and trailing spaces and replace sequences of spaces with a single one
366+
for ch in attr.as_ref() {
367+
match current_state {
368+
ParseState::SpaceOrStart => match ch {
369+
b'\n' | b'\r' | b'\t' | b' ' => continue,
370+
c @ _ => {
371+
current_state = ParseState::CDATA;
372+
last_cdata_idx = value.len();
373+
value.push(*c);
374+
}
375+
},
376+
ParseState::CDATA => match ch {
377+
b'\n' | b'\r' | b'\t' | b' ' => {
378+
current_state = ParseState::SpaceOrStart;
379+
value.push(b' ');
380+
}
381+
c @ _ => {
382+
last_cdata_idx = value.len();
383+
value.push(*c)
384+
}
385+
},
386+
}
387+
}
388+
389+
// Trim any trailing spaces
390+
if current_state == ParseState::SpaceOrStart {
391+
value.truncate(last_cdata_idx + 1);
392+
}
393+
394+
Cow::Owned(value)
395+
396+
397+
// let mut value: Vec<u8> = Vec::new();
398+
399+
// // TODO: replace sequences of spaces
400+
// for i in 0..attr.len() {
401+
// let ch = attr[i];
402+
// match ch {
403+
// b'\n' => value.push(b' '),
404+
// b'\r' => value.push(b' '),
405+
// b'\t' => value.push(b' '),
406+
// c @ _ => value.push(c),
407+
// }
408+
// }
409+
410+
// // Position where value starts after whitespace.
411+
// let first_non_space_char = value
412+
// .iter()
413+
// .position(|c| !c.is_ascii_whitespace())
414+
// .unwrap_or(0);
415+
// // Position where the trailing whitespace starts.
416+
// let last_non_space_char = value
417+
// .iter()
418+
// .rposition(|c| !c.is_ascii_whitespace())
419+
// .and_then(|idx| Some(idx + 1))
420+
// .unwrap_or(0);
421+
// Cow::Owned(value[first_non_space_char..last_non_space_char].to_vec())
422+
}
423+
334424
impl<'a> Iterator for Attributes<'a> {
335425
type Item = Result<Attribute<'a>>;
336426
fn next(&mut self) -> Option<Self::Item> {
@@ -355,7 +445,7 @@ impl<'a> Iterator for Attributes<'a> {
355445
($key:expr, $val:expr) => {
356446
Some(Ok(Attribute {
357447
key: &self.bytes[$key],
358-
value: Cow::Borrowed(&self.bytes[$val]),
448+
value: normalize_attribute_value(Cow::Borrowed(&self.bytes[$val])),
359449
}))
360450
};
361451
}
@@ -460,6 +550,52 @@ mod tests {
460550
assert!(attributes.next().is_none());
461551
}
462552

553+
#[test]
554+
fn attribute_value_normalization() {
555+
let event = b"a attr=\"tab character\tor newline\nor return\rshould be replaced\"";
556+
let mut attributes = Attributes::new(event, 0);
557+
attributes.with_checks(true);
558+
let a = attributes.next().unwrap().unwrap();
559+
assert_eq!(
560+
a.value.as_ref(),
561+
b"tab character or newline or return should be replaced"
562+
);
563+
}
564+
565+
#[test]
566+
fn test_normalize_attribute_value() {
567+
// return, tab, and newline characters (0xD, 0x9, 0xA) must be replaced with a space character
568+
assert_eq!(
569+
normalize_attribute_value(Cow::Borrowed(b"\rfoo\rbar\tbaz\ndelta\n")).as_ref(),
570+
b"foo bar baz delta"
571+
);
572+
// leading and trailing spaces must be stripped
573+
assert_eq!(
574+
normalize_attribute_value(Cow::Borrowed(b" foo ")).as_ref(),
575+
b"foo"
576+
);
577+
// leading space
578+
assert_eq!(
579+
normalize_attribute_value(Cow::Borrowed(b" bar")).as_ref(),
580+
b"bar"
581+
);
582+
// trailing space
583+
assert_eq!(
584+
normalize_attribute_value(Cow::Borrowed(b"baz ")).as_ref(),
585+
b"baz"
586+
);
587+
// sequences of spaces must be replaced with a single space
588+
assert_eq!(
589+
normalize_attribute_value(Cow::Borrowed(b" foo bar baz ")).as_ref(),
590+
b"foo bar baz"
591+
);
592+
// sequence replacement including whitespace alias characters
593+
assert_eq!(
594+
normalize_attribute_value(Cow::Borrowed(b" \tfoo\tbar \rbaz \n\ndelta\n")).as_ref(),
595+
b"foo bar baz delta"
596+
);
597+
}
598+
463599
#[test]
464600
fn mixed_quote() {
465601
let event = b"name a='a' b = \"b\" c='cc\"cc'";

0 commit comments

Comments
 (0)