udp_recv_packet.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #include <util/generic/noncopyable.h>
  3. #include <util/system/defaults.h>
  4. #include <memory>
  5. #include "allocator.h"
  6. namespace NNetlibaSocket {
  7. enum { UDP_MAX_PACKET_SIZE = 8900 };
  8. class TUdpHostRecvBufAlloc;
  9. struct TUdpRecvPacket: public TWithCustomAllocator {
  10. friend class TUdpHostRecvBufAlloc;
  11. int DataStart = 0, DataSize = 0;
  12. std::shared_ptr<char> Data;
  13. private:
  14. int ArraySize_ = 0;
  15. };
  16. ///////////////////////////////////////////////////////////////////////////////
  17. class TUdpHostRecvBufAlloc: public TNonCopyable {
  18. private:
  19. mutable TUdpRecvPacket* RecvPktBuf;
  20. static TUdpRecvPacket* Alloc() {
  21. return new TUdpRecvPacket();
  22. }
  23. public:
  24. static TUdpRecvPacket* Create(const int dataSize) {
  25. TUdpRecvPacket* result = Alloc();
  26. result->Data.reset(TCustomAllocator<char>().allocate(dataSize), [=](char* p) { TCustomAllocator<char>().deallocate(p, dataSize); }, TCustomAllocator<char>());
  27. result->ArraySize_ = dataSize;
  28. return result;
  29. }
  30. void SetNewPacket() const {
  31. RecvPktBuf = CreateNewPacket();
  32. }
  33. public:
  34. static TUdpRecvPacket* CreateNewSmallPacket(int dataSize) {
  35. return Create(dataSize);
  36. }
  37. static TUdpRecvPacket* CreateNewPacket() {
  38. return Create(UDP_MAX_PACKET_SIZE);
  39. }
  40. static TUdpRecvPacket* Clone(const TUdpRecvPacket* pkt) {
  41. TUdpRecvPacket* result = Alloc();
  42. result->DataStart = pkt->DataStart;
  43. result->DataSize = pkt->DataSize;
  44. result->Data = pkt->Data;
  45. result->ArraySize_ = pkt->ArraySize_;
  46. return result;
  47. }
  48. TUdpHostRecvBufAlloc() {
  49. SetNewPacket();
  50. }
  51. ~TUdpHostRecvBufAlloc() {
  52. delete RecvPktBuf;
  53. }
  54. TUdpRecvPacket* ExtractPacket() {
  55. TUdpRecvPacket* res = RecvPktBuf;
  56. SetNewPacket();
  57. return res;
  58. }
  59. int GetBufSize() const {
  60. return RecvPktBuf->ArraySize_;
  61. }
  62. char* GetDataPtr() const {
  63. return RecvPktBuf->Data.get();
  64. }
  65. };
  66. }