Check character boundaries before comparing string slices

This commit is contained in:
Dirkjan Ochtman 2023-02-21 21:21:15 +01:00
parent 7e05d35ba6
commit 1e5525c9cf
2 changed files with 19 additions and 17 deletions

View File

@ -490,6 +490,7 @@ pub(crate) fn decode(input: &str) -> Cow<'_, str> {
let mut last_end = 0; let mut last_end = 0;
while input_len - last_end >= 4 { while input_len - last_end >= 4 {
if input.is_char_boundary(last_end + 4) {
match &input[last_end..(last_end + 4)] { match &input[last_end..(last_end + 4)] {
"&lt;" => { "&lt;" => {
result.push('<'); result.push('<');
@ -503,15 +504,16 @@ pub(crate) fn decode(input: &str) -> Cow<'_, str> {
} }
_ => (), _ => (),
}; };
}
if input_len - last_end >= 5 { if input_len - last_end >= 5 && input.is_char_boundary(last_end + 5) {
if &input[last_end..(last_end + 5)] == "&amp;" { if &input[last_end..(last_end + 5)] == "&amp;" {
result.push('&'); result.push('&');
last_end += 5; last_end += 5;
continue; continue;
} }
if input_len - last_end >= 6 { if input_len - last_end >= 6 && input.is_char_boundary(last_end + 6) {
match &input[last_end..(last_end + 6)] { match &input[last_end..(last_end + 6)] {
"&apos;" => { "&apos;" => {
result.push('\''); result.push('\'');

View File

@ -14,9 +14,9 @@ struct Foo {
fn direct() { fn direct() {
let v = Foo { let v = Foo {
flag: true, flag: true,
inner: "hello".to_string(), inner: "cbdté".to_string(),
}; };
let xml = "<Foo flag=\"true\">hello</Foo>"; let xml = "<Foo flag=\"true\">cbdté</Foo>";
assert_eq!(to_string(&v).unwrap(), xml); assert_eq!(to_string(&v).unwrap(), xml);
assert_eq!(from_str::<Foo>(xml), Ok(v)); assert_eq!(from_str::<Foo>(xml), Ok(v));