From 2665bdd6d29ec2515946ac629002c04c23a50bfa Mon Sep 17 00:00:00 2001 From: "Mark D. Roth" Date: Thu, 18 Aug 2016 08:02:24 -0700 Subject: [PATCH] Reduce allocations associated with src/cpp/util/byte_buffer.cc. --- include/grpc++/support/byte_buffer.h | 3 +++ src/cpp/util/byte_buffer.cc | 25 +++++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/include/grpc++/support/byte_buffer.h b/include/grpc++/support/byte_buffer.h index 20bd407109127..01249a0b88bd0 100644 --- a/include/grpc++/support/byte_buffer.h +++ b/include/grpc++/support/byte_buffer.h @@ -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; diff --git a/src/cpp/util/byte_buffer.cc b/src/cpp/util/byte_buffer.cc index c2cd20ee07f0a..4c4772a92b30d 100644 --- a/src/cpp/util/byte_buffer.cc +++ b/src/cpp/util/byte_buffer.cc @@ -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 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::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(const_cast(slices)), nslices); } ByteBuffer::~ByteBuffer() { @@ -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