From: Nicholas Hutchinson Date: Wed, 24 Feb 2021 19:32:20 +0000 (+0000) Subject: Fix Util::read_file truncating files if size_hint is an underestimate (#808) X-Git-Tag: v4.2.1~27 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=577656afb5f4a0ccdebe24409fa15b2ea60a3f58;p=thirdparty%2Fccache.git Fix Util::read_file truncating files if size_hint is an underestimate (#808) If the size_hint passed to read_file was an underestimate, or the platform's `stat()` implementation gives an inaccurate file size (e.g. MinGW) then `Util::read_file()` would only issue a single `read()` call instead of reading the entire file. Fixes #803. --- diff --git a/src/Util.cpp b/src/Util.cpp index 71de5f9cd..f49708fd4 100644 --- a/src/Util.cpp +++ b/src/Util.cpp @@ -1180,7 +1180,7 @@ read_file(const std::string& path, size_t size_hint) result.resize(size_hint); while (true) { - if (pos > result.size()) { + if (pos == result.size()) { result.resize(2 * result.size()); } const size_t max_read = result.size() - pos; diff --git a/unittest/test_Util.cpp b/unittest/test_Util.cpp index 56d4368f7..cb2be415c 100644 --- a/unittest/test_Util.cpp +++ b/unittest/test_Util.cpp @@ -820,6 +820,10 @@ TEST_CASE("Util::read_file and Util::write_file") #else CHECK(data == "carpet\n\n"); #endif + + Util::write_file("size_hint_test", std::string(8192, '\0')); + CHECK(Util::read_file("size_hint_test", 4096 /*size_hint*/).size() == 8192); + CHECK_THROWS_WITH(Util::read_file("does/not/exist"), "No such file or directory");