diff options
| author | Lexi Winter <lexi@le-fay.org> | 2025-06-28 19:25:55 +0100 |
|---|---|---|
| committer | Lexi Winter <lexi@le-fay.org> | 2025-06-28 19:25:55 +0100 |
| commit | a2d7181700ac64b8e7a4472ec26dfa253b38f188 (patch) | |
| tree | 23c5a9c8ec4089ac346e2e0f9391909c3089b66b /nihil.posix/getenv.cc | |
| parent | f226d46ee02b57dd76a4793593aa8d66e1c58353 (diff) | |
| download | nihil-a2d7181700ac64b8e7a4472ec26dfa253b38f188.tar.gz nihil-a2d7181700ac64b8e7a4472ec26dfa253b38f188.tar.bz2 | |
split nihil into separate modules
Diffstat (limited to 'nihil.posix/getenv.cc')
| -rw-r--r-- | nihil.posix/getenv.cc | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/nihil.posix/getenv.cc b/nihil.posix/getenv.cc new file mode 100644 index 0000000..36df950 --- /dev/null +++ b/nihil.posix/getenv.cc @@ -0,0 +1,45 @@ + +/* + * This source code is released into the public domain. + */ + +module; + +#include <cstdint> +#include <expected> +#include <string> +#include <system_error> +#include <vector> + +#include <unistd.h> + +module nihil.posix; + +import nihil.error; + +namespace nihil { + +auto getenv(std::string_view varname) -> std::expected<std::string, error> +{ + // Start with a buffer of this size, and double it every iteration. + constexpr auto bufinc = std::size_t{1024}; + + auto cvarname = std::string(varname); + auto buf = std::vector<char>(bufinc); + for (;;) { + auto const ret = ::getenv_r(cvarname.c_str(), + buf.data(), buf.size()); + + if (ret == 0) + return {std::string(buf.data())}; + + if (ret == -1 && errno == ERANGE) { + buf.resize(buf.size() * 2); + continue; + } + + return std::unexpected(error(std::errc(errno))); + } +} + +} // namespace nihil |
