Skip to content

Commit

Permalink
Fix capacity checking as pointed in the review.
Browse files Browse the repository at this point in the history
  • Loading branch information
futursolo committed Jun 29, 2022
1 parent 0d477f4 commit 9c36639
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions packages/yew/src/platform/io.rs
Expand Up @@ -64,19 +64,20 @@ impl BufWriter {
self.buf.reserve(self.capacity);
}

/// Returns `True` if the internal buffer has capacity to fit a string of certain length.
#[inline]
fn has_capacity_of(&self, next_part_len: usize) -> bool {
self.buf.capacity() >= self.buf.len() + next_part_len
}

/// Writes a string into the buffer, optionally drains the buffer.
pub fn write(&mut self, s: Cow<'_, str>) {
if self.buf.capacity() < s.len() {
if !self.has_capacity_of(s.len()) {
// There isn't enough capacity, we drain the buffer.
self.drain();
}

// It's important to check self.buf.capacity() >= s.len():
//
// 1. self.buf.reserve() may choose to over reserve than capacity.
// 2. When self.buf.capacity() == s.len(), the previous buffer is not drained. So it needs
// to push onto the buffer instead of sending.
if self.buf.capacity() >= s.len() {
if self.has_capacity_of(s.len()) {
// The next part is going to fit into the buffer, we push it onto the buffer.
self.buf.push_str(&s);
} else {
Expand Down

0 comments on commit 9c36639

Please sign in to comment.