forked from metin2/client
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)
|
||||
{
|
||||
std::string realFileName = fileName;
|
||||
std::string ymirPrefix = "d:/";
|
||||
constexpr char ymirPrefix[] = "d:/";
|
||||
std::string relative = fileName;
|
||||
if (relative.rfind(ymirPrefix, 0) == 0)
|
||||
relative.erase(0, sizeof(ymirPrefix) - 1);
|
||||
|
||||
if (fileName.find(ymirPrefix) == 0)
|
||||
realFileName = realFileName.substr(ymirPrefix.length());
|
||||
std::filesystem::path p = folderPath;
|
||||
p /= relative;
|
||||
|
||||
realFileName = this->folderPath + "/" + realFileName;
|
||||
|
||||
// Try to open the file
|
||||
std::ifstream file(realFileName, std::ios::binary);
|
||||
std::ifstream file(p, std::ios::binary | std::ios::ate);
|
||||
if (!file.is_open())
|
||||
return false;
|
||||
|
||||
// Read the file's contents
|
||||
fileData = std::make_shared<std::vector<char>>(
|
||||
std::istreambuf_iterator<char>(file),
|
||||
std::istreambuf_iterator<char>()
|
||||
);
|
||||
// get size in one call
|
||||
std::ifstream::pos_type sz = file.tellg();
|
||||
if (sz < 0)
|
||||
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;
|
||||
}
|
Reference in New Issue
Block a user