From d861261a5dd78e11fb56d21e1c6c22fd0099df03 Mon Sep 17 00:00:00 2001 From: Faerbit Date: Sun, 4 Aug 2024 23:07:38 +0200 Subject: [PATCH] [bencode/ser] "Optimize" performance --- src/bencode/ser.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/bencode/ser.rs b/src/bencode/ser.rs index b730e7c..0ab694d 100644 --- a/src/bencode/ser.rs +++ b/src/bencode/ser.rs @@ -1,5 +1,5 @@ use std::collections::BTreeMap; - +use std::mem::swap; use serde::{ser, Serialize}; use crate::bencode::error::{Error, Result}; @@ -280,8 +280,9 @@ impl <'a> ser::SerializeMap for MapSerializer<'a> { { key.serialize(&mut self.value_serializer)?; self.last_inserted_key = self.value_serializer.output.clone(); - self.sorted_map.insert(self.value_serializer.output.clone(), Vec::new()); - self.value_serializer.output.clear(); + let mut key_to_insert = Vec::new(); + swap(&mut self.value_serializer.output, &mut key_to_insert); + self.sorted_map.insert(key_to_insert, Vec::new()); Ok(()) } @@ -290,8 +291,13 @@ impl <'a> ser::SerializeMap for MapSerializer<'a> { T: ?Sized + Serialize { value.serialize(&mut self.value_serializer)?; - self.sorted_map.insert(self.last_inserted_key.clone(), self.value_serializer.output.clone()); - self.value_serializer.output.clear(); + let mut value_to_insert = Vec::new(); + swap(&mut self.value_serializer.output, &mut value_to_insert); + if let Some(x) = self.sorted_map.get_mut(&self.last_inserted_key) { + *x = value_to_insert; + } else { + unreachable!() + } self.last_inserted_key.clear(); Ok(()) }