xref: /openbsd-src/regress/lib/libc/vis/vis_test.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: vis_test.c,v 1.4 2015/07/20 01:52:28 millert Exp $	*/
2 
3 /* Public domain. 2005, Otto Moerbeek */
4 
5 #include <limits.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <vis.h>
10 
11 #define NTESTS	8000
12 #define NCH	800
13 
14 char ibuf[NCH];
15 char obuf[NCH * 4];
16 char rbuf[NCH * 4];
17 
18 int flags[] = {
19 	VIS_ALL,
20 	VIS_GLOB,
21 	VIS_TAB,
22 	VIS_NL,
23 	VIS_DQ,
24 	VIS_WHITE,
25 	VIS_SAFE
26 };
27 
28 char *flagname[] = {
29 	"VIS_ALL",
30 	"VIS_GLOB",
31 	"VIS_TAB",
32 	"VIS_NL",
33 	"VIS_DQ",
34 	"VIS_WHITE",
35 	"VIS_SAFE"
36 };
37 
38 int title;
39 
40 void
41 dotitle(int i, int j)
42 {
43 	if (title == 0)
44 		printf("%d %s:", i, flagname[j]);
45 	title = 1;
46 }
47 
48 int
49 main(int argc, char *argv[])
50 {
51 
52 	char inp[UCHAR_MAX + 1];
53 	char out[4 * UCHAR_MAX + 1];
54 	int i, j, fail = 0;
55 	ssize_t owant, o, r;
56 
57 	for (i = 0; i <= UCHAR_MAX; i++) {
58 		inp[i] = i;
59 	}
60 	strvisx(out, inp, UCHAR_MAX + 1, 0);
61 	printf("%s\n", out);
62 
63 	for (i = 0; i < NTESTS; i++) {
64 		arc4random_buf(ibuf, sizeof(ibuf) - 1);
65 		ibuf[sizeof(ibuf) - 1] = '\0';
66 		title = 0;
67 
68 		for (j = 0; j < sizeof(flags)/sizeof(flags[0]); j++) {
69 			owant = sizeof(ibuf);
70 			o = strnvis(obuf, ibuf, owant, flags[j]);
71 			if (o >= owant) {
72 				owant = o + 1;
73 				o = strnvis(obuf, ibuf, owant, flags[j]);
74 				if (o > owant) {
75 					dotitle(i, j);
76 					printf("HUGE overflow\n");
77 				}
78 				if (o < owant - 1) {
79 					dotitle(i, j);
80 					printf("over-estimate of overflow\n");
81 				}
82 			} else if (o > strlen(ibuf) * 4) {
83 				dotitle(i, j);
84 				printf("wants too much %d %d\n", o, strlen(ibuf) * 4);
85 				continue;
86 			}
87 
88 			r = strnunvis(rbuf, obuf, sizeof rbuf);
89 
90 			if (r == -1) {
91 				dotitle(i, j);
92 				printf("cannot decode\n");
93 				printf("%s\n", obuf);
94 				fail = 1;
95 			} else if (r != strlen(ibuf)) {
96 				dotitle(i, j);
97 				printf("rlen %d != inlen %d\n", r, strlen(ibuf));
98 				printf("%s\n", obuf);
99 				printf("%s\n", rbuf);
100 				fail = 1;
101 			} else if (bcmp(ibuf, rbuf, r)) {
102 				dotitle(i, j);
103 				printf("strings are different\n");
104 				printf("%s\n", ibuf);
105 				printf("%s\n", rbuf);
106 				fail = 1;
107 			}
108 		}
109 	}
110 	exit(fail);
111 }
112