aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.posix/getenv.ccm
diff options
context:
space:
mode:
Diffstat (limited to 'nihil.posix/getenv.ccm')
-rw-r--r--nihil.posix/getenv.ccm22
1 files changed, 9 insertions, 13 deletions
diff --git a/nihil.posix/getenv.ccm b/nihil.posix/getenv.ccm
index 5967bf7..ddffeb3 100644
--- a/nihil.posix/getenv.ccm
+++ b/nihil.posix/getenv.ccm
@@ -2,18 +2,15 @@
module;
#include <cerrno>
-#include <expected>
-#include <string>
-#include <system_error>
-#include <vector>
-
-#include <unistd.h>
+#include <stdlib.h> // NOLINT: getenv_r
#include "nihil.hh"
export module nihil.posix:getenv;
+import nihil.std;
import nihil.error;
+import nihil.util;
namespace nihil {
@@ -23,9 +20,10 @@ namespace nihil {
// future calls to setenv().
export [[nodiscard]] auto getenv(std::string_view varname) -> std::expected<std::string, error>
{
+ auto errno_guard = save_errno();
auto cvarname = std::string(varname);
-#ifdef NIHIL_HAVE_GETENV_R
+#if NIHIL_HAVE_GETENV_R == 1
// Start with a buffer of this size, and double it every iteration.
constexpr auto bufinc = std::size_t{1024};
@@ -44,16 +42,14 @@ export [[nodiscard]] auto getenv(std::string_view varname) -> std::expected<std:
return std::unexpected(error(std::errc(errno)));
}
#else // NIHIL_HAVE_GETENV_R
- errno = 0;
- auto *v = ::getenv(cvarname.c_str()); // NOLINT
+ // getenv() may not set errno on failure, so initialise it to a reasonable value.
+ errno = ENOENT;
+ auto const *v = ::getenv(cvarname.c_str()); // NOLINT
if (v != nullptr)
return {std::string(v)};
- if (errno != 0)
- return std::unexpected(error(std::errc(errno)));
-
- return std::unexpected(error(std::errc::no_such_file_or_directory));
+ return error(sys_error());
#endif // NIHIL_HAVE_GETENV_R
}