From 2b333ce579e2ace07d270639a0573b162c7c4f15 Mon Sep 17 00:00:00 2001 From: Emmanuel Gil Peyrot Date: Wed, 24 Jul 2024 17:47:35 +0200 Subject: [PATCH] xso: Add an EmptyAsError text codec As its name implies, this codec emits an error when the parsed string is empty. --- xso/src/text.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/xso/src/text.rs b/xso/src/text.rs index 70ef9131..988a7d60 100644 --- a/xso/src/text.rs +++ b/xso/src/text.rs @@ -171,6 +171,27 @@ impl TextCodec> for EmptyAsNone { } } +/// Text codec which returns None instead of the empty string. +pub struct EmptyAsError; + +impl TextCodec for EmptyAsError { + fn decode(s: String) -> Result { + if s.is_empty() { + Err(Error::Other("Empty text node.")) + } else { + Ok(s) + } + } + + fn encode(value: &String) -> Result>, Error> { + if value.is_empty() { + Err(Error::Other("Empty text node.")) + } else { + Ok(Some(Cow::Borrowed(value.as_str()))) + } + } +} + /// Trait for preprocessing text data from XML. /// /// This may be used by codecs to allow to customize some of their behaviour.