From cf1349915807ffb1f119f108602583271f58e89d Mon Sep 17 00:00:00 2001 From: Daniel Wolf Date: Sun, 18 Sep 2016 22:00:08 +0200 Subject: [PATCH] Caching bin path --- src/platformTools.cpp | 47 +++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/src/platformTools.cpp b/src/platformTools.cpp index 2dcda5a..b8352df 100644 --- a/src/platformTools.cpp +++ b/src/platformTools.cpp @@ -11,29 +11,32 @@ using boost::filesystem::path; using std::string; path getBinPath() { - try { - // Determine path length - int pathLength = wai_getExecutablePath(nullptr, 0, nullptr); - if (pathLength == -1) { - throw std::runtime_error("Error determining path length."); + static const path binPath = [] { + try { + // Determine path length + int pathLength = wai_getExecutablePath(nullptr, 0, nullptr); + if (pathLength == -1) { + throw std::runtime_error("Error determining path length."); + } + + // Get path + // Note: According to documentation, pathLength does *not* include the trailing zero. Actually, it does. + // In case there are situations where it doesn't, we allocate one character more. + std::vector buffer(pathLength + 1); + if (wai_getExecutablePath(buffer.data(), buffer.size(), nullptr) == -1) { + throw std::runtime_error("Error reading path."); + } + buffer[pathLength] = 0; + + // Convert to boost::filesystem::path + string pathString(buffer.data()); + static path binPath(boost::filesystem::canonical(pathString).make_preferred()); + return binPath; + } catch (...) { + std::throw_with_nested(std::runtime_error("Could not determine path of bin directory.")); } - - // Get path - // Note: According to documentation, pathLength does *not* include the trailing zero. Actually, it does. - // In case there are situations where it doesn't, we allocate one character more. - std::vector buffer(pathLength + 1); - if (wai_getExecutablePath(buffer.data(), buffer.size(), nullptr) == -1) { - throw std::runtime_error("Error reading path."); - } - buffer[pathLength] = 0; - - // Convert to boost::filesystem::path - string pathString(buffer.data()); - static path binPath(boost::filesystem::canonical(pathString).make_preferred()); - return binPath; - } catch (...) { - std::throw_with_nested(std::runtime_error("Could not determine path of bin directory.") ); - } + }(); + return binPath; } path getBinDirectory() {