1 /* $OpenBSD: vis_test.c,v 1.5 2017/07/27 15:08:37 bluhm 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
dotitle(int i,int j)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
main(int argc,char * argv[])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 %zd %zu\n",
85 o, strlen(ibuf) * 4);
86 continue;
87 }
88
89 r = strnunvis(rbuf, obuf, sizeof rbuf);
90
91 if (r == -1) {
92 dotitle(i, j);
93 printf("cannot decode\n");
94 printf("%s\n", obuf);
95 fail = 1;
96 } else if (r != strlen(ibuf)) {
97 dotitle(i, j);
98 printf("rlen %zd != inlen %zu\n",
99 r, strlen(ibuf));
100 printf("%s\n", obuf);
101 printf("%s\n", rbuf);
102 fail = 1;
103 } else if (bcmp(ibuf, rbuf, r)) {
104 dotitle(i, j);
105 printf("strings are different\n");
106 printf("%s\n", ibuf);
107 printf("%s\n", rbuf);
108 fail = 1;
109 }
110 }
111 }
112 exit(fail);
113 }
114