]> granicus.if.org Git - strace/blob - tests/hexdump_strdup.c
2f200dbd12f02b889689b73816dec521bd87bb40
[strace] / tests / hexdump_strdup.c
1 /*
2  * Make a hexdump copy of C string
3  *
4  * Copyright (c) 2016 Dmitry V. Levin <ldv@altlinux.org>
5  * All rights reserved.
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  */
9
10 #include "tests.h"
11
12 #include <assert.h>
13 #include <stdlib.h>
14 #include <string.h>
15
16 const char *
17 hexdump_memdup(const char *src, size_t len)
18 {
19         size_t dst_size = 3 * len + 2;
20         assert(dst_size > len);
21
22         char *dst = malloc(dst_size);
23         if (!dst)
24                 perror_msg_and_fail("malloc(%zu)", dst_size);
25
26         char *p = dst;
27         const unsigned char *usrc = (const unsigned char *) src;
28         size_t i;
29         for (i = 0; i < len; ++i) {
30                 unsigned int c = usrc[i];
31                 *(p++) = ' ';
32                 if (i == 8)
33                         *(p++) = ' ';
34                 *(p++) = "0123456789abcdef"[c >> 4];
35                 *(p++) = "0123456789abcdef"[c & 0xf];
36         }
37         *p = '\0';
38
39         return dst;
40 }
41
42 const char *
43 hexdump_strdup(const char *src)
44 {
45         return hexdump_memdup(src, strlen(src));
46 }