libostd/ostd/environ.hh

98 lines
2.3 KiB
C++
Raw Normal View History

/* Environment handling.
*
* This file is part of OctaSTD. See COPYING.md for futher information.
*/
#ifndef OSTD_ENVIRON_HH
#define OSTD_ENVIRON_HH
#include "ostd/platform.hh"
#include "ostd/internal/win32.hh"
#include <stdlib.h>
#include <string.h>
2017-01-30 00:54:06 +01:00
#include <vector>
#include "ostd/maybe.hh"
#include "ostd/string.hh"
/* TODO: make POSIX version thread safe, the Windows version is... */
namespace ostd {
2017-01-30 00:54:06 +01:00
inline Maybe<std::string> env_get(ConstCharRange name) {
char buf[256];
auto tbuf = to_temp_cstr(name, buf, sizeof(buf));
#ifndef OSTD_PLATFORM_WIN32
char const *ret = getenv(tbuf.get());
if (!ret) {
return ostd::nothing;
}
2017-01-30 00:54:06 +01:00
return std::string{ret};
#else
2017-01-30 00:54:06 +01:00
std::vector<char> rbuf;
DWORD sz;
for (;;) {
2017-01-30 00:54:06 +01:00
sz = GetEnvironmentVariable(tbuf.get(), rbuf.data(), rbuf.capacity());
if (!sz) {
return ostd::nothing;
}
2017-01-30 00:54:06 +01:00
if (sz < rbuf.capacity()) {
break;
}
2017-01-30 00:54:06 +01:00
rbuf.reserve(sz);
}
2017-01-30 00:54:06 +01:00
return std::string{rbuf.data(), sz};
#endif
}
inline bool env_set(
ConstCharRange name, ConstCharRange value, bool update = true
) {
char sbuf[2048];
char *buf = sbuf;
bool alloc = (name.size() + value.size() + 2) > sizeof(sbuf);
if (alloc) {
buf = new char[name.size() + value.size() + 2];
}
memcpy(buf, name.data(), name.size());
buf[name.size()] = '\0';
memcpy(&buf[name.size() + 1], value.data(), value.size());
buf[name.size() + value.size() + 1] = '\0';
#ifndef OSTD_PLATFORM_WIN32
bool ret = !setenv(buf, &buf[name.size() + 1], update);
#else
if (!update && GetEnvironmentVariable(buf, nullptr, 0)) {
return true;
}
bool ret = !!SetEnvironmentVariable(buf, &buf[name.size() + 1]);
#endif
if (alloc) {
delete[] buf;
}
return ret;
}
2016-07-08 20:48:11 +02:00
inline bool env_unset(ConstCharRange name) {
char buf[256];
if (name.size() < sizeof(buf)) {
memcpy(buf, name.data(), name.size());
buf[name.size()] = '\0';
#ifndef OSTD_PLATFORM_WIN32
return !unsetenv(buf);
#else
return !!SetEnvironmentVariable(buf, nullptr);
#endif
}
#ifndef OSTD_PLATFORM_WIN32
2017-01-30 00:54:06 +01:00
return !unsetenv(std::string{name}.data());
#else
2017-01-30 00:54:06 +01:00
return !!SetEnvironmentVariable(std::string{name}.data(), nullptr);
#endif
}
} /* namespace ostd */
#endif