diff --git a/src/block.h b/src/block.h index cd3a48e..13daea1 100644 --- a/src/block.h +++ b/src/block.h @@ -25,13 +25,18 @@ class block { public: block(): line_bytes_(0) { + lines_.reserve(max_lines_per_block_); + } + + bool empty() const { + return line_bytes_ == 0; } void add_line(std::vector &&line) { assert(!line.empty()); assert(line_fits(line.size())); line_bytes_ += line.size(); - lines_.push_back(line); + lines_.emplace_back(line); } bool line_fits(unsigned size) { @@ -40,7 +45,7 @@ class block { } void flush(FILE *f) { - if (line_bytes_) { + if (!empty()) { fprintf(f, "%dw%c%c", line_bytes_ + 2, 0, static_cast(lines_.size())); diff --git a/test/test_block.cc b/test/test_block.cc index 0b39a30..5c840b0 100644 --- a/test/test_block.cc +++ b/test/test_block.cc @@ -24,7 +24,20 @@ typedef std::vector vec; const lest::test specification[] = { - "Block line limit", + "A block is created empty", + [] { + block b; + EXPECT(b.empty()); + }, + + "Adding a line makes a block no longer empty", + [] { + block b; + b.add_line(vec{1}); + EXPECT(!b.empty()); + }, + + "A block can contain 128 lines", [] { block b; for (int i = 0; i < 128; ++i) { @@ -34,7 +47,7 @@ const lest::test specification[] = { EXPECT(!b.line_fits(1)); }, - "Block size limit", + "A block has a size limit of about 16 kilobyte", [] { block b; for (int i = 0; i < 16; ++i) { @@ -44,30 +57,33 @@ const lest::test specification[] = { EXPECT(!b.line_fits(400)); }, - "Flush", + "Flushing an empty block does nothing", [] { block b; - { - tempfile f; - b.flush(f.file()); - EXPECT(f.data().empty()); - } - for (uint8_t n = 0; n < 10; n += 2) { - vec line = {n, static_cast(n+1)}; - EXPECT(b.line_fits(line.size())); - b.add_line(std::move(line)); - } - { - tempfile f; - b.flush(f.file()); - EXPECT(( f.data() == vec{'1','2','w',0,5,0,1,2,3,4,5,6,7,8,9} )); - } - { - tempfile f; - b.flush(f.file()); - EXPECT(f.data().empty()); - } + tempfile f; + b.flush(f.file()); + EXPECT(f.data().empty()); }, + + "Flush() writes the lines to a file with a proper header", + [] { + block b; + for (uint8_t n = 1; n < 6; ++n) { + b.add_line(vec{n, n}); + } + tempfile f; + b.flush(f.file()); + EXPECT(( f.data() == vec{'1','2','w',0,5,1,1,2,2,3,3,4,4,5,5} )); + }, + + "After flush() a block is empty again", + [] { + block b; + b.add_line(vec{1}); + tempfile f; + b.flush(f.file()); + EXPECT(b.empty()); + } }; int main() { diff --git a/test/test_line.cc b/test/test_line.cc index fd89c57..38ab10e 100644 --- a/test/test_line.cc +++ b/test/test_line.cc @@ -53,7 +53,7 @@ const lest::test specification[] = { [] { EXPECT(( encode_line(vec{1,2,3}) == (vec{1,sub(0,2),1,2,3}) )); }, - + "Encoding a (non-initial) blank line", [] { EXPECT(( encode_line(vec{0,0,0}, vec{1,2,3}) == vec{0xFF} ));