coded.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #pragma once
  2. #include <util/generic/string.h>
  3. #include <util/stream/output.h>
  4. #include <util/stream/zerocopy.h>
  5. namespace NClickHouse {
  6. /**
  7. * Class which reads and decodes binary data which is composed of varint-
  8. * encoded integers and fixed-width pieces.
  9. */
  10. class TCodedInputStream {
  11. public:
  12. TCodedInputStream() = default;
  13. /// Create a CodedInputStream that reads from the given ZeroCopyInput.
  14. explicit TCodedInputStream(IZeroCopyInput* input);
  15. // Read an unsigned integer with Varint encoding, truncating to 32 bits.
  16. // Reading a 32-bit value is equivalent to reading a 64-bit one and casting
  17. // it to uint32, but may be more efficient.
  18. bool ReadVarint32(ui32* value);
  19. // Read an unsigned integer with Varint encoding.
  20. bool ReadVarint64(ui64* value);
  21. // Read raw bytes, copying them into the given buffer.
  22. bool ReadRaw(void* buffer, size_t size);
  23. // Like ReadRaw, but reads into a string.
  24. //
  25. // Implementation Note: ReadString() grows the string gradually as it
  26. // reads in the data, rather than allocating the entire requested size
  27. // upfront. This prevents denial-of-service attacks in which a client
  28. // could claim that a string is going to be MAX_INT bytes long in order to
  29. // crash the server because it can't allocate this much space at once.
  30. bool ReadString(TString* buffer, int size);
  31. // Skips a number of bytes. Returns false if an underlying read error
  32. // occurs.
  33. bool Skip(size_t count);
  34. private:
  35. IZeroCopyInput* Input_;
  36. };
  37. class TCodedOutputStream {
  38. public:
  39. TCodedOutputStream() = default;
  40. /// Create a CodedInputStream that writes to the given ZeroCopyOutput.
  41. explicit TCodedOutputStream(IOutputStream* output);
  42. void Flush();
  43. // Write raw bytes, copying them from the given buffer.
  44. void WriteRaw(const void* buffer, int size);
  45. /// Write an unsigned integer with Varint encoding.
  46. void WriteVarint64(const ui64 value);
  47. private:
  48. IOutputStream* Output_;
  49. };
  50. }