message_allocator.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. //
  3. // Copyright 2019 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. #ifndef GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H
  19. #define GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H
  20. namespace grpc {
  21. // NOTE: This is an API for advanced users who need custom allocators.
  22. // Per rpc struct for the allocator. This is the interface to return to user.
  23. class RpcAllocatorState {
  24. public:
  25. virtual ~RpcAllocatorState() = default;
  26. // Optionally deallocate request early to reduce the size of working set.
  27. // A custom MessageAllocator needs to be registered to make use of this.
  28. // This is not abstract because implementing it is optional.
  29. virtual void FreeRequest() {}
  30. };
  31. // This is the interface returned by the allocator.
  32. // grpc library will call the methods to get request/response pointers and to
  33. // release the object when it is done.
  34. template <typename RequestT, typename ResponseT>
  35. class MessageHolder : public RpcAllocatorState {
  36. public:
  37. // Release this object. For example, if the custom allocator's
  38. // AllocateMessasge creates an instance of a subclass with new, the Release()
  39. // should do a "delete this;".
  40. virtual void Release() = 0;
  41. RequestT* request() { return request_; }
  42. ResponseT* response() { return response_; }
  43. protected:
  44. void set_request(RequestT* request) { request_ = request; }
  45. void set_response(ResponseT* response) { response_ = response; }
  46. private:
  47. // NOTE: subclasses should set these pointers.
  48. RequestT* request_;
  49. ResponseT* response_;
  50. };
  51. // A custom allocator can be set via the generated code to a callback unary
  52. // method, such as SetMessageAllocatorFor_Echo(custom_allocator). The allocator
  53. // needs to be alive for the lifetime of the server.
  54. // Implementations need to be thread-safe.
  55. template <typename RequestT, typename ResponseT>
  56. class MessageAllocator {
  57. public:
  58. virtual ~MessageAllocator() = default;
  59. virtual MessageHolder<RequestT, ResponseT>* AllocateMessages() = 0;
  60. };
  61. } // namespace grpc
  62. #endif // GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H