Avoid holding entire file in memory

Previously we need a file buffer that is as large as the file size and
this could be a problem when user has less free memory available or
having very large data. Now with the help of `FileOutputIterator`,
we can have a much smaller, fixed size immediate file buffer and also
the code looks nice with `lt::bencode()`.
This commit is contained in:
Chocobo1
2020-04-01 14:25:00 +08:00
parent 96c5af7ae9
commit 9f281c2d25
6 changed files with 158 additions and 15 deletions

View File

@@ -47,6 +47,7 @@
#include "base/exceptions.h"
#include "base/global.h"
#include "base/utils/fs.h"
#include "base/utils/io.h"
#include "base/utils/misc.h"
#include "infohash.h"
#include "trackerentry.h"
@@ -166,12 +167,12 @@ void TorrentInfo::saveToFile(const QString &path) const
#endif
const lt::entry torrentEntry = torrentCreator.generate();
QByteArray out;
out.reserve(1024 * 1024); // most torrent file sizes are under 1 MB
lt::bencode(std::back_inserter(out), torrentEntry);
QFile torrentFile {path};
if (!torrentFile.open(QIODevice::WriteOnly))
throw RuntimeError {torrentFile.errorString()};
QFile torrentFile{path};
if (!torrentFile.open(QIODevice::WriteOnly) || (torrentFile.write(out) != out.size()))
lt::bencode(Utils::IO::FileDeviceOutputIterator {torrentFile}, torrentEntry);
if (torrentFile.error() != QFileDevice::NoError)
throw RuntimeError {torrentFile.errorString()};
}