From 9c366398c06720d8be41c642f61caf52b5da840c Mon Sep 17 00:00:00 2001 From: Kaede Hoshikawa Date: Wed, 29 Jun 2022 20:20:30 +0900 Subject: [PATCH] Fix capacity checking as pointed in the review. --- packages/yew/src/platform/io.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/yew/src/platform/io.rs b/packages/yew/src/platform/io.rs index dd60ad95bd7..ff696c17c6c 100644 --- a/packages/yew/src/platform/io.rs +++ b/packages/yew/src/platform/io.rs @@ -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 {