From c8c83b15bb6ae28876796d90486090443654d68b Mon Sep 17 00:00:00 2001 From: Philip Craig Date: Sat, 28 Aug 2021 00:00:00 +0000 Subject: [PATCH] Better document api contract for WritableBuffer Co-authored-by: bjorn3 --- src/write/util.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/write/util.rs b/src/write/util.rs index 10b9e5a0..4664a159 100644 --- a/src/write/util.rs +++ b/src/write/util.rs @@ -6,10 +6,15 @@ use crate::pod::{bytes_of, bytes_of_slice, Pod}; #[allow(clippy::len_without_is_empty)] pub trait WritableBuffer { /// Returns position/offset for data to be written at. + /// + /// Should only be used in debug assertions fn len(&self) -> usize; /// Reserves specified number of bytes in the buffer. - fn reserve(&mut self, additional: usize) -> Result<(), ()>; + /// + /// This will be called exactly once before writing anything to the buffer, + /// and the given size is the exact total number of bytes that will be written. + fn reserve(&mut self, size: usize) -> Result<(), ()>; /// Writes zero bytes at the end of the buffer until the buffer /// has the specified length. @@ -54,8 +59,9 @@ impl WritableBuffer for Vec { } #[inline] - fn reserve(&mut self, additional: usize) -> Result<(), ()> { - self.reserve(additional); + fn reserve(&mut self, size: usize) -> Result<(), ()> { + debug_assert!(self.is_empty()); + self.reserve(size); Ok(()) } @@ -67,6 +73,7 @@ impl WritableBuffer for Vec { #[inline] fn write_bytes(&mut self, val: &[u8]) { + debug_assert!(self.len() + val.len() <= self.capacity()); self.extend_from_slice(val) } }