Skip to content

Commit

Permalink
Add helper to decoder Cow data, which retains original lifetime
Browse files Browse the repository at this point in the history
  • Loading branch information
Mingun committed Jun 28, 2024
1 parent 42d7123 commit 80bf12d
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 15 deletions.
9 changes: 9 additions & 0 deletions src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,15 @@ impl Decoder {

Ok(())
}

/// Decodes the `Cow` buffer, preserves the lifetime
pub(crate) fn decode_cow<'b>(&self, bytes: &Cow<'b, [u8]>) -> Result<Cow<'b, str>> {
match bytes {
Cow::Borrowed(bytes) => self.decode(bytes),
// Convert to owned, because otherwise Cow will be bound with wrong lifetime
Cow::Owned(bytes) => Ok(self.decode(bytes)?.into_owned().into()),
}
}
}

/// Decodes the provided bytes using the specified encoding.
Expand Down
6 changes: 1 addition & 5 deletions src/events/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,7 @@ impl<'a> Attribute<'a> {
decoder: Decoder,
resolve_entity: impl FnMut(&str) -> Option<&'entity str>,
) -> XmlResult<Cow<'a, str>> {
let decoded = match &self.value {
Cow::Borrowed(bytes) => decoder.decode(bytes)?,
// Convert to owned, because otherwise Cow will be bound with wrong lifetime
Cow::Owned(bytes) => decoder.decode(bytes)?.into_owned().into(),
};
let decoded = decoder.decode_cow(&self.value)?;

match unescape_with(&decoded, resolve_entity)? {
// Because result is borrowed, no replacements was done and we can use original string
Expand Down
12 changes: 2 additions & 10 deletions src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,11 +595,7 @@ impl<'a> BytesText<'a> {
&self,
resolve_entity: impl FnMut(&str) -> Option<&'entity str>,
) -> Result<Cow<'a, str>> {
let decoded = match &self.content {
Cow::Borrowed(bytes) => self.decoder.decode(bytes)?,
// Convert to owned, because otherwise Cow will be bound with wrong lifetime
Cow::Owned(bytes) => self.decoder.decode(bytes)?.into_owned().into(),
};
let decoded = self.decoder.decode_cow(&self.content)?;

match unescape_with(&decoded, resolve_entity)? {
// Because result is borrowed, no replacements was done and we can use original string
Expand Down Expand Up @@ -810,11 +806,7 @@ impl<'a> BytesCData<'a> {

/// Gets content of this text buffer in the specified encoding
pub(crate) fn decode(&self) -> Result<Cow<'a, str>> {
Ok(match &self.content {
Cow::Borrowed(bytes) => self.decoder.decode(bytes)?,
// Convert to owned, because otherwise Cow will be bound with wrong lifetime
Cow::Owned(bytes) => self.decoder.decode(bytes)?.into_owned().into(),
})
self.decoder.decode_cow(&self.content)
}
}

Expand Down

0 comments on commit 80bf12d

Please sign in to comment.