Fix BufferedWriter triggering std::terminate on exception when writing

Fixes #2932
This commit is contained in:
Maxime Coste 2019-05-29 20:28:06 +10:00
parent 7de3ea786f
commit 262ef9b4e3

View File

@ -273,12 +273,13 @@ void write_to_file(StringView filename, StringView data)
struct BufferedWriter struct BufferedWriter
{ {
BufferedWriter(int fd) : fd{fd} {} BufferedWriter(int fd)
: m_fd{fd}, m_exception_count{std::uncaught_exceptions()} {}
~BufferedWriter() ~BufferedWriter() noexcept(false)
{ {
if (pos != 0) if (m_pos != 0 and m_exception_count == std::uncaught_exceptions())
Kakoune::write(fd, {buffer, pos}); Kakoune::write(m_fd, {m_buffer, m_pos});
} }
void write(StringView data) void write(StringView data)
@ -286,13 +287,13 @@ struct BufferedWriter
while (not data.empty()) while (not data.empty())
{ {
const ByteCount length = data.length(); const ByteCount length = data.length();
const ByteCount write_len = std::min(length, size - pos); const ByteCount write_len = std::min(length, size - m_pos);
memcpy(buffer + (int)pos, data.data(), (int)write_len); memcpy(m_buffer + (int)m_pos, data.data(), (int)write_len);
pos += write_len; m_pos += write_len;
if (pos == size) if (m_pos == size)
{ {
Kakoune::write(fd, {buffer, size}); Kakoune::write(m_fd, {m_buffer, size});
pos = 0; m_pos = 0;
} }
data = data.substr(write_len); data = data.substr(write_len);
} }
@ -300,9 +301,10 @@ struct BufferedWriter
private: private:
static constexpr ByteCount size = 4096; static constexpr ByteCount size = 4096;
int fd; int m_fd;
ByteCount pos = 0; int m_exception_count;
char buffer[(int)size]; ByteCount m_pos = 0;
char m_buffer[(int)size];
}; };