diff --git a/src/core/Buffer.cc b/src/core/Buffer.cc index 5b07d3d..4978062 100644 --- a/src/core/Buffer.cc +++ b/src/core/Buffer.cc @@ -55,8 +55,11 @@ bool Buffer::load_from_file(const char * filename) piece_table = std::make_shared(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; } } diff --git a/src/core/PieceTable.cc b/src/core/PieceTable.cc index b39deeb..959dbf2 100644 --- a/src/core/PieceTable.cc +++ b/src/core/PieceTable.cc @@ -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++; diff --git a/src/core/PieceTable.h b/src/core/PieceTable.h index 07b2b9c..b990b09 100644 --- a/src/core/PieceTable.h +++ b/src/core/PieceTable.h @@ -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;