Debian Codegraph @

src/mpt/environment/environment.hpp

raw
1 /* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */
2
3 #ifndef MPT_ENVIRONMENT_ENVIRONMENT_HPP
4 #define MPT_ENVIRONMENT_ENVIRONMENT_HPP
5
6 #include "mpt/base/detect.hpp"
7 #include "mpt/base/macros.hpp"
8 #include "mpt/base/namespace.hpp"
9 #include "mpt/string/types.hpp"
10 #include "mpt/string_transcode/transcode.hpp"
11 #include "mpt/system_error/system_error.hpp"
12
13 #include <optional>
14 #if MPT_OS_WINDOWS
15 #if defined(UNICODE) && !MPT_OS_WINDOWS_WINRT
16 #include <vector>
17 #endif // !MPT_OS_WINDOWS_WINRT
18 #endif // MPT_OS_WINDOWS
19
20 #include <cstdlib>
21
22 #if MPT_OS_WINDOWS
23 #include <windows.h>
24 #endif // MPT_OS_WINDOWS
25
26
27
28 namespace mpt {
29 inline namespace MPT_INLINE_NS {
30
31
32
33 inline std::optional<mpt::ustring> getenv(const mpt::ustring & env_var) {
34 #if MPT_OS_WINDOWS && MPT_OS_WINDOWS_WINRT
35 MPT_UNUSED(env_var);
36 return std::nullopt;
37 #elif MPT_OS_WINDOWS && defined(UNICODE)
38 std::vector<WCHAR> buf(32767);
39 DWORD size = GetEnvironmentVariable(mpt::transcode<std::wstring>(env_var).c_str(), buf.data(), 32767);
40 if (size == 0) {
41 mpt::windows::ExpectError(ERROR_ENVVAR_NOT_FOUND);
42 return std::nullopt;
43 }
44 return mpt::transcode<mpt::ustring>(buf.data());
45 #else
46 const char * val = std::getenv(mpt::transcode<std::string>(mpt::environment_encoding, env_var).c_str());
47 if (!val) {
48 return std::nullopt;
49 }
50 return mpt::transcode<mpt::ustring>(mpt::environment_encoding, val);
51 #endif
52 }
53
54
55
56 } // namespace MPT_INLINE_NS
57 } // namespace mpt
58
59
60
61 #endif // MPT_ENVIRONMENT_ENVIRONMENT_HPP