From 3fae068b9bb52e05b51f40e8a17e13efc7a1f20d Mon Sep 17 00:00:00 2001 From: Michele Caini Date: Thu, 17 Oct 2019 22:47:57 +0200 Subject: [PATCH] added Utilities::OS::env overload to iterate all env variables --- src/uvw/util.hpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/uvw/util.hpp b/src/uvw/util.hpp index 3da5ca68..0d31f6a3 100644 --- a/src/uvw/util.hpp +++ b/src/uvw/util.hpp @@ -1,6 +1,7 @@ #pragma once +#include #include #include #include @@ -554,6 +555,38 @@ struct Utilities { return (0 == (value.empty() ? uv_os_unsetenv(name.c_str()) : uv_os_setenv(name.c_str(), value.c_str()))); } + /** + * @brief Retrieves all environment variables and iterates them. + * + * Environment variables are passed one at a time to the callback in the + * form of `std::string_view`s.
+ * The signature of the function call operator must be such that it + * accepts two parameters, the name and the value of the i-th variable. + * + * @tparam Func Type of a function object to which to pass environment + * variables. + * @param func A function object to which to pass environment variables. + * @return True in case of success, false otherwise. + */ + template + static std::enable_if_t, bool> + env(Func func) noexcept { + uv_env_item_t *items = nullptr; + int count{}; + + const bool ret = (uv_os_environ(&items, &count) == 0); + + if(ret) { + for(int pos = 0; pos < count; ++pos) { + func(std::string_view{items[pos].name}, std::string_view{items[pos].value}); + } + + uv_os_free_environ(items, count); + } + + return ret; + } + /** * @brief Returns the hostname. * @return The hostname, an empty string in case of errors.