1
0

grpc.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright 2014 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef FLATBUFFERS_GRPC_H_
  17. #define FLATBUFFERS_GRPC_H_
  18. // Helper functionality to glue FlatBuffers and GRPC.
  19. #include "grpc++/support/byte_buffer.h"
  20. #include "grpc/byte_buffer_reader.h"
  21. namespace grpc {
  22. template <class T>
  23. class SerializationTraits<T, typename std::enable_if<std::is_base_of<
  24. flatbuffers::BufferRefBase, T>::value>::type> {
  25. public:
  26. // The type we're passing here is a BufferRef, which is already serialized
  27. // FlatBuffer data, which then gets passed to GRPC.
  28. static grpc::Status Serialize(const T& msg,
  29. grpc_byte_buffer **buffer,
  30. bool *own_buffer) {
  31. // TODO(wvo): make this work without copying.
  32. auto slice = gpr_slice_from_copied_buffer(
  33. reinterpret_cast<const char *>(msg.buf), msg.len);
  34. *buffer = grpc_raw_byte_buffer_create(&slice, 1);
  35. *own_buffer = true;
  36. return grpc::Status();
  37. }
  38. // There is no de-serialization step in FlatBuffers, so we just receive
  39. // the data from GRPC.
  40. static grpc::Status Deserialize(grpc_byte_buffer *buffer,
  41. T *msg,
  42. int max_message_size) {
  43. // TODO(wvo): make this more efficient / zero copy when possible.
  44. auto len = grpc_byte_buffer_length(buffer);
  45. msg->buf = reinterpret_cast<uint8_t *>(malloc(len));
  46. msg->len = static_cast<flatbuffers::uoffset_t>(len);
  47. msg->must_free = true;
  48. uint8_t *current = msg->buf;
  49. grpc_byte_buffer_reader reader;
  50. grpc_byte_buffer_reader_init(&reader, buffer);
  51. gpr_slice slice;
  52. while (grpc_byte_buffer_reader_next(&reader, &slice)) {
  53. memcpy(current, GPR_SLICE_START_PTR(slice), GPR_SLICE_LENGTH(slice));
  54. current += GPR_SLICE_LENGTH(slice);
  55. gpr_slice_unref(slice);
  56. }
  57. GPR_ASSERT(current == msg->buf + msg->len);
  58. grpc_byte_buffer_reader_destroy(&reader);
  59. grpc_byte_buffer_destroy(buffer);
  60. return grpc::Status();
  61. }
  62. };
  63. } // namespace grpc;
  64. #endif // FLATBUFFERS_GRPC_H_