initial commit
This commit is contained in:
57
client/core/persistence/PersistentBinaryObject.cpp
Normal file
57
client/core/persistence/PersistentBinaryObject.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
#include "persistence/PersistentBinaryObject.h"
|
||||
|
||||
#include <QDataStream>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
|
||||
namespace core {
|
||||
|
||||
bool PersistentBinaryObject::saveToFile(const QString& absolutePath) const {
|
||||
if (absolutePath.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
const auto parent = QFileInfo(absolutePath).absolutePath();
|
||||
if (!QFileInfo(parent).exists()) {
|
||||
QDir().mkpath(parent);
|
||||
}
|
||||
|
||||
const QString tmpPath = absolutePath + QStringLiteral(".tmp");
|
||||
QFile f(tmpPath);
|
||||
if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QDataStream ds(&f);
|
||||
ds.setVersion(QDataStream::Qt_5_15);
|
||||
ds << quint32(recordMagic()) << quint32(recordFormatVersion());
|
||||
writeBody(ds);
|
||||
|
||||
f.close();
|
||||
if (f.error() != QFile::NoError) {
|
||||
QFile::remove(tmpPath);
|
||||
return false;
|
||||
}
|
||||
QFile::remove(absolutePath);
|
||||
return QFile::rename(tmpPath, absolutePath);
|
||||
}
|
||||
|
||||
bool PersistentBinaryObject::loadFromFile(const QString& absolutePath) {
|
||||
QFile f(absolutePath);
|
||||
if (!f.open(QIODevice::ReadOnly)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QDataStream ds(&f);
|
||||
ds.setVersion(QDataStream::Qt_5_15);
|
||||
|
||||
quint32 magic = 0;
|
||||
quint32 version = 0;
|
||||
ds >> magic >> version;
|
||||
if (ds.status() != QDataStream::Ok || magic != recordMagic() || version != recordFormatVersion()) {
|
||||
return false;
|
||||
}
|
||||
return readBody(ds);
|
||||
}
|
||||
|
||||
} // namespace core
|
||||
Reference in New Issue
Block a user