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

Add trimming option for the de::from_* functions #561

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
25 changes: 20 additions & 5 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1852,7 +1852,7 @@ use std::io::BufRead;
use std::mem::replace;
#[cfg(feature = "overlapped-lists")]
use std::num::NonZeroUsize;
use std::ops::Deref;
use std::ops::{Deref, Range};

/// Data represented by a text node or a CDATA node. XML markup is not expected
pub(crate) const TEXT_KEY: &str = "$text";
Expand All @@ -1869,7 +1869,24 @@ pub(crate) const VALUE_KEY: &str = "$value";
/// [`PI`]: Event::PI
#[derive(Debug, PartialEq, Eq)]
pub struct Text<'a> {
/// Untrimmed text after concatenating content of all
/// [`Text`] and [`CData`] events
text: Cow<'a, str>,
/// A range into `text` which contains data after trimming
content: Range<usize>,
}

impl<'a> Text<'a> {
fn new(text: Cow<'a, str>) -> Self {
let start = text.find(|c| !char::is_whitespace(c)).unwrap_or(0);
let end = text
.rfind(|c| !char::is_whitespace(c))
.unwrap_or(text.len().saturating_sub(1));
Self {
text,
content: start..end,
}
}
}

impl<'a> Deref for Text<'a> {
Expand All @@ -1884,9 +1901,7 @@ impl<'a> Deref for Text<'a> {
impl<'a> From<&'a str> for Text<'a> {
#[inline]
fn from(text: &'a str) -> Self {
Self {
text: Cow::Borrowed(text),
}
Self::new(Cow::Borrowed(text))
}
}

Expand Down Expand Up @@ -2010,7 +2025,7 @@ impl<'i, R: XmlRead<'i>> XmlReader<'i, R> {
_ => break,
}
}
Ok(DeEvent::Text(Text { text: result }))
Ok(DeEvent::Text(Text::new(result)))
}

/// Read one text event, panics if current event is not a text event
Expand Down