Preserve whether there is a EOL at EOF when writing the file

This commit is contained in:
Josh Holtrop 2016-07-24 17:24:00 -04:00
parent e66130b603
commit 63b3848424
3 changed files with 20 additions and 4 deletions

View File

@ -55,8 +55,11 @@ bool Buffer::load_from_file(const char * filename)
piece_table = std::make_shared<PieceTable>(m_file_buffer, m_file_buffer_size);
for (auto it = text_loader.begin(); it != text_loader.end(); it++)
{
auto next = it;
next++;
bool eol = next != text_loader.end();
/* TODO: correctly calculate n_chars based on current file encoding. */
piece_table->append_initial_line_piece(it->first, it->second, it->second);
piece_table->append_initial_line_piece(it->first, it->second, it->second, eol);
}
m_eol_at_eof = text_loader.get_eol_at_eof();
@ -93,6 +96,7 @@ bool Buffer::write_to_file(const char * filename)
return false;
}
uint32_t bytes_written = 0u;
for (auto pd = piece_table->start_descriptor->next;
pd != piece_table->end_descriptor;
pd = pd->next)
@ -101,12 +105,22 @@ bool Buffer::write_to_file(const char * filename)
{
return false;
}
bytes_written += pd->length;
if (pd->eol())
{
if (!file.write((const uint8_t *)eol_seq, eol_len))
{
return false;
}
bytes_written += eol_len;
}
}
if (m_eol_at_eof && bytes_written > 0u)
{
if (!file.write((const uint8_t *)eol_seq, eol_len))
{
return false;
}
}

View File

@ -11,14 +11,16 @@ PieceTable::PieceTable(const uint8_t * file_buffer, unsigned long file_buffer_si
m_piece_descriptor_index = 2u;
}
void PieceTable::append_initial_line_piece(uint8_t * start, uint32_t length, uint32_t n_chars)
void PieceTable::append_initial_line_piece(uint8_t * start, uint32_t length, uint32_t n_chars, bool eol)
{
PieceDescriptor * pd = add_piece_descriptor();
pd->prev = end_descriptor->prev;
pd->next = end_descriptor;
pd->start = start;
pd->length = length;
pd->n_chars = n_chars | PIECE_DESCRIPTOR_N_CHARS_EOL_FLAG_MASK;
pd->n_chars = n_chars;
if (eol)
pd->n_chars |= PIECE_DESCRIPTOR_N_CHARS_EOL_FLAG_MASK;
end_descriptor->prev->next = pd;
end_descriptor->prev = pd;
m_num_lines++;

View File

@ -68,7 +68,7 @@ public:
PieceDescriptor * start_descriptor;
PieceDescriptor * end_descriptor;
void append_initial_line_piece(uint8_t * start, uint32_t length, uint32_t n_chars);
void append_initial_line_piece(uint8_t * start, uint32_t length, uint32_t n_chars, bool eol);
protected:
const uint8_t * m_file_buffer;