Optimize, avoid unnecessary memory alloc & copy

This commit is contained in:
halx99 2016-06-21 10:52:25 +08:00 committed by GitHub
parent c25550e1a4
commit 51ba45ae26
1 changed files with 7 additions and 24 deletions

View File

@ -274,39 +274,22 @@ void BMFontConfiguration::purgeFontDefDictionary()
std::set<unsigned int>* BMFontConfiguration::parseConfigFile(const std::string& controlFile) std::set<unsigned int>* BMFontConfiguration::parseConfigFile(const std::string& controlFile)
{ {
Data data = FileUtils::getInstance()->getDataFromFile(controlFile); std::string data;
CCASSERT((!data.isNull()), "BMFontConfiguration::parseConfigFile | Open file error."); if (FileUtils::getInstance()->getContents(controlFile, &data) != FileUtils::Status::OK || data.empty())
if (data.isNull()) { {
return nullptr; return nullptr;
} }
if (data.size() >= (sizeof("BMP") - 1) && memcmp("BMF", data.c_str(), sizeof("BMP") - 1) == 0) {
if (memcmp("BMF", data.getBytes(), 3) == 0) {
// Handle fnt file of binary format // Handle fnt file of binary format
std::set<unsigned int>* ret = parseBinaryConfigFile(data.getBytes(), data.getSize(), controlFile); std::set<unsigned int>* ret = parseBinaryConfigFile((unsigned char*)&data.front(), data.size(), controlFile);
return ret; return ret;
} }
if (data[0] == 0)
if (data.getBytes()[0] == 0)
{ {
CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str());
return nullptr; return nullptr;
} }
auto contents = data.c_str();
// Handle fnt file of string format, allocate one extra byte '\0' at the end since c string needs it.
// 'strchr' finds a char until it gets a '\0', if 'contents' self doesn't end with '\0',
// 'strchr' will search '\n' out of 'contents' 's buffer size, it will trigger potential and random crashes since
// lineLength may bigger than 512 and 'memcpy(line, contents + parseCount, lineLength);' will cause stack buffer overflow.
// Please note that 'contents' needs to be freed before this function returns.
auto contents = (char*)malloc(data.getSize() + 1);
if (contents == nullptr)
{
CCLOGERROR("BMFontConfiguration::parseConfigFile, out of memory!");
return nullptr;
}
memcpy(contents, data.getBytes(), data.getSize());
// Ensure the last byte is '\0'
contents[data.getSize()] = '\0';
std::set<unsigned int> *validCharsString = new (std::nothrow) std::set<unsigned int>(); std::set<unsigned int> *validCharsString = new (std::nothrow) std::set<unsigned int>();