diff options
author | Stanislaw Halik <sthalik@misaki.pl> | 2023-03-05 23:02:03 +0100 |
---|---|---|
committer | Stanislaw Halik <sthalik@misaki.pl> | 2023-03-05 23:02:03 +0100 |
commit | af04c19b70e723f25d561e5fd806ab713c441434 (patch) | |
tree | ff9fcc6b0089495e393dda4e1114212ec997ec42 /compat | |
parent | c2b45b12457bad6a3f25aa310b20e6dd15265187 (diff) |
compat: add portable setenv(3)
Diffstat (limited to 'compat')
-rw-r--r-- | compat/setenv.cpp | 37 | ||||
-rw-r--r-- | compat/setenv.hpp | 13 |
2 files changed, 50 insertions, 0 deletions
diff --git a/compat/setenv.cpp b/compat/setenv.cpp new file mode 100644 index 00000000..cb98fa3d --- /dev/null +++ b/compat/setenv.cpp @@ -0,0 +1,37 @@ +#include "setenv.hpp" +#include <cerrno> +#include <cstdlib> +#include <cstring> +#include <Corrade/Containers/String.h> +#include <Corrade/Containers/StringIterable.h> + +namespace floormat { + +#ifdef _WIN32 +int setenv(const char* name, const char* value, int overwrite) +{ + if (!std::strchr(name, '=') || !value || !*value) + { + errno = EINVAL; + return -1; + } + if (!overwrite) + if (const auto* s = std::getenv(name); s && *s) + return 0; + + return _putenv("="_s.join(StringIterable{name, value}).data()); +} + +int unsetenv(const char* name) +{ + if (!name || !*name) + { + errno = EINVAL; + return -1; + } + + return _putenv("="_s.join(StringIterable{name, ""_s}).data()); +} +#endif + +} // namespace floormat diff --git a/compat/setenv.hpp b/compat/setenv.hpp new file mode 100644 index 00000000..5dff666a --- /dev/null +++ b/compat/setenv.hpp @@ -0,0 +1,13 @@ +#pragma once +#include <cstdlib> + +#ifdef _WIN32 +namespace floormat { +using std::getenv; +int setenv(const char* name, const char* value, int overwrite); +int unsetenv(const char* name); +} // namespace floormat +#else +#include <cstdlib> +namespace floormat { using std::getenv; using std::setenv; using std::unsetenv; } +#endif |