byte_buffer_proto_helper.cc 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. *
  3. * Copyright 2016 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include "test/cpp/util/byte_buffer_proto_helper.h"
  19. #include "absl/memory/memory.h"
  20. namespace grpc {
  21. namespace testing {
  22. bool ParseFromByteBuffer(ByteBuffer* buffer, grpc::protobuf::Message* message) {
  23. std::vector<Slice> slices;
  24. (void)buffer->Dump(&slices);
  25. std::string buf;
  26. buf.reserve(buffer->Length());
  27. for (auto s = slices.begin(); s != slices.end(); s++) {
  28. buf.append(reinterpret_cast<const char*>(s->begin()), s->size());
  29. }
  30. return message->ParseFromString(buf);
  31. }
  32. std::unique_ptr<ByteBuffer> SerializeToByteBuffer(
  33. grpc::protobuf::Message* message) {
  34. std::string buf;
  35. message->SerializeToString(&buf);
  36. Slice slice(buf);
  37. return absl::make_unique<ByteBuffer>(&slice, 1);
  38. }
  39. bool SerializeToByteBufferInPlace(grpc::protobuf::Message* message,
  40. ByteBuffer* buffer) {
  41. std::string buf;
  42. if (!message->SerializeToString(&buf)) {
  43. return false;
  44. }
  45. buffer->Clear();
  46. Slice slice(buf);
  47. ByteBuffer tmp(&slice, 1);
  48. buffer->Swap(&tmp);
  49. return true;
  50. }
  51. } // namespace testing
  52. } // namespace grpc