/* SPDX-License-Identifier: LGPL-2.1-or-later */
+#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
#include "errno-list.h"
# include "errno-to-name.inc"
const char* errno_to_name(int id) {
-
if (id < 0)
id = -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;
+}
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]){})
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);