[bencode/ser] "Optimize" performance

This commit is contained in:
Fabian 2024-08-04 23:07:38 +02:00
parent 0264c133ac
commit f0fac02251

View File

@ -1,5 +1,5 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::mem::swap;
use serde::{ser, Serialize}; use serde::{ser, Serialize};
use crate::bencode::error::{Error, Result}; use crate::bencode::error::{Error, Result};
@ -280,8 +280,9 @@ impl <'a> ser::SerializeMap for MapSerializer<'a> {
{ {
key.serialize(&mut self.value_serializer)?; key.serialize(&mut self.value_serializer)?;
self.last_inserted_key = self.value_serializer.output.clone(); self.last_inserted_key = self.value_serializer.output.clone();
self.sorted_map.insert(self.value_serializer.output.clone(), Vec::new()); let mut key_to_insert = Vec::new();
self.value_serializer.output.clear(); swap(&mut self.value_serializer.output, &mut key_to_insert);
self.sorted_map.insert(key_to_insert, Vec::new());
Ok(()) Ok(())
} }
@ -290,8 +291,11 @@ impl <'a> ser::SerializeMap for MapSerializer<'a> {
T: ?Sized + Serialize T: ?Sized + Serialize
{ {
value.serialize(&mut self.value_serializer)?; value.serialize(&mut self.value_serializer)?;
self.sorted_map.insert(self.last_inserted_key.clone(), self.value_serializer.output.clone()); let mut value_to_insert = Vec::new();
self.value_serializer.output.clear(); swap(&mut self.value_serializer.output, &mut value_to_insert);
let Some(x) = self.sorted_map.get_mut(&self.last_inserted_key)
else { unreachable!() };
*x = value_to_insert;
self.last_inserted_key.clear(); self.last_inserted_key.clear();
Ok(()) Ok(())
} }