From 51ba45ae2697c99835b021e4e1b96faaf6610353 Mon Sep 17 00:00:00 2001 From: halx99 Date: Tue, 21 Jun 2016 10:52:25 +0800 Subject: [PATCH] Optimize, avoid unnecessary memory alloc & copy --- cocos/2d/CCFontFNT.cpp | 31 +++++++------------------------ 1 file changed, 7 insertions(+), 24 deletions(-) diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 4a314d24e0..e02fe2d080 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -274,39 +274,22 @@ void BMFontConfiguration::purgeFontDefDictionary() std::set* BMFontConfiguration::parseConfigFile(const std::string& controlFile) { - Data data = FileUtils::getInstance()->getDataFromFile(controlFile); - CCASSERT((!data.isNull()), "BMFontConfiguration::parseConfigFile | Open file error."); - if (data.isNull()) { + std::string data; + if (FileUtils::getInstance()->getContents(controlFile, &data) != FileUtils::Status::OK || data.empty()) + { return nullptr; } - - if (memcmp("BMF", data.getBytes(), 3) == 0) { + if (data.size() >= (sizeof("BMP") - 1) && memcmp("BMF", data.c_str(), sizeof("BMP") - 1) == 0) { // Handle fnt file of binary format - std::set* ret = parseBinaryConfigFile(data.getBytes(), data.getSize(), controlFile); + std::set* ret = parseBinaryConfigFile((unsigned char*)&data.front(), data.size(), controlFile); return ret; } - - if (data.getBytes()[0] == 0) + if (data[0] == 0) { CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); return nullptr; } - - // 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'; + auto contents = data.c_str(); std::set *validCharsString = new (std::nothrow) std::set();