proto_packer.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #pragma once
  2. #include "packers.h"
  3. #include <util/generic/yexception.h>
  4. namespace NPackers {
  5. template <typename TProtoMessage>
  6. class TProtoMessagePacker {
  7. public:
  8. void UnpackLeaf(const char* bufferPtr, TProtoMessage& protoMessage) const {
  9. const size_t protoMessageByteSize = GetProtoMessageByteSize(bufferPtr);
  10. const size_t skipBytesCount = ProtoMessageByteSizePacker.SkipLeaf(bufferPtr);
  11. if (!protoMessage.ParseFromArray(static_cast<const void*>(bufferPtr + skipBytesCount), protoMessageByteSize)) {
  12. ythrow yexception() << "Cannot unpack leaf with proto message";
  13. }
  14. }
  15. void PackLeaf(char* bufferPtr, const TProtoMessage& protoMessage, const size_t totalByteSize) const {
  16. const size_t protoMessageByteSize = protoMessage.ByteSize();
  17. const size_t skipBytesCount = totalByteSize - protoMessageByteSize;
  18. ProtoMessageByteSizePacker.PackLeaf(bufferPtr, protoMessageByteSize, skipBytesCount);
  19. if (!protoMessage.SerializeToArray(static_cast<void*>(bufferPtr + skipBytesCount), protoMessageByteSize)) {
  20. ythrow yexception() << "Cannot pack leaf with proto message";
  21. }
  22. }
  23. size_t MeasureLeaf(const TProtoMessage& protoMessage) const {
  24. const size_t protoMessageByteSize = protoMessage.ByteSize();
  25. return ProtoMessageByteSizePacker.MeasureLeaf(protoMessageByteSize) + protoMessageByteSize;
  26. }
  27. size_t SkipLeaf(const char* bufferPtr) const {
  28. const size_t protoMessageByteSize = GetProtoMessageByteSize(bufferPtr);
  29. return ProtoMessageByteSizePacker.SkipLeaf(bufferPtr) + protoMessageByteSize;
  30. }
  31. private:
  32. TIntegralPacker<size_t> ProtoMessageByteSizePacker;
  33. size_t GetProtoMessageByteSize(const char* bufferPtr) const {
  34. size_t result;
  35. ProtoMessageByteSizePacker.UnpackLeaf(bufferPtr, result);
  36. return result;
  37. }
  38. };
  39. }