Optimise Multiaddr::append. (#549)

Append to the existing vector instead of allocating a temporary one and
copying bytes over.
This commit is contained in:
Toralf Wittner
2018-10-10 11:07:30 +02:00
committed by GitHub
parent fd4ae72f8c
commit 9bdaabc884
2 changed files with 19 additions and 4 deletions

View File

@ -24,6 +24,7 @@ use serde::{
};
use std::{
fmt,
io,
iter::FromIterator,
net::{SocketAddr, SocketAddrV4, SocketAddrV6, IpAddr, Ipv4Addr, Ipv6Addr},
result::Result as StdResult,
@ -180,9 +181,10 @@ impl Multiaddr {
///
#[inline]
pub fn append(&mut self, p: Protocol) {
let mut w = Vec::new();
p.write_bytes(&mut w).expect("writing to a Vec never fails");
self.bytes.extend_from_slice(&w);
let n = self.bytes.len();
let mut w = io::Cursor::new(&mut self.bytes);
w.set_position(n as u64);
p.write_bytes(&mut w).expect("writing to a Vec never fails")
}
/// Remove the outermost address.

View File

@ -282,4 +282,17 @@ fn ser_and_deser_bincode() {
assert_eq!(serialized, vec![8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 6, 0, 0]);
let deserialized: Multiaddr = bincode::deserialize(&serialized).unwrap();
assert_eq!(addr, deserialized);
}
}
#[test]
fn append() {
let mut a: Multiaddr = Protocol::Ip4(Ipv4Addr::new(1, 2, 3, 4)).into();
a.append(Protocol::Tcp(80));
a.append(Protocol::Http);
let mut i = a.iter();
assert_eq!(Some(Protocol::Ip4(Ipv4Addr::new(1, 2, 3, 4))), i.next());
assert_eq!(Some(Protocol::Tcp(80)), i.next());
assert_eq!(Some(Protocol::Http), i.next());
assert_eq!(None, i.next())
}