xref: /openbsd-src/regress/lib/libedit/read/test_read_char.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*
2  * Copyright (c) 2016 Ingo Schwarze <schwarze@openbsd.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #include <err.h>
18 #include <locale.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 
22 #include "read.c"
23 #include "glue.c"
24 
25 /*
26  * Unit test steering program for editline/read.c, read_char().
27  * Reads from standard input until read_char() returns 0.
28  * Writes the code points read to standard output in %x format.
29  * If EILSEQ is set after read_char(), indicating that there were some
30  * garbage bytes before the character, the code point gets * prefixed.
31  * The return value is indicated by appending to the code point:
32  * a comma for 1, a full stop for 0, [%d] otherwise.
33  * Errors out on unexpected failure (setlocale failure, malloc
34  * failure, or unexpected errno).
35  * Since ENOMSG is very unlikely to occur, it is used to make
36  * sure that read_char() doesn't clobber errno.
37  */
38 
39 int
40 main(void)
41 {
42 	EditLine el;
43 	int irc;
44 	wchar_t cp;
45 
46 	if (setlocale(LC_CTYPE, "") == NULL)
47 		err(1, "setlocale");
48 	el.el_flags = CHARSET_IS_UTF8;
49 	el.el_infd = STDIN_FILENO;
50 	if ((el.el_signal = calloc(1, sizeof(*el.el_signal))) == NULL)
51 		err(1, NULL);
52 	do {
53 		errno = ENOMSG;
54 		irc = read_char(&el, &cp);
55 		switch (errno) {
56 		case ENOMSG:
57 			break;
58 		case EILSEQ:
59 			putchar('*');
60 			break;
61 		default:
62 			err(1, NULL);
63 		}
64 		printf("%x", cp);
65 		switch (irc) {
66 		case 1:
67 			putchar(',');
68 			break;
69 		case 0:
70 			putchar('.');
71 			break;
72 		default:
73 			printf("[%d]", irc);
74 			break;
75 		}
76 	} while (irc != 0);
77 	return 0;
78 }
79