mirror of
https://github.com/fluencelabs/rust-libp2p
synced 2025-06-29 09:41:34 +00:00
Optimise Multiaddr::append
. (#549)
Append to the existing vector instead of allocating a temporary one and copying bytes over.
This commit is contained in:
@ -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.
|
||||
|
@ -283,3 +283,16 @@ fn ser_and_deser_bincode() {
|
||||
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())
|
||||
}
|
||||
|
Reference in New Issue
Block a user