Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix UTF-8 decoding errors #2

Merged
merged 1 commit into from
Mar 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Handle UTF-8 decoding issues without a panic, fixing [#1](https://github.com/georust/kml/issues/1)

## [v0.3.0](https://github.com/georust/kml/releases/tag/v0.3.0)

- Cleaned up method names (i.e. "parse*" to "read*")
Expand Down
34 changes: 30 additions & 4 deletions src/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,10 @@ where
.push(self.read_element(&start, start_attrs)?);
}
Event::Text(ref mut e) => {
element.content = Some(e.unescape_and_decode(&self.reader).expect("Error"))
element.content = Some(
e.unescape_and_decode(&self.reader)
.unwrap_or_else(|_| String::from_utf8_lossy(e.escaped()).to_string()),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems reasonable!

)
}
Event::End(ref mut e) => {
if e.local_name() == tag {
Expand Down Expand Up @@ -747,9 +750,9 @@ where
fn read_str(&mut self) -> Result<String, Error> {
let e = self.reader.read_event(&mut self.buf)?;
match e {
Event::Text(e) | Event::CData(e) => {
Ok(e.unescape_and_decode(&self.reader).expect("Error"))
}
Event::Text(e) | Event::CData(e) => Ok(e
.unescape_and_decode(&self.reader)
.unwrap_or_else(|_| String::from_utf8_lossy(e.escaped()).to_string())),
Event::End(_) => Ok("".to_string()),
e => Err(Error::InvalidXmlEvent(format!("{:?}", e))),
}
Expand Down Expand Up @@ -928,6 +931,29 @@ mod tests {
}))
}

#[test]
fn test_read_str_lossy() {
let kml_str = r#"
<Placemark>
<name><![CDATA[Test & Test]]></name>
<description>1¼ miles</description>
<Point>
<coordinates>
-1.0,1.0,0
</coordinates>
</Point>
</Placemark>"#;
let p: Kml = kml_str.parse().unwrap();
assert!(matches!(p, Kml::Placemark(_)));
let placemark: Placemark = match p {
Kml::Placemark(p) => Some(p),
_ => None,
}
.unwrap();
assert_eq!(placemark.name, Some("Test & Test".to_string()));
assert_eq!(placemark.description, Some("1¼ miles".to_string()));
}

#[test]
fn test_parse() {
let kml_str = include_str!("../tests/fixtures/sample.kml");
Expand Down