From fce846ae3d0440d10e0fd0e0d5539feafef891a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Sch=C3=A4fer?= Date: Wed, 24 Jul 2024 16:09:02 +0200 Subject: [PATCH] xso: refactor Base64 text codec This introduces support for `Cow<'_, [u8]>` (which is not needed currently, but still good to have) and generalizes the `Option` implementation so that it doesn't have to be copied for every other type supported to be Base64'd (we may add support for `bytes::Bytes` at some point, for instance). --- xso/src/text.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/xso/src/text.rs b/xso/src/text.rs index bb142a8b..483b97b1 100644 --- a/xso/src/text.rs +++ b/xso/src/text.rs @@ -256,15 +256,34 @@ impl TextCodec> for Base64 { #[cfg(feature = "base64")] #[cfg_attr(docsrs, doc(cfg(feature = "base64")))] -impl TextCodec>> for Base64 { - fn decode(s: String) -> Result>, Error> { +impl<'x, Filter: TextFilter> TextCodec> for Base64 { + fn decode(s: String) -> Result, Error> { + let value = Filter::preprocess(s); + StandardBase64Engine + .decode(value.as_bytes()) + .map_err(Error::text_parse_error) + .map(Cow::Owned) + } + + fn encode<'a>(value: &'a Cow<'x, [u8]>) -> Result>, Error> { + Ok(Some(Cow::Owned(StandardBase64Engine.encode(&value)))) + } +} + +#[cfg(feature = "base64")] +#[cfg_attr(docsrs, doc(cfg(feature = "base64")))] +impl TextCodec> for Base64 +where + Base64: TextCodec, +{ + fn decode(s: String) -> Result, Error> { if s.is_empty() { return Ok(None); } Ok(Some(Self::decode(s)?)) } - fn encode(decoded: &Option>) -> Result>, Error> { + fn encode(decoded: &Option) -> Result>, Error> { decoded .as_ref() .map(Self::encode)