• 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_memory(const char * instr,const size_t len)19 print_quoted_memory(const char *instr, const size_t len)
20 {
21 	const unsigned char *str = (const unsigned char*) instr;
22 	size_t i;
23 
24 	for (i = 0; i < len; ++i) {
25 		const int c = str[i];
26 		switch (c) {
27 			case '\"':
28 				printf("\\\"");
29 				break;
30 			case '\\':
31 				printf("\\\\");
32 				break;
33 			case '\f':
34 				printf("\\f");
35 				break;
36 			case '\n':
37 				printf("\\n");
38 				break;
39 			case '\r':
40 				printf("\\r");
41 				break;
42 			case '\t':
43 				printf("\\t");
44 				break;
45 			case '\v':
46 				printf("\\v");
47 				break;
48 			default:
49 				if (c >= ' ' && c <= 0x7e)
50 					putchar(c);
51 				else {
52 					putchar('\\');
53 
54 					char c1 = '0' + (c & 0x7);
55 					char c2 = '0' + ((c >> 3) & 0x7);
56 					char c3 = '0' + (c >> 6);
57 
58 					if (*str >= '0' && *str <= '9') {
59 						/* Print \octal */
60 						putchar(c3);
61 						putchar(c2);
62 					} else {
63 						/* Print \[[o]o]o */
64 						if (c3 != '0')
65 							putchar(c3);
66 						if (c3 != '0' || c2 != '0')
67 							putchar(c2);
68 					}
69 					putchar(c1);
70 				}
71 				break;
72 		}
73 	}
74 
75 }
76