Expose BufferedWriter

This commit is contained in:
Maxime Coste 2021-07-31 09:44:24 +10:00
parent 914f4f8c19
commit a566a22cbc
2 changed files with 38 additions and 37 deletions

View File

@ -279,43 +279,6 @@ void write_to_file(StringView filename, StringView data)
write(fd, data);
}
struct BufferedWriter
{
BufferedWriter(int fd)
: m_fd{fd}, m_exception_count{std::uncaught_exceptions()} {}
~BufferedWriter() noexcept(false)
{
if (m_pos != 0 and m_exception_count == std::uncaught_exceptions())
Kakoune::write(m_fd, {m_buffer, m_pos});
}
void write(StringView data)
{
while (not data.empty())
{
const ByteCount length = data.length();
const ByteCount write_len = std::min(length, size - m_pos);
memcpy(m_buffer + (int)m_pos, data.data(), (int)write_len);
m_pos += write_len;
if (m_pos == size)
{
Kakoune::write(m_fd, {m_buffer, size});
m_pos = 0;
}
data = data.substr(write_len);
}
}
private:
static constexpr ByteCount size = 4096;
int m_fd;
int m_exception_count;
ByteCount m_pos = 0;
char m_buffer[(int)size];
};
void write_buffer_to_fd(Buffer& buffer, int fd)
{
auto eolformat = buffer.options()["eolformat"].get<EolFormat>();

View File

@ -10,6 +10,7 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <cstring>
namespace Kakoune
{
@ -121,6 +122,43 @@ CandidateList complete_filename(StringView prefix, const Regex& ignore_regex,
CandidateList complete_command(StringView prefix, ByteCount cursor_pos = -1);
template<int buffer_size = 4096>
struct BufferedWriter
{
BufferedWriter(int fd)
: m_fd{fd}, m_exception_count{std::uncaught_exceptions()} {}
~BufferedWriter() noexcept(false)
{
if (m_pos != 0 and m_exception_count == std::uncaught_exceptions())
Kakoune::write(m_fd, {m_buffer, m_pos});
}
void write(StringView data)
{
while (not data.empty())
{
const ByteCount length = data.length();
const ByteCount write_len = std::min(length, size - m_pos);
memcpy(m_buffer + (int)m_pos, data.data(), (int)write_len);
m_pos += write_len;
if (m_pos == size)
{
Kakoune::write(m_fd, {m_buffer, size});
m_pos = 0;
}
data = data.substr(write_len);
}
}
private:
static constexpr ByteCount size = buffer_size;
int m_fd;
int m_exception_count;
ByteCount m_pos = 0;
char m_buffer[(int)size];
};
}
#endif // file_hh_INCLUDED