From e0863aa50f3509b3102f33d694f7d129bc33fbcb Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 11 May 2017 11:15:36 -0700 Subject: [PATCH] Only open files for write if necessary --- libraries/shared/src/shared/Storage.cpp | 30 ++++++++++++++++++++++++- libraries/shared/src/shared/Storage.h | 5 ++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/libraries/shared/src/shared/Storage.cpp b/libraries/shared/src/shared/Storage.cpp index aae1f8455f..943dad9f56 100644 --- a/libraries/shared/src/shared/Storage.cpp +++ b/libraries/shared/src/shared/Storage.cpp @@ -68,7 +68,7 @@ StoragePointer FileStorage::create(const QString& filename, size_t size, const u } FileStorage::FileStorage(const QString& filename) : _file(filename) { - if (_file.open(QFile::ReadWrite)) { + if (_file.open(QFile::ReadOnly)) { _mapped = _file.map(0, _file.size()); if (_mapped) { _valid = true; @@ -90,3 +90,31 @@ FileStorage::~FileStorage() { _file.close(); } } + +void FileStorage::ensureWriteAccess() { + if (_hasWriteAccess) { + return; + } + + if (_mapped) { + if (!_file.unmap(_mapped)) { + throw std::runtime_error("Unable to unmap file"); + } + } + if (_file.isOpen()) { + _file.close(); + } + _valid = false; + + if (_file.open(QFile::ReadWrite)) { + _mapped = _file.map(0, _file.size()); + if (_mapped) { + _valid = true; + _hasWriteAccess = true; + } else { + qCWarning(storagelogging) << "Failed to map file " << _file.fileName(); + } + } else { + qCWarning(storagelogging) << "Failed to open file " << _file.fileName(); + } +} \ No newline at end of file diff --git a/libraries/shared/src/shared/Storage.h b/libraries/shared/src/shared/Storage.h index da5b773d52..4cad9fa083 100644 --- a/libraries/shared/src/shared/Storage.h +++ b/libraries/shared/src/shared/Storage.h @@ -60,11 +60,14 @@ namespace storage { FileStorage& operator=(const FileStorage& other) = delete; const uint8_t* data() const override { return _mapped; } - uint8_t* mutableData() override { return _mapped; } + uint8_t* mutableData() override { ensureWriteAccess(); return _mapped; } size_t size() const override { return _file.size(); } operator bool() const override { return _valid; } private: + void ensureWriteAccess(); + bool _valid { false }; + bool _hasWriteAccess { false }; QFile _file; uint8_t* _mapped { nullptr }; };