Skip to content

Commit

Permalink
Merge pull request grpc#7773 from markdroth/bytebuffer_alloc
Browse files Browse the repository at this point in the history
Reduce allocations associated with src/cpp/util/byte_buffer.cc.
  • Loading branch information
markdroth authored Aug 18, 2016
2 parents 5c648dc + 2665bdd commit 9770206
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
3 changes: 3 additions & 0 deletions include/grpc++/support/byte_buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ class ByteBuffer GRPC_FINAL {
/// Buffer size in bytes.
size_t Length() const;

/// Swap the state of *this and *other.
void Swap(ByteBuffer* other);

private:
friend class SerializationTraits<ByteBuffer, void>;

Expand Down
25 changes: 19 additions & 6 deletions src/cpp/util/byte_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,19 @@
namespace grpc {

ByteBuffer::ByteBuffer(const Slice* slices, size_t nslices) {
// TODO(yangg) maybe expose some core API to simplify this
std::vector<gpr_slice> c_slices(nslices);
for (size_t i = 0; i < nslices; i++) {
c_slices[i] = slices[i].slice_;
}
buffer_ = grpc_raw_byte_buffer_create(c_slices.data(), nslices);
// The following assertions check that the representation of a grpc::Slice is
// identical to that of a gpr_slice: it has a gpr_slice field, and nothing
// else.
static_assert(std::is_same<decltype(slices[0].slice_), gpr_slice>::value,
"Slice must have same representation as gpr_slice");
static_assert(sizeof(Slice) == sizeof(gpr_slice),
"Slice must have same representation as gpr_slice");
// The const_cast is legal if grpc_raw_byte_buffer_create() does no more
// than its advertised side effect of increasing the reference count of the
// slices it processes, and such an increase does not affect the semantics
// seen by the caller of this constructor.
buffer_ = grpc_raw_byte_buffer_create(
reinterpret_cast<gpr_slice*>(const_cast<Slice*>(slices)), nslices);
}

ByteBuffer::~ByteBuffer() {
Expand Down Expand Up @@ -95,4 +102,10 @@ ByteBuffer& ByteBuffer::operator=(const ByteBuffer& buf) {
return *this;
}

void ByteBuffer::Swap(ByteBuffer* other) {
grpc_byte_buffer* tmp = other->buffer_;
other->buffer_ = this->buffer_;
this->buffer_ = tmp;
}

} // namespace grpc

0 comments on commit 9770206

Please sign in to comment.