From a3d44485f4050e74661b5a8e9c791230775b3ac7 Mon Sep 17 00:00:00 2001 From: Yuya Nishihara Date: Thu, 21 Mar 2024 11:38:23 +0900 Subject: [PATCH] templater: add helper methods to map property like Option/Result These two are common when implementing methods. Fortunately, the "return-position impl Trait in traits" feature is stabilized in Rust 1.75.0, so we don't need another variant of TemplateFunction. --- cli/src/templater.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/cli/src/templater.rs b/cli/src/templater.rs index 581ec561a..ec3f580cd 100644 --- a/cli/src/templater.rs +++ b/cli/src/templater.rs @@ -330,6 +330,31 @@ tuple_impls! { (0 T0, 1 T1, 2 T2, 3 T3) } +/// `TemplateProperty` adapters that are useful when implementing methods. +pub trait TemplatePropertyExt: TemplateProperty { + /// Translates to a property that will apply fallible `function` to an + /// extracted value. + fn and_then(self, function: F) -> TemplateFunction + where + Self: Sized, + F: Fn(Self::Output) -> Result, + { + TemplateFunction::new(self, function) + } + + /// Translates to a property that will apply `function` to an extracted + /// value, leaving `Err` untouched. + fn map(self, function: F) -> impl TemplateProperty + where + Self: Sized, + F: Fn(Self::Output) -> O, + { + TemplateFunction::new(self, move |value| Ok(function(value))) + } +} + +impl TemplatePropertyExt for P {} + /// Adapter to drop template context. pub struct Literal(pub O); @@ -525,6 +550,9 @@ where } } +/// Adapter to apply fallible `function` to the `property`. +/// +/// This is usually created by `TemplatePropertyExt::and_then()`/`map()`. pub struct TemplateFunction { pub property: P, pub function: F,