Skip to content

Commit

Permalink
[#70] fix(buffer): when mmap-ing, don't fail on empty files
Browse files Browse the repository at this point in the history
This patch introduces a fix to a long-standing problem with the buffer `mmap`-ing behaviour and empty files. Previously, when trying to map an empty file, the system would throw an exception which caused a bunch of problems in implementations. Now, it checks the file size before trying to map it and if the size is zero, the empty buffer is returned.

Closes: #70
  • Loading branch information
lmichaelis committed Jul 1, 2023
1 parent f46144f commit ed37464
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
4 changes: 4 additions & 0 deletions source/buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,10 @@ namespace phoenix {
}

buffer buffer::mmap(const std::filesystem::path& path, bool readonly) {
auto file_size = std::filesystem::file_size(path);
if (file_size == 0)
return buffer::empty();

if (readonly) {
return buffer {std::make_shared<detail::mmap_backing<mio::access_mode::read>>(path)};
}
Expand Down
Empty file added tests/samples/empty.txt
Empty file.
9 changes: 9 additions & 0 deletions tests/test_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -559,4 +559,13 @@ TEST_SUITE("buffer") {
auto buf = phoenix::buffer::allocate(10);
CHECK_FALSE(empty == buf);
}

TEST_CASE("buffer(mmap)") {
SUBCASE("empty file") {
auto buf = phoenix::buffer::mmap("samples/empty.txt");
CHECK_EQ(buf.limit(), 0);
CHECK_EQ(buf.capacity(), 0);
CHECK_THROWS_AS((void) buf.get_char(), phoenix::buffer_underflow);
}
}
}

0 comments on commit ed37464

Please sign in to comment.