varint.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "varint.h"
  2. #include "zigzag.h"
  3. #include <util/generic/yexception.h>
  4. namespace NYson {
  5. ////////////////////////////////////////////////////////////////////////////////
  6. int WriteVarUInt64(IOutputStream* output, ui64 value) {
  7. bool stop = false;
  8. int bytesWritten = 0;
  9. while (!stop) {
  10. ++bytesWritten;
  11. ui8 byte = static_cast<ui8>(value | 0x80);
  12. value >>= 7;
  13. if (value == 0) {
  14. stop = true;
  15. byte &= 0x7F;
  16. }
  17. output->Write(byte);
  18. }
  19. return bytesWritten;
  20. }
  21. int WriteVarInt32(IOutputStream* output, i32 value) {
  22. return WriteVarUInt64(output, static_cast<ui64>(ZigZagEncode32(value)));
  23. }
  24. int WriteVarInt64(IOutputStream* output, i64 value) {
  25. return WriteVarUInt64(output, static_cast<ui64>(ZigZagEncode64(value)));
  26. }
  27. int ReadVarUInt64(IInputStream* input, ui64* value) {
  28. size_t count = 0;
  29. ui64 result = 0;
  30. ui8 byte = 0;
  31. do {
  32. if (7 * count > 8 * sizeof(ui64)) {
  33. ythrow yexception() << "The data is too long to read ui64";
  34. }
  35. if (input->Read(&byte, 1) != 1) {
  36. ythrow yexception() << "The data is too short to read ui64";
  37. }
  38. result |= (static_cast<ui64>(byte & 0x7F)) << (7 * count);
  39. ++count;
  40. } while (byte & 0x80);
  41. *value = result;
  42. return count;
  43. }
  44. int ReadVarInt32(IInputStream* input, i32* value) {
  45. ui64 varInt;
  46. int bytesRead = ReadVarUInt64(input, &varInt);
  47. if (varInt > Max<ui32>()) {
  48. ythrow yexception() << "The data is too long to read i32";
  49. }
  50. *value = ZigZagDecode32(static_cast<ui32>(varInt));
  51. return bytesRead;
  52. }
  53. int ReadVarInt64(IInputStream* input, i64* value) {
  54. ui64 varInt;
  55. int bytesRead = ReadVarUInt64(input, &varInt);
  56. *value = ZigZagDecode64(varInt);
  57. return bytesRead;
  58. }
  59. } // namespace NYson