xref: /openbsd/regress/lib/libc/vis/vis_test.c (revision 8932bfb7)
1 /*	$OpenBSD: vis_test.c,v 1.3 2011/03/13 22:12:37 deraadt 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_WHITE,
24 	VIS_SAFE
25 };
26 
27 char *flagname[] = {
28 	"VIS_ALL",
29 	"VIS_GLOB",
30 	"VIS_TAB",
31 	"VIS_NL",
32 	"VIS_WHITE",
33 	"VIS_SAFE"
34 };
35 
36 int title;
37 
38 void
39 dotitle(int i, int j)
40 {
41 	if (title == 0)
42 		printf("%d %s:", i, flagname[j]);
43 	title = 1;
44 }
45 
46 int
47 main(int argc, char *argv[])
48 {
49 
50 	char inp[UCHAR_MAX + 1];
51 	char out[4 * UCHAR_MAX + 1];
52 	int i, j, fail = 0;
53 	ssize_t owant, o, r;
54 
55 	for (i = 0; i <= UCHAR_MAX; i++) {
56 		inp[i] = i;
57 	}
58 	strvisx(out, inp, UCHAR_MAX + 1, 0);
59 	printf("%s\n", out);
60 
61 	for (i = 0; i < NTESTS; i++) {
62 		arc4random_buf(ibuf, sizeof(ibuf) - 1);
63 		ibuf[sizeof(ibuf) - 1] = '\0';
64 		title = 0;
65 
66 		for (j = 0; j < sizeof(flags)/sizeof(flags[0]); j++) {
67 			owant = sizeof(ibuf);
68 			o = strnvis(obuf, ibuf, owant, flags[j]);
69 			if (o >= owant) {
70 				owant = o + 1;
71 				o = strnvis(obuf, ibuf, owant, flags[j]);
72 				if (o > owant) {
73 					dotitle(i, j);
74 					printf("HUGE overflow\n");
75 				}
76 				if (o < owant - 1) {
77 					dotitle(i, j);
78 					printf("over-estimate of overflow\n");
79 				}
80 			} else if (o > strlen(ibuf) * 4) {
81 				dotitle(i, j);
82 				printf("wants too much %d %d\n", o, strlen(ibuf) * 4);
83 				continue;
84 			}
85 
86 			r = strnunvis(rbuf, obuf, sizeof rbuf);
87 
88 			if (r == -1) {
89 				dotitle(i, j);
90 				printf("cannot decode\n");
91 				printf("%s\n", obuf);
92 				fail = 1;
93 			} else if (r != strlen(ibuf)) {
94 				dotitle(i, j);
95 				printf("rlen %d != inlen %d\n", r, strlen(ibuf));
96 				printf("%s\n", obuf);
97 				printf("%s\n", rbuf);
98 				fail = 1;
99 			} else if (bcmp(ibuf, rbuf, r)) {
100 				dotitle(i, j);
101 				printf("strings are different\n");
102 				printf("%s\n", ibuf);
103 				printf("%s\n", rbuf);
104 				fail = 1;
105 			}
106 		}
107 	}
108 	exit(fail);
109 }
110