Rewrite MessageQueue deserialization to reduce allocations

master
Jonas Platte 2020-07-10 21:41:46 +02:00
parent 3a07a17e9d
commit 3ee06be87b
No known key found for this signature in database
GPG Key ID: CC154DE0E30B7C67
1 changed files with 26 additions and 8 deletions

View File

@ -139,20 +139,38 @@ impl IntoIterator for MessageQueue {
} }
pub(crate) mod ser_deser { pub(crate) mod ser_deser {
use std::fmt;
use super::*; 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<S>(self, mut access: S) -> Result<Self::Value, S::Error>
where
S: de::SeqAccess<'de>,
{
let mut msgs = Vec::with_capacity(access.size_hint().unwrap_or(0));
while let Some(msg) = access.next_element::<SyncMessageEvent>()? {
msgs.push(MessageWrapper(msg));
}
Ok(MessageQueue { msgs })
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<MessageQueue, D::Error> pub fn deserialize<'de, D>(deserializer: D) -> Result<MessageQueue, D::Error>
where where
D: de::Deserializer<'de>, D: de::Deserializer<'de>,
{ {
let messages: Vec<SyncMessageEvent> = de::Deserialize::deserialize(deserializer)?; deserializer.deserialize_seq(MessageQueueDeserializer)
let mut msgs = vec![];
for msg in messages {
msgs.push(MessageWrapper(msg));
}
Ok(MessageQueue { msgs })
} }
pub fn serialize<S>(msgs: &MessageQueue, serializer: S) -> Result<S::Ok, S::Error> pub fn serialize<S>(msgs: &MessageQueue, serializer: S) -> Result<S::Ok, S::Error>