]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
basic/errno-list: add helper to print errno names
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Sat, 28 Jun 2025 19:34:10 +0000 (21:34 +0200)
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Tue, 1 Jul 2025 15:51:49 +0000 (17:51 +0200)
src/basic/errno-list.c
src/basic/errno-list.h
src/test/test-errno-list.c

index 5bfd8aa076a7030e8cb1706c1d2590d92ac0f742..8de9888083980ea04ab952a20da0135d3da1d760 100644 (file)
@@ -1,5 +1,7 @@
 /* SPDX-License-Identifier: LGPL-2.1-or-later */
 
+#include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
 
 #include "errno-list.h"
@@ -33,7 +35,6 @@ const char* errno_to_name(int id) {
 #  include "errno-to-name.inc"
 
 const char* errno_to_name(int id) {
-
         if (id < 0)
                 id = -id;
 
@@ -43,3 +44,11 @@ const char* errno_to_name(int id) {
         return errno_names[id];
 }
 #endif
+
+const char* errno_name_full(int id, char buf[static ERRNO_NAME_BUF_LEN]) {
+        const char *a = errno_to_name(id);
+        if (a)
+                return a;
+        snprintf(buf, ERRNO_NAME_BUF_LEN, "%d", abs(id));
+        return buf;
+}
index 5b29642ce492d7a8c5abb66451f595018320cf53..6ce2d75c09a8cec49cfb1a6a01925e201661cce2 100644 (file)
@@ -9,3 +9,10 @@ int errno_from_name(const char *name) _pure_;
 static inline bool errno_is_valid(int n) {
         return n > 0 && n <= ERRNO_MAX;
 }
+
+#define ERRNO_NAME_BUF_LEN DECIMAL_STR_MAX(int)
+/* Like errno_name, but always returns a string. */
+const char* errno_name_full(int id, char buf[static ERRNO_NAME_BUF_LEN]);
+
+/* A helper to print the errno "name" or number if name is not defined. */
+#define ERRNO_NAME_FULL(errnum) errno_name_full(errnum, (char[ERRNO_NAME_BUF_LEN]){})
index 3bd9ee232ca83d746b95196ab3b2fec9b89f699b..c72f657123f093bd64c165c35a6e9d7ffc9e41d5 100644 (file)
@@ -29,4 +29,26 @@ TEST(errno_list) {
         ASSERT_STREQ(errno_to_name(ECONNREFUSED), "ECONNREFUSED");
 }
 
+TEST(errno_name_full) {
+        char buf[ERRNO_NAME_BUF_LEN];
+
+        ASSERT_STREQ(errno_name_full(0, buf), "0");
+        ASSERT_STREQ(errno_name_full(EPERM, buf), "EPERM");
+        ASSERT_STREQ(errno_name_full(ENOENT, buf), "ENOENT");
+        ASSERT_STREQ(errno_name_full(200, buf), "200");
+        ASSERT_STREQ(errno_name_full(-200, buf), "200");
+}
+
+TEST(ERRNO_NAME_FULL) {
+        ASSERT_STREQ(ERRNO_NAME_FULL(0), "0");
+        ASSERT_STREQ(ERRNO_NAME_FULL(EPERM), "EPERM");
+        ASSERT_STREQ(ERRNO_NAME_FULL(ENOENT), "ENOENT");
+        ASSERT_STREQ(ERRNO_NAME_FULL(200), "200");
+        ASSERT_STREQ(ERRNO_NAME_FULL(-200), "200");
+
+        int x = 0;
+        ASSERT_STREQ(ERRNO_NAME_FULL(++x), "EPERM");  /* Confirm that eval happens just once. */
+        ASSERT_EQ(x, 1);
+}
+
 DEFINE_TEST_MAIN(LOG_INFO);