system_ram.cpp raw
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-present The Limenka developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include <common/system_ram.h>
7
8 #ifdef WIN32
9 #include <windows.h>
10 #else
11 #include <unistd.h>
12 #endif
13
14 #include <algorithm>
15 #include <cstdint>
16 #include <limits>
17
18 std::optional<size_t> TryGetTotalRam()
19 {
20 static const auto total_ram{[]() -> std::optional<size_t> {
21 [[maybe_unused]] auto clamp{[](uint64_t v) { return size_t(std::min(v, uint64_t{std::numeric_limits<size_t>::max()})); }};
22 #ifdef WIN32
23 if (MEMORYSTATUSEX m{}; (m.dwLength = sizeof(m), GlobalMemoryStatusEx(&m))) return clamp(m.ullTotalPhys);
24 #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__illumos__) || defined(__linux__)
25 if (long p{sysconf(_SC_PHYS_PAGES)}, s{sysconf(_SC_PAGESIZE)}; p > 0 && s > 0) return clamp(1ULL * p * s);
26 #endif
27 return std::nullopt;
28 }()};
29 return total_ram;
30 }
31