From d8340db310784041089823002bfb2d9b472f9769 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Dom=C3=ADnguez?= Date: Fri, 21 Aug 2020 20:35:25 +0200 Subject: [PATCH] Group fields in create_typing_event --- .../src/r0/typing/create_typing_event.rs | 61 +++++++++++++++---- 1 file changed, 49 insertions(+), 12 deletions(-) diff --git a/ruma-client-api/src/r0/typing/create_typing_event.rs b/ruma-client-api/src/r0/typing/create_typing_event.rs index b1e60f94..ce800a75 100644 --- a/ruma-client-api/src/r0/typing/create_typing_event.rs +++ b/ruma-client-api/src/r0/typing/create_typing_event.rs @@ -1,5 +1,6 @@ //! [PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}](https://matrix.org/docs/spec/client_server/r0.6.0#put-matrix-client-r0-rooms-roomid-typing-userid) +use serde::{de::Error, Deserialize, Deserializer, Serialize}; use std::time::Duration; use ruma_api::ruma_api; @@ -24,21 +25,57 @@ ruma_api! { #[ruma_api(path)] pub room_id: RoomId, - // TODO: Group the following two body fields into an enum - - /// Whether the user is typing or not. If `false`, the `timeout` key can be omitted. - pub typing: bool, - - /// The length of time in milliseconds to mark this user as typing. - #[serde( - with = "ruma_serde::duration::opt_ms", - default, - skip_serializing_if = "Option::is_none", - )] - pub timeout: Option, + /// Whether the user is typing within a length of time or not. + #[serde(flatten)] + pub state: Typing, } response: {} error: crate::Error } + +/// A mark for whether the user is typing within a length of time or not. +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(into = "TypingInner")] +pub enum Typing { + /// Not typing. + No, + /// Typing during the specified length of time. + Yes(Duration), +} + +#[derive(Deserialize, Serialize)] +struct TypingInner { + typing: bool, + #[serde( + with = "ruma_serde::duration::opt_ms", + default, + skip_serializing_if = "Option::is_none" + )] + timeout: Option, +} + +impl From for TypingInner { + fn from(typing: Typing) -> Self { + match typing { + Typing::No => Self { typing: false, timeout: None }, + Typing::Yes(time) => Self { typing: true, timeout: Some(time) }, + } + } +} + +impl<'de> Deserialize<'de> for Typing { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let inner = TypingInner::deserialize(deserializer)?; + + match (inner.typing, inner.timeout) { + (false, _) => Ok(Self::No), + (true, Some(time)) => Ok(Self::Yes(time)), + _ => Err(D::Error::missing_field("timeout")), + } + } +}