commit: b4eec8162b2d775cbc31c740991db2663fc49c32
Author: Michał Górny <mgorny <AT> gentoo <DOT> org>
AuthorDate: Thu Dec 25 17:03:46 2025 +0000
Commit: Michał Górny <mgorny <AT> gentoo <DOT> org>
CommitDate: Thu Dec 25 17:03:46 2025 +0000
URL: https://gitweb.gentoo.org/proj/steve.git/commit/?id=b4eec816
Move /proc/meminfo search into a separate function
Signed-off-by: Michał Górny <mgorny <AT> gentoo.org>
src/steve.cxx | 66 +++++++++++++++++++++++++++++++++++++----------------------
1 file changed, 41 insertions(+), 25 deletions(-)
diff --git a/src/steve.cxx b/src/steve.cxx
index 952f72e..25a6b50 100644
--- a/src/steve.cxx
+++ b/src/steve.cxx
@@ -27,6 +27,7 @@
#include <optional>
#include <print>
#include <string>
+#include <string_view>
#include <unordered_map>
#include <variant>
@@ -185,6 +186,41 @@ static void steve_get_load(steve_state *state)
}
}
+static std::optional<long> steve_get_meminfo(int fd, std::string_view label)
+{
+ char buf[4096] = {"\n"};
+ ssize_t rd = pread(fd, &buf[1], sizeof(buf) - 2, 0);
+
+ if (rd < 0) {
+ perror("Reading /proc/meminfo failed, memory use will not be
available");
+ return {};
+ }
+
+ buf[rd + 1] = 0;
+ char *match = strstr(buf, label.data());
+ if (!match) {
+ std::print(stderr, "Parsing /proc/meminfo failed: no {}\n",
label);
+ return {};
+ }
+ match += label.size();
+ match += strspn(match, " ");
+
+ char *end = match + strspn(match, "0123456789");
+ if (strncmp(end, " kB\n", 4)) {
+ std::print(stderr, "Parsing /proc/meminfo failed: {} not
suffixed by ' kB'\n", label);
+ return {};
+ }
+ *end = 0;
+
+ long val;
+ if (!arg_to_long(match, &val)) {
+ std::print(stderr, "Parsing /proc/meminfo failed: {} is not a
valid positive long\n", match);
+ return {};
+ }
+
+ return val;
+}
+
static void steve_get_memory_use(steve_state *state)
{
if (state->meminfo_fd == -2) {
@@ -194,31 +230,11 @@ static void steve_get_memory_use(steve_state *state)
}
if (state->meminfo_fd != -1) {
- char buf[4096] = {"\n"};
- ssize_t rd = pread(state->meminfo_fd, &buf[1], sizeof(buf) - 2,
0);
-
- if (rd >= 0) {
- buf[rd + 1] = 0;
-
- constexpr char mem_avail_label[] = "\nMemAvailable:";
- char *mem_avail = strstr(buf, mem_avail_label);
- if (mem_avail) {
- mem_avail += sizeof(mem_avail_label) - 1;
- mem_avail += strspn(mem_avail, " ");
- char *end = mem_avail + strspn(mem_avail,
"0123456789");
- if (!strncmp(end, " kB\n", 4)) {
- *end = 0;
- long val;
- if (arg_to_long(mem_avail, &val)) {
- state->memory_avail = val /
1024;
- return;
- }
- }
- }
-
- std::print(stderr, "Parsing /proc/meminfo failed\n");
- } else
- perror("Reading /proc/meminfo failed, memory use will
not be available");
+ auto maybe_val = steve_get_meminfo(state->meminfo_fd,
"\nMemAvailable:");
+ if (maybe_val.has_value()) {
+ state->memory_avail = maybe_val.value() / 1024;
+ return;
+ }
close(state->meminfo_fd);
state->meminfo_fd = -1;