feat: faster reading of local files
should be around 10x faster then what it was before
This commit is contained in:
@@ -76,23 +76,32 @@ bool Folder::fileExists(const std::string& fileName)
|
|||||||
|
|
||||||
bool Folder::getFile(const std::string& fileName, std::shared_ptr<std::vector<char>>& fileData)
|
bool Folder::getFile(const std::string& fileName, std::shared_ptr<std::vector<char>>& fileData)
|
||||||
{
|
{
|
||||||
std::string realFileName = fileName;
|
constexpr char ymirPrefix[] = "d:/";
|
||||||
std::string ymirPrefix = "d:/";
|
std::string relative = fileName;
|
||||||
|
if (relative.rfind(ymirPrefix, 0) == 0)
|
||||||
|
relative.erase(0, sizeof(ymirPrefix) - 1);
|
||||||
|
|
||||||
if (fileName.find(ymirPrefix) == 0)
|
std::filesystem::path p = folderPath;
|
||||||
realFileName = realFileName.substr(ymirPrefix.length());
|
p /= relative;
|
||||||
|
|
||||||
realFileName = this->folderPath + "/" + realFileName;
|
std::ifstream file(p, std::ios::binary | std::ios::ate);
|
||||||
|
|
||||||
// Try to open the file
|
|
||||||
std::ifstream file(realFileName, std::ios::binary);
|
|
||||||
if (!file.is_open())
|
if (!file.is_open())
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// Read the file's contents
|
// get size in one call
|
||||||
fileData = std::make_shared<std::vector<char>>(
|
std::ifstream::pos_type sz = file.tellg();
|
||||||
std::istreambuf_iterator<char>(file),
|
if (sz < 0)
|
||||||
std::istreambuf_iterator<char>()
|
return false;
|
||||||
);
|
|
||||||
|
// allocate exactly once
|
||||||
|
auto buf = std::make_shared<std::vector<char>>(static_cast<size_t>(sz));
|
||||||
|
|
||||||
|
// rewind and read in one go
|
||||||
|
file.seekg(0, std::ios::beg);
|
||||||
|
file.read(buf->data(), sz);
|
||||||
|
if (!file)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
fileData = std::move(buf);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
Reference in New Issue
Block a user