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_pull/detail/byte_writer.h | |
download | ydb-1110808a9d39d4b808aef724c861a2e1a38d2a69.tar.gz |
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'library/cpp/yson_pull/detail/byte_writer.h')
-rw-r--r-- | library/cpp/yson_pull/detail/byte_writer.h | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/library/cpp/yson_pull/detail/byte_writer.h b/library/cpp/yson_pull/detail/byte_writer.h new file mode 100644 index 0000000000..dc1d4b4b96 --- /dev/null +++ b/library/cpp/yson_pull/detail/byte_writer.h @@ -0,0 +1,77 @@ +#pragma once + +#include "macros.h" + +#include <library/cpp/yson_pull/output.h> + +#include <util/system/types.h> + +#include <cstddef> +#include <cstring> + +namespace NYsonPull { + namespace NDetail { + template <class StreamCounter> + class byte_writer { + NYsonPull::NOutput::IStream& stream_; + StreamCounter stream_counter_; + + public: + byte_writer(NYsonPull::NOutput::IStream& stream) + : stream_(stream) + { + } + + // const-ness added to prevent direct stream mutation + const NYsonPull::NOutput::IStream& stream() { + return stream_; + } + const StreamCounter& counter() { + return stream_counter_; + } + + void flush_buffer() { + stream_.flush_buffer(); + } + + void advance(size_t bytes) { + auto& buf = stream_.buffer(); + stream_counter_.update( + buf.pos(), + buf.pos() + bytes); + buf.advance(bytes); + } + + void write(ui8 c) { + auto& buf = stream_.buffer(); + if (Y_LIKELY(!buf.is_full())) { + *buf.pos() = c; + advance(1); + } else { + auto ptr = reinterpret_cast<char*>(&c); + stream_counter_.update(&c, &c + 1); + stream_.flush_buffer({ptr, 1}); + } + } + + void write(const ui8* data, size_t size) { + auto& buf = stream_.buffer(); + auto free_buf = buf.available(); + if (Y_LIKELY(size < free_buf)) { + ::memcpy(buf.pos(), data, size); + advance(size); + } else { + if (!buf.is_full()) { + ::memcpy(buf.pos(), data, free_buf); + advance(free_buf); + data += free_buf; + size -= free_buf; + } + stream_counter_.update(data, data + size); + stream_.flush_buffer({reinterpret_cast<const char*>(data), + size}); + } + } + }; + } +} |