[bencode/ser] "Optimize" performance

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

View File

@ -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(())
}