From af04c19b70e723f25d561e5fd806ab713c441434 Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Sun, 5 Mar 2023 23:02:03 +0100 Subject: compat: add portable setenv(3) --- compat/setenv.cpp | 37 +++++++++++++++++++++++++++++++++++++ compat/setenv.hpp | 13 +++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 compat/setenv.cpp create mode 100644 compat/setenv.hpp 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 +#include +#include +#include +#include + +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 + +#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 +namespace floormat { using std::getenv; using std::setenv; using std::unsetenv; } +#endif -- cgit v1.2.3