Make ImgFile ignore operations before the file is opened

Before f65f9b9845ddf0a4050213cc36ef43c9c852a6c7 this would happen
automatically (since the stream member was always valid). It's now a
unique_ptr that's only initialized when the file is opened, so we need
to add guards for all the operations.
This commit is contained in:
Mihai Parparita 2024-11-25 22:37:37 +01:00
parent 04280ecda4
commit 08fa2f887d
2 changed files with 20 additions and 1 deletions

View File

@ -1,7 +1,9 @@
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
include(PlatformGlob)
include_directories("${PROJECT_SOURCE_DIR}")
include_directories("${PROJECT_SOURCE_DIR}"
"${PROJECT_SOURCE_DIR}/thirdparty/loguru/"
)
platform_glob(SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")

View File

@ -20,6 +20,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <utils/imgfile.h>
#include <loguru.hpp>
#include <fstream>
#include <sstream>
@ -59,17 +60,29 @@ bool ImgFile::open(const std::string &img_path)
void ImgFile::close()
{
if (!impl->stream) {
LOG_F(WARNING, "ImgFile::close before disk was opened, ignoring.");
return;
}
impl->stream.reset();
}
uint64_t ImgFile::size() const
{
if (!impl->stream) {
LOG_F(WARNING, "ImgFile::size before disk was opened, ignoring.");
return 0;
}
impl->stream->seekg(0, impl->stream->end);
return impl->stream->tellg();
}
uint64_t ImgFile::read(void* buf, uint64_t offset, uint64_t length) const
{
if (!impl->stream) {
LOG_F(WARNING, "ImgFile::read before disk was opened, ignoring.");
return 0;
}
impl->stream->seekg(offset, std::ios::beg);
impl->stream->read((char *)buf, length);
return impl->stream->gcount();
@ -77,6 +90,10 @@ uint64_t ImgFile::read(void* buf, uint64_t offset, uint64_t length) const
uint64_t ImgFile::write(const void* buf, uint64_t offset, uint64_t length)
{
if (!impl->stream) {
LOG_F(WARNING, "ImgFile::write before disk was opened, ignoring.");
return 0;
}
impl->stream->seekg(offset, std::ios::beg);
impl->stream->write((const char *)buf, length);
#if defined(WIN32) || defined(__APPLE__) || defined(__linux)