coded.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include "coded.h"
  2. #include <memory.h>
  3. namespace NClickHouse {
  4. static const int MAX_VARINT_BYTES = 10;
  5. TCodedInputStream::TCodedInputStream(IZeroCopyInput* input)
  6. : Input_(input)
  7. {
  8. }
  9. bool TCodedInputStream::ReadRaw(void* buffer, size_t size) {
  10. ui8* p = static_cast<ui8*>(buffer);
  11. while (size > 0) {
  12. const void* ptr;
  13. if (size_t len = Input_->Next(&ptr, size)) {
  14. memcpy(p, ptr, len);
  15. p += len;
  16. size -= len;
  17. } else {
  18. break;
  19. }
  20. }
  21. return size == 0;
  22. }
  23. bool TCodedInputStream::Skip(size_t count) {
  24. while (count > 0) {
  25. const void* ptr;
  26. size_t len = Input_->Next(&ptr, count);
  27. if (len == 0) {
  28. return false;
  29. }
  30. count -= len;
  31. }
  32. return true;
  33. }
  34. bool TCodedInputStream::ReadVarint64(ui64* value) {
  35. *value = 0;
  36. for (size_t i = 0; i < 9; ++i) {
  37. ui8 byte;
  38. if (!Input_->Read(&byte, sizeof(byte))) {
  39. return false;
  40. } else {
  41. *value |= (byte & 0x7F) << (7 * i);
  42. if (!(byte & 0x80)) {
  43. return true;
  44. }
  45. }
  46. }
  47. // TODO skip invalid
  48. return false;
  49. }
  50. TCodedOutputStream::TCodedOutputStream(IOutputStream* output)
  51. : Output_(output)
  52. {
  53. }
  54. void TCodedOutputStream::Flush() {
  55. Output_->Flush();
  56. }
  57. void TCodedOutputStream::WriteRaw(const void* buffer, int size) {
  58. Output_->Write(buffer, size);
  59. }
  60. void TCodedOutputStream::WriteVarint64(ui64 value) {
  61. ui8 bytes[MAX_VARINT_BYTES];
  62. int size = 0;
  63. for (size_t i = 0; i < 9; ++i) {
  64. ui8 byte = value & 0x7F;
  65. if (value > 0x7F)
  66. byte |= 0x80;
  67. bytes[size++] = byte;
  68. value >>= 7;
  69. if (!value) {
  70. break;
  71. }
  72. }
  73. WriteRaw(bytes, size);
  74. }
  75. }