From: Zbigniew Jędrzejewski-Szmek Date: Sat, 28 Jun 2025 19:34:10 +0000 (+0200) Subject: basic/errno-list: add helper to print errno names X-Git-Tag: v258-rc1~206^2~1 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=6020ca2c23b8ab8fd7a8101bad4859c7ace19768;p=thirdparty%2Fsystemd.git basic/errno-list: add helper to print errno names --- diff --git a/src/basic/errno-list.c b/src/basic/errno-list.c index 5bfd8aa076a..8de98880839 100644 --- a/src/basic/errno-list.c +++ b/src/basic/errno-list.c @@ -1,5 +1,7 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ +#include +#include #include #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; +} diff --git a/src/basic/errno-list.h b/src/basic/errno-list.h index 5b29642ce49..6ce2d75c09a 100644 --- a/src/basic/errno-list.h +++ b/src/basic/errno-list.h @@ -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]){}) diff --git a/src/test/test-errno-list.c b/src/test/test-errno-list.c index 3bd9ee232ca..c72f657123f 100644 --- a/src/test/test-errno-list.c +++ b/src/test/test-errno-list.c @@ -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);