From 8eb96549d340897a4df00bbdb0a4ffeae0fccb2d Mon Sep 17 00:00:00 2001 From: Kinrany Date: Tue, 21 Jul 2020 01:05:53 +0300 Subject: [PATCH] Implement From and TryFrom for AnyPushRule Conversion into PushRule always succeeds, so no need to use TryFrom there --- ruma-common/src/push.rs | 79 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/ruma-common/src/push.rs b/ruma-common/src/push.rs index ba1cece5..12469e6f 100644 --- a/ruma-common/src/push.rs +++ b/ruma-common/src/push.rs @@ -2,7 +2,10 @@ //! //! [push]: https://matrix.org/docs/spec/client_server/r0.6.1#id89 -use std::fmt::{self, Formatter}; +use std::{ + convert::TryFrom, + fmt::{self, Formatter}, +}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::value::RawValue as RawJsonValue; @@ -128,6 +131,80 @@ pub struct AnyPushRule { pub pattern: Option, } +impl From for AnyPushRule { + fn from(push_rule: PushRule) -> Self { + let PushRule { actions, default, enabled, rule_id } = push_rule; + AnyPushRule { actions, default, enabled, rule_id, pattern: None, conditions: None } + } +} + +impl From for AnyPushRule { + fn from(push_rule: PatternedPushRule) -> Self { + let PatternedPushRule { actions, default, enabled, rule_id, pattern } = push_rule; + AnyPushRule { actions, default, enabled, rule_id, pattern: Some(pattern), conditions: None } + } +} + +impl From for AnyPushRule { + fn from(push_rule: ConditionalPushRule) -> Self { + let ConditionalPushRule { actions, default, enabled, rule_id, conditions } = push_rule; + AnyPushRule { + actions, + default, + enabled, + rule_id, + pattern: None, + conditions: Some(conditions), + } + } +} + +impl From for PushRule { + fn from(push_rule: AnyPushRule) -> Self { + let AnyPushRule { actions, default, enabled, rule_id, .. } = push_rule; + PushRule { actions, default, enabled, rule_id } + } +} + +/// An error that happens when `AnyPushRule` cannot be converted +/// into a more specific push rule type. +#[derive(Debug)] +pub struct AnyPushRuleConversionError; + +impl TryFrom for PatternedPushRule { + type Error = AnyPushRuleConversionError; + + fn try_from(push_rule: AnyPushRule) -> Result { + if let AnyPushRule { actions, default, enabled, rule_id, pattern: Some(pattern), .. } = + push_rule + { + Ok(PatternedPushRule { actions, default, enabled, rule_id, pattern }) + } else { + Err(AnyPushRuleConversionError) + } + } +} + +impl TryFrom for ConditionalPushRule { + type Error = AnyPushRuleConversionError; + + fn try_from(push_rule: AnyPushRule) -> Result { + if let AnyPushRule { + actions, + default, + enabled, + rule_id, + conditions: Some(conditions), + .. + } = push_rule + { + Ok(ConditionalPushRule { actions, default, enabled, rule_id, conditions }) + } else { + Err(AnyPushRuleConversionError) + } + } +} + /// This represents the different actions that should be taken when a rule is matched, and /// controls how notifications are delivered to the client. ///