• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "tests.h"
2 
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 
7 /*
8  * Based on string_quote() from util.c.
9  * Assumes instr is NUL-terminated.
10  */
11 
12 void
print_quoted_string(const char * instr)13 print_quoted_string(const char *instr)
14 {
15 	print_quoted_memory(instr, strlen(instr));
16 }
17 
18 void
print_quoted_cstring(const char * instr,const size_t size)19 print_quoted_cstring(const char *instr, const size_t size)
20 {
21 	const size_t len = strnlen(instr, size);
22 	if (len < size) {
23 		print_quoted_memory(instr, len);
24 	} else {
25 		print_quoted_memory(instr, size - 1);
26 		printf("...");
27 	}
28 }
29 
30 void
print_quoted_memory(const void * const instr,const size_t len)31 print_quoted_memory(const void *const instr, const size_t len)
32 {
33 	const unsigned char *str = (const unsigned char *) instr;
34 	size_t i;
35 
36 	putchar('"');
37 	for (i = 0; i < len; ++i) {
38 		const int c = str[i];
39 		switch (c) {
40 			case '\"':
41 				printf("\\\"");
42 				break;
43 			case '\\':
44 				printf("\\\\");
45 				break;
46 			case '\f':
47 				printf("\\f");
48 				break;
49 			case '\n':
50 				printf("\\n");
51 				break;
52 			case '\r':
53 				printf("\\r");
54 				break;
55 			case '\t':
56 				printf("\\t");
57 				break;
58 			case '\v':
59 				printf("\\v");
60 				break;
61 			default:
62 				if (c >= ' ' && c <= 0x7e)
63 					putchar(c);
64 				else {
65 					putchar('\\');
66 
67 					char c1 = '0' + (c & 0x7);
68 					char c2 = '0' + ((c >> 3) & 0x7);
69 					char c3 = '0' + (c >> 6);
70 
71 					if (*str >= '0' && *str <= '9') {
72 						/* Print \octal */
73 						putchar(c3);
74 						putchar(c2);
75 					} else {
76 						/* Print \[[o]o]o */
77 						if (c3 != '0')
78 							putchar(c3);
79 						if (c3 != '0' || c2 != '0')
80 							putchar(c2);
81 					}
82 					putchar(c1);
83 				}
84 				break;
85 		}
86 	}
87 
88 	putchar('"');
89 }
90 
91 void
print_quoted_hex(const void * const instr,const size_t len)92 print_quoted_hex(const void *const instr, const size_t len)
93 {
94 	const unsigned char *str = instr;
95 	size_t i;
96 
97 	printf("\"");
98 	for (i = 0; i < len; i++)
99 		printf("\\x%02x", str[i]);
100 	printf("\"");
101 }
102