Fix multiaddr::util::BytesWriter. (#1068)

The current implementation does not properly reserve enough space for
`Write::write_all` to succeed. The property test has been improved to
trigger that issue.
This commit is contained in:
Toralf Wittner
2019-04-18 14:28:47 +02:00
committed by GitHub
parent ca58f8029c
commit 5a465b7f50
2 changed files with 10 additions and 23 deletions

View File

@ -1,4 +1,4 @@
use bytes::{BufMut, BytesMut};
use bytes::BytesMut;
/// An [`io::Write`] impl for [`BytesMut`].
///
@ -9,25 +9,8 @@ pub(crate) struct BytesWriter(pub(crate) BytesMut);
impl std::io::Write for BytesWriter {
fn write(&mut self, src: &[u8]) -> std::io::Result<usize> {
let n = std::cmp::min(self.0.remaining_mut(), src.len());
self.0.put(&src[.. n]);
Ok(n)
}
fn write_all(&mut self, mut buf: &[u8]) -> std::io::Result<()> {
if self.0.remaining_mut() < buf.len() {
self.0.reserve(buf.len() - self.0.remaining_mut());
}
while !buf.is_empty() {
match self.write(buf) {
Ok(0) => return Err(std::io::ErrorKind::WriteZero.into()),
Ok(n) => buf = &buf[n ..],
Err(e) => if e.kind() != std::io::ErrorKind::Interrupted {
return Err(e)
}
}
}
Ok(())
self.0.extend_from_slice(src);
Ok(src.len())
}
fn flush(&mut self) -> std::io::Result<()> {