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;
while input_len - last_end >= 4 {
if input.is_char_boundary(last_end + 4) {
match &input[last_end..(last_end + 4)] {
"&lt;" => {
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;" {
result.push('&');
last_end += 5;
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)] {
"&apos;" => {
result.push('\'');

View File

@ -14,9 +14,9 @@ struct Foo {
fn direct() {
let v = Foo {
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!(from_str::<Foo>(xml), Ok(v));