Skip to content

Commit

Permalink
[RPC][BUGFIX][BACKPORT-0.6] Fix bug in rpc ring buffer shrink (apache…
Browse files Browse the repository at this point in the history
  • Loading branch information
tqchen committed May 7, 2020
1 parent 60c5e48 commit a70812b
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions src/common/ring_buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
Expand Down Expand Up @@ -49,8 +49,12 @@ class RingBuffer {
return ring_.size();
}
/*!
* Reserve capacity to be at least n.
* Will only increase capacity if n is bigger than current capacity.
* Reserve capacity to be at least n.
* Will only increase capacity if n is bigger than current capacity.
*
* The effect of Reserve only lasts before the next call to Reserve.
* Other functions in the ring buffer can also call into the reserve.
*
* \param n The size of capacity.
*/
void Reserve(size_t n) {
Expand All @@ -63,19 +67,27 @@ class RingBuffer {
size_t ncopy = head_ptr_ + bytes_available_ - old_size;
memcpy(&ring_[0] + old_size, &ring_[0], ncopy);
}
} else if (ring_.size() > n * 8 && ring_.size() > kInitCapacity) {
// shrink too large temporary buffer to avoid out of memory on some embedded devices
} else if (ring_.size() > n * 8 &&
ring_.size() > kInitCapacity) {
// shrink too large temporary buffer to
// avoid out of memory on some embedded devices
if (bytes_available_ != 0) {
// move existing bytes to the head.
size_t old_bytes = bytes_available_;

std::vector<char> tmp(old_bytes);

Read(&tmp[0], old_bytes);
ring_.resize(kInitCapacity);
ring_.shrink_to_fit();

memcpy(&ring_[0], &tmp[0], old_bytes);
head_ptr_ = 0;
bytes_available_ = old_bytes;
}
// shrink the ring.
size_t new_size = kInitCapacity;
new_size = std::max(new_size, n);
new_size = std::max(new_size, bytes_available_);

ring_.resize(new_size);
ring_.shrink_to_fit();
head_ptr_ = 0;
}
}

Expand Down

0 comments on commit a70812b

Please sign in to comment.