Skip to content

Commit 7c72df5

Browse files
colonashemminger
authored andcommitted
utils: add print_escape_buf to format and print arbitrary bytes
Keep it as simple as possible for now: just escape anything that is not isprint-able, is among the "escape" parameter or '\' as an octal escape sequence. This should be pretty easy to extend if any other user needs something more complex in the future. Signed-off-by: Ivan Delalande <colona@arista.com>
1 parent 4f6b733 commit 7c72df5

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

include/utils.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,8 @@ static inline void __jiffies_to_tv(struct timeval *tv, unsigned long jiffies)
195195
tv->tv_usec = tvusec - 1000000 * tv->tv_sec;
196196
}
197197

198+
void print_escape_buf(const __u8 *buf, size_t len, const char *escape);
199+
198200
int print_timestamp(FILE *fp);
199201
void print_nlmsg_timestamp(FILE *fp, const struct nlmsghdr *n);
200202

lib/utils.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include <time.h>
3232
#include <sys/time.h>
3333
#include <errno.h>
34+
#include <ctype.h>
3435

3536
#include "rt_names.h"
3637
#include "utils.h"
@@ -1047,6 +1048,20 @@ int addr64_n2a(__u64 addr, char *buff, size_t len)
10471048
return written;
10481049
}
10491050

1051+
/* Print buffer and escape bytes that are !isprint or among 'escape' */
1052+
void print_escape_buf(const __u8 *buf, size_t len, const char *escape)
1053+
{
1054+
size_t i;
1055+
1056+
for (i = 0; i < len; ++i) {
1057+
if (isprint(buf[i]) && buf[i] != '\\' &&
1058+
!strchr(escape, buf[i]))
1059+
printf("%c", buf[i]);
1060+
else
1061+
printf("\\%03o", buf[i]);
1062+
}
1063+
}
1064+
10501065
int print_timestamp(FILE *fp)
10511066
{
10521067
struct timeval tv;

0 commit comments

Comments
 (0)