summaryrefslogtreecommitdiffstats
path: root/src/corelib/global/qglobal.cpp
diff options
context:
space:
mode:
authorMarc Mutz <marc.mutz@kdab.com>2012-08-03 12:46:15 +0200
committerQt by Nokia <qt-info@nokia.com>2012-08-09 21:27:09 +0200
commitfa08b143f3deb1db11984a88aa34d541c19c9fc5 (patch)
treeabbe3ff4f15f148d97edf6bd13eed79a4294d318 /src/corelib/global/qglobal.cpp
parent977441f61cc42b7f29e48980577105323fbd3b47 (diff)
QtGlobal: (new) qEnvironmentVariableIs{Set,Empty}()
These functions are a faster version of {,!}qgetenv().is{Null,Empty}(), a common pattern in Qt code. Their main advantage is that they don't need to allocate memory, so they can be used in noexcept functions, or dynamic initialisation of namespace-scope statics, because throwing in these contexts invokes std::terminate(). Change-Id: I651c5bd72f450b5d7df76590f8791572fe992af5 Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Diffstat (limited to 'src/corelib/global/qglobal.cpp')
-rw-r--r--src/corelib/global/qglobal.cpp56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/corelib/global/qglobal.cpp b/src/corelib/global/qglobal.cpp
index 17cb9db86f..b60e7495c6 100644
--- a/src/corelib/global/qglobal.cpp
+++ b/src/corelib/global/qglobal.cpp
@@ -2085,6 +2085,62 @@ QByteArray qgetenv(const char *varName)
/*!
\relates <QtGlobal>
+ \internal
+
+ This function checks whether the environment variable \a varName
+ is empty.
+
+ Equivalent to
+ \code
+ qgetenv(varName).isEmpty()
+ \endcode
+ except that it's potentially much faster, and can't throw exceptions.
+
+ \sa qgetenv(), qEnvironmentVariableIsSet()
+*/
+bool qEnvironmentVariableIsEmpty(const char *varName) Q_DECL_NOEXCEPT
+{
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+ // we provide a buffer that can only hold the empty string, so
+ // when the env.var isn't empty, we'll get an ERANGE error (buffer
+ // too small):
+ size_t dummy;
+ char buffer = '\0';
+ return getenv_s(&dummy, &buffer, 1, varName) != ERANGE;
+#else
+ const char * const value = ::getenv(varName);
+ return !value || !*value;
+#endif
+}
+
+/*!
+ \relates <QtGlobal>
+ \internal
+
+ This function checks whether the environment variable \a varName
+ is set.
+
+ Equivalent to
+ \code
+ !qgetenv(varName).isNull()
+ \endcode
+ except that it's potentially much faster, and can't throw exceptions.
+
+ \sa qgetenv(), qEnvironmentVariableIsEmpty()
+*/
+bool qEnvironmentVariableIsSet(const char *varName) Q_DECL_NOEXCEPT
+{
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+ size_t requiredSize = 0;
+ (void)getenv_s(&requiredSize, 0, 0, varName);
+ return requiredSize != 0;
+#else
+ return ::getenv(varName) != 0;
+#endif
+}
+
+/*!
+ \relates <QtGlobal>
This function sets the \a value of the environment variable named
\a varName. It will create the variable if it does not exist. It