Skip to content

Commit 2525faa

Browse files
committed
Pre-allocate the full require Vec prior to serializing into vecs
We end up generating a substantial amount of allocations just doubling `Vec`s when serializing to them, and our `serialized_length` method is generally rather effecient, so we just rely on it and allocate correctly up front.
1 parent e09afaf commit 2525faa

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

lightning/src/util/ser.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,14 @@ pub trait Writeable {
199199

200200
/// Writes `self` out to a `Vec<u8>`.
201201
fn encode(&self) -> Vec<u8> {
202-
let mut msg = VecWriter(Vec::new());
202+
let len = self.serialized_length();
203+
let mut msg = VecWriter(Vec::with_capacity(len));
203204
self.write(&mut msg).unwrap();
205+
// Note that objects with interior mutability may change size between when we called
206+
// serialized_length and when we called write. That's okay, but shouldn't happen during
207+
// testing as most of our tests are not threaded.
208+
#[cfg(test)]
209+
debug_assert_eq!(len, msg.0.len());
204210
msg.0
205211
}
206212

@@ -211,6 +217,7 @@ pub trait Writeable {
211217
0u16.write(&mut msg).unwrap();
212218
self.write(&mut msg).unwrap();
213219
let len = msg.0.len();
220+
debug_assert_eq!(len - 2, self.serialized_length());
214221
msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
215222
msg.0
216223
}

0 commit comments

Comments
 (0)