diff --git a/src/common/mm_io.cpp b/src/common/mm_io.cpp index 52dda1862..2d2971065 100644 --- a/src/common/mm_io.cpp +++ b/src/common/mm_io.cpp @@ -161,6 +161,16 @@ mm_file_io_c::prepare_path(const std::string &path) { throw mtx::mm_io::create_directory_x(path, strerror(error_code.value()), error_code.value()); } +memory_cptr +mm_file_io_c::slurp(std::string const &file_name) { + mm_file_io_c in(file_name, MODE_READ); + auto content = memory_c::alloc(in.get_size()); + if (in.get_size() != in.read(content, in.get_size())) + throw mtx::mm_io::end_of_file_x{}; + + return content; +} + uint64 mm_file_io_c::getFilePointer() { return m_current_position; diff --git a/src/common/mm_io.h b/src/common/mm_io.h index a8552d7ee..d8c34f4fd 100644 --- a/src/common/mm_io.h +++ b/src/common/mm_io.h @@ -216,6 +216,7 @@ public: virtual ~mm_file_io_c(); static void prepare_path(const std::string &path); + static memory_cptr slurp(std::string const &file_name); virtual uint64 getFilePointer(); #if defined(SYS_WINDOWS) diff --git a/tests/unit/common/mm_io.cpp b/tests/unit/common/mm_io.cpp new file mode 100644 index 000000000..dd7f53a6a --- /dev/null +++ b/tests/unit/common/mm_io.cpp @@ -0,0 +1,17 @@ +#include "common/common_pch.h" + +#include "gtest/gtest.h" +#include "tests/unit/util.h" + +namespace { + +TEST(MmIo, Slurp) { + memory_cptr m; + + ASSERT_NO_THROW(m = mm_file_io_c::slurp("tests/unit/data/text/chunky_bacon.txt")); + EXPECT_EQ(*m, std::string{"Chunky Bacon\n"}); + + ASSERT_THROW(mm_file_io_c::slurp("doesnotexist"), mtx::mm_io::exception); +} + +} diff --git a/tests/unit/data/text/chunky_bacon.txt b/tests/unit/data/text/chunky_bacon.txt new file mode 100644 index 000000000..e8bf5fa25 --- /dev/null +++ b/tests/unit/data/text/chunky_bacon.txt @@ -0,0 +1 @@ +Chunky Bacon diff --git a/tests/unit/util.h b/tests/unit/util.h index 5629a65e8..4e6c308f6 100644 --- a/tests/unit/util.h +++ b/tests/unit/util.h @@ -51,4 +51,10 @@ public: } +inline bool +operator ==(memory_c const &a, + std::string const &b) { + return (a.get_size() == b.length()) && !memcmp(a.get_buffer(), b.c_str(), b.length()); +} + #endif // MTX_TESTS_UNIT_UTIL_H