diff options
author | Devtools Arcadia <arcadia-devtools@yandex-team.ru> | 2022-02-07 18:08:42 +0300 |
---|---|---|
committer | Devtools Arcadia <arcadia-devtools@mous.vla.yp-c.yandex.net> | 2022-02-07 18:08:42 +0300 |
commit | 1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch) | |
tree | e26c9fed0de5d9873cce7e00bc214573dc2195b7 /library/cpp/yson/varint.cpp | |
download | ydb-1110808a9d39d4b808aef724c861a2e1a38d2a69.tar.gz |
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'library/cpp/yson/varint.cpp')
-rw-r--r-- | library/cpp/yson/varint.cpp | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/library/cpp/yson/varint.cpp b/library/cpp/yson/varint.cpp new file mode 100644 index 0000000000..d538ee3cff --- /dev/null +++ b/library/cpp/yson/varint.cpp @@ -0,0 +1,71 @@ +#include "varint.h" + +#include "zigzag.h" + +#include <util/generic/yexception.h> + +namespace NYson { + //////////////////////////////////////////////////////////////////////////////// + + int WriteVarUInt64(IOutputStream* output, ui64 value) { + bool stop = false; + int bytesWritten = 0; + while (!stop) { + ++bytesWritten; + ui8 byte = static_cast<ui8>(value | 0x80); + value >>= 7; + if (value == 0) { + stop = true; + byte &= 0x7F; + } + output->Write(byte); + } + return bytesWritten; + } + + int WriteVarInt32(IOutputStream* output, i32 value) { + return WriteVarUInt64(output, static_cast<ui64>(ZigZagEncode32(value))); + } + + int WriteVarInt64(IOutputStream* output, i64 value) { + return WriteVarUInt64(output, static_cast<ui64>(ZigZagEncode64(value))); + } + + int ReadVarUInt64(IInputStream* input, ui64* value) { + size_t count = 0; + ui64 result = 0; + + ui8 byte = 0; + do { + if (7 * count > 8 * sizeof(ui64)) { + ythrow yexception() << "The data is too long to read ui64"; + } + if (input->Read(&byte, 1) != 1) { + ythrow yexception() << "The data is too long to read ui64"; + } + result |= (static_cast<ui64>(byte & 0x7F)) << (7 * count); + ++count; + } while (byte & 0x80); + + *value = result; + return count; + } + + int ReadVarInt32(IInputStream* input, i32* value) { + ui64 varInt; + int bytesRead = ReadVarUInt64(input, &varInt); + if (varInt > Max<ui32>()) { + ythrow yexception() << "The data is too long to read ui64"; + } + *value = ZigZagDecode32(static_cast<ui32>(varInt)); + return bytesRead; + } + + int ReadVarInt64(IInputStream* input, i64* value) { + ui64 varInt; + int bytesRead = ReadVarUInt64(input, &varInt); + *value = ZigZagDecode64(varInt); + return bytesRead; + } + +} // namespace NYson |