mirror of
https://github.com/fluencelabs/rust-libp2p
synced 2025-06-29 17:51:35 +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::{
|
use std::{
|
||||||
fmt,
|
fmt,
|
||||||
|
io,
|
||||||
iter::FromIterator,
|
iter::FromIterator,
|
||||||
net::{SocketAddr, SocketAddrV4, SocketAddrV6, IpAddr, Ipv4Addr, Ipv6Addr},
|
net::{SocketAddr, SocketAddrV4, SocketAddrV6, IpAddr, Ipv4Addr, Ipv6Addr},
|
||||||
result::Result as StdResult,
|
result::Result as StdResult,
|
||||||
@ -180,9 +181,10 @@ impl Multiaddr {
|
|||||||
///
|
///
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn append(&mut self, p: Protocol) {
|
pub fn append(&mut self, p: Protocol) {
|
||||||
let mut w = Vec::new();
|
let n = self.bytes.len();
|
||||||
p.write_bytes(&mut w).expect("writing to a Vec never fails");
|
let mut w = io::Cursor::new(&mut self.bytes);
|
||||||
self.bytes.extend_from_slice(&w);
|
w.set_position(n as u64);
|
||||||
|
p.write_bytes(&mut w).expect("writing to a Vec never fails")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove the outermost address.
|
/// Remove the outermost address.
|
||||||
|
@ -283,3 +283,16 @@ fn ser_and_deser_bincode() {
|
|||||||
let deserialized: Multiaddr = bincode::deserialize(&serialized).unwrap();
|
let deserialized: Multiaddr = bincode::deserialize(&serialized).unwrap();
|
||||||
assert_eq!(addr, deserialized);
|
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