1 /**
2  * this is a small sample script to use libmbfl.
3  * Rui Hirokawa <hirokawa@php.net>
4  *
5  * this file is encoded in EUC-JP.
6  */
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include "mbfl/mbfilter.h"
12 
hexdump(const mbfl_string * ptr)13 static void hexdump(const mbfl_string *ptr)
14 {
15 	unsigned int i;
16 
17 	for (i = 0; i < ptr->len; i++) {
18 		printf("%%%02x", ptr->val[i]);
19 	}
20 
21 	printf(" (%u)\n", ptr->len);
22 }
23 
main(int argc,char ** argv)24 int main(int argc, char **argv)
25 {
26 	enum mbfl_no_encoding from_encoding, to_encoding;
27 	enum mbfl_no_language no_language;
28 	mbfl_buffer_converter *convd = NULL;
29 	mbfl_memory_device dev;
30 	mbfl_string string, result, *ret;
31 	int final = 0;
32 	int state = 0;
33 
34 	if (argc < 4) {
35 		fprintf(stderr, "Usage: %s lang to_encoding from_encoding\n", argv[0]);
36 		return EXIT_FAILURE;
37 	}
38 
39 	if ((no_language = mbfl_name2no_language(argv[1])) ==
40 			mbfl_no_language_invalid) {
41 		printf("Unsupported NLS: %s\n", argv[1]);
42 		return EXIT_FAILURE;
43 	}
44 
45 	if ((to_encoding = mbfl_name2no_encoding(argv[2])) ==
46 			mbfl_no_encoding_invalid) {
47 		printf("Unsupported encoding: %s\n", argv[2]);
48 		return EXIT_FAILURE;
49 	}
50 
51 	if ((from_encoding = mbfl_name2no_encoding(argv[3])) ==
52 			mbfl_no_encoding_invalid) {
53 		printf("Unsupported encoding: %s\n", argv[3]);
54 		return EXIT_FAILURE;
55 	}
56 
57 	convd = mbfl_buffer_converter_new(from_encoding, to_encoding, 0);
58 
59 	do {
60 		mbfl_memory_device_init(&dev, 0, 4096);
61 		mbfl_string_init_set(&string, no_language, from_encoding);
62 
63 		for (;;) {
64 			const int c = fgetc(stdin);
65 
66 			if (c == EOF) {
67 				final = 1;
68 				break;
69 			} else if (c == 10) {
70 				if (state == 1) {
71 					state = 0;
72 					continue;
73 				}
74 				break;
75 			} else if (c == 13) {
76 				state = 1;
77 				break;
78 			}
79 
80 			if (dev.pos >= dev.length) {
81 				if (dev.length + dev.allocsz < dev.length) {
82 					printf("Unable to allocate memory\n");
83 					return EXIT_FAILURE;
84 				}
85 
86 				mbfl_memory_device_realloc(&dev, dev.length + dev.allocsz,
87 						dev.allocsz);
88 			}
89 
90 			dev.buffer[dev.pos++] = (unsigned char)c;
91 		}
92 
93 		mbfl_memory_device_result(&dev, &string);
94 		mbfl_string_init_set(&result, no_language, to_encoding);
95 		ret = mbfl_buffer_converter_feed_result(convd, &string, &result);
96 		hexdump(&result);
97 		mbfl_string_clear(&result);
98 		mbfl_string_clear(&string);
99 	} while (!final);
100 
101 	mbfl_buffer_converter_delete(convd);
102 
103 	return EXIT_SUCCESS;
104 }
105