From 3ee06be87b84e9978f9ebae88561f6c4285551d9 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Fri, 10 Jul 2020 21:41:46 +0200 Subject: [PATCH] Rewrite MessageQueue deserialization to reduce allocations --- matrix_sdk_base/src/models/message.rs | 34 ++++++++++++++++++++------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/matrix_sdk_base/src/models/message.rs b/matrix_sdk_base/src/models/message.rs index 7f4532ef..d1431e6c 100644 --- a/matrix_sdk_base/src/models/message.rs +++ b/matrix_sdk_base/src/models/message.rs @@ -139,20 +139,38 @@ impl IntoIterator for MessageQueue { } pub(crate) mod ser_deser { + use std::fmt; + use super::*; + struct MessageQueueDeserializer; + + impl<'de> de::Visitor<'de> for MessageQueueDeserializer { + type Value = MessageQueue; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("an array of message events") + } + + fn visit_seq(self, mut access: S) -> Result + where + S: de::SeqAccess<'de>, + { + let mut msgs = Vec::with_capacity(access.size_hint().unwrap_or(0)); + + while let Some(msg) = access.next_element::()? { + msgs.push(MessageWrapper(msg)); + } + + Ok(MessageQueue { msgs }) + } + } + pub fn deserialize<'de, D>(deserializer: D) -> Result where D: de::Deserializer<'de>, { - let messages: Vec = de::Deserialize::deserialize(deserializer)?; - - let mut msgs = vec![]; - for msg in messages { - msgs.push(MessageWrapper(msg)); - } - - Ok(MessageQueue { msgs }) + deserializer.deserialize_seq(MessageQueueDeserializer) } pub fn serialize(msgs: &MessageQueue, serializer: S) -> Result