diff --git a/libtransmission/tr-buffer.h b/libtransmission/tr-buffer.h index b44ad8f5b..dd0df0d4d 100644 --- a/libtransmission/tr-buffer.h +++ b/libtransmission/tr-buffer.h @@ -264,7 +264,22 @@ public: virtual std::pair reserve_space(size_t n_bytes) override { - buf_.resize(end_pos_ + n_bytes); + if (auto const free_at_end = buf_.size() - end_pos_; free_at_end < n_bytes) + { + if (auto const total_free = begin_pos_ + free_at_end; total_free >= n_bytes) + { + // move data so that all free space is at the end + auto const size = this->size(); + std::copy(data(), data() + size, std::data(buf_)); + begin_pos_ = 0; + end_pos_ = size; + } + else // even `total_free` is not enough, so resize + { + buf_.resize(end_pos_ + n_bytes); + } + } + return { buf_.data() + end_pos_, n_bytes }; }