ClickHouse/dbms/src/IO/WriteBufferFromString.h

78 lines
1.5 KiB
C++
Raw Normal View History

2011-11-01 17:57:37 +00:00
#pragma once
#include <string>
2011-11-01 17:57:37 +00:00
#include <IO/WriteBuffer.h>
2011-11-01 17:57:37 +00:00
2011-11-03 20:30:12 +00:00
#define WRITE_BUFFER_FROM_STRING_INITIAL_SIZE_IF_EMPTY 32
2011-11-01 17:57:37 +00:00
2017-07-31 21:39:24 +00:00
2011-11-01 17:57:37 +00:00
namespace DB
{
2017-05-28 14:29:40 +00:00
/** Writes the data to a string.
* Note: before using the resulting string, destroy this object.
2011-11-01 17:57:37 +00:00
*/
class WriteBufferFromString : public WriteBuffer
{
private:
std::string & s;
2011-11-01 17:57:37 +00:00
void nextImpl() override
{
size_t old_size = s.size();
s.resize(old_size * 2);
internal_buffer = Buffer(reinterpret_cast<Position>(&s[old_size]), reinterpret_cast<Position>(&*s.end()));
working_buffer = internal_buffer;
}
2011-11-01 17:57:37 +00:00
2017-07-31 21:39:24 +00:00
protected:
void finish()
{
s.resize(count());
}
2012-06-18 06:19:13 +00:00
2011-11-01 17:57:37 +00:00
public:
WriteBufferFromString(std::string & s_)
: WriteBuffer(reinterpret_cast<Position>(&s_[0]), s_.size()), s(s_)
{
if (s.empty())
{
s.resize(WRITE_BUFFER_FROM_STRING_INITIAL_SIZE_IF_EMPTY);
set(reinterpret_cast<Position>(&s[0]), s.size());
}
}
~WriteBufferFromString() override
{
finish();
}
2011-11-01 17:57:37 +00:00
};
2017-07-31 21:39:24 +00:00
namespace detail
{
/// For correct order of initialization.
class StringHolder
{
protected:
std::string value;
};
}
2017-08-01 13:31:38 +00:00
2017-07-31 21:39:24 +00:00
/// Creates the string by itself and allows to get it.
class WriteBufferFromOwnString : public detail::StringHolder, public WriteBufferFromString
2017-07-31 21:39:24 +00:00
{
public:
WriteBufferFromOwnString() : WriteBufferFromString(value) {}
2017-07-31 21:39:24 +00:00
std::string & str()
{
finish();
return value;
2017-07-31 21:39:24 +00:00
}
};
2011-11-01 17:57:37 +00:00
}