~sircmpwn/ctools

ref: f2d583864b4c95633f8897b3e1d44b2fa5352899 ctools/src/fold.c -rw-r--r-- 5.1 KiB View raw
f2d58386 — Gabor Koszegi Implement fold 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

static const unsigned int MODE_BYTES = 1;
static const unsigned int MODE_BLANK = 2;

static const size_t UTF8_MAX_LEN = 6;

static void
usage(void)
{
	fprintf(stderr, "usage: fold [-bs] [-w width] [file...]\n");
}

/*
 *  Ret. val. | Meaning
 * -----------+------------------------------------------------------------
 *     > 0    | valid (actual length)
 *      0     | undecidable (nbytes < encoded length)
 *     < 0    | invalid (-1 * seq. length that is guaranteed to be invalid)
 */
static int
utf8_len(unsigned char *seq, const int nbytes)
{
	/* undecidable */
	if (nbytes < 1) {
		return 0;
	}

	/* ASCII */
	if (seq[0] < 0x80) {
		return 1;
	}

	/* seq begins with continuation byte or
	 * undefined leading byte */
	if (seq[0] < 0xc0 || seq[0] >= 0xfe) {
		return -1;
	}

	/* lower and upper bounds for second byte
	 * which can be modified in special cases */
	unsigned char lb = 0x80;
	unsigned char ub = 0xc0;
	/* length encoded in leading byte */
	int bmax;

	if (seq[0] < 0xe0) {
		bmax = 2;
		/* these can only start overlong sequences */
		if (seq[0] < 0xc2) {
			lb = 0xc0;
		}
	} else if (seq[0] < 0xf0) {
		bmax = 3;
		/* 0xe0 may start overlong sequences */
		if (seq[0] == 0xe0) {
			lb = 0xa0;
		/* 0xed may start UTF-16 surrogate halves */
		} else if (seq[0] == 0xed) {
			ub = 0xa0;
		}
	} else if (seq[0] < 0xf8) {
		bmax = 4;
		/* 0xf0 may start overlong sequences */
		if (seq[0] == 0xf0) {
			lb = 0x90;
		/* 0xf4 may code codepoints over Unicode's limit */
		} else if (seq[0] == 0xf4) {
			ub = 0x90;
		} else if (seq[0] >= 0xf5) {
			lb = 0xc0;
		}
	} else if (seq[0] < 0xfc) {
		bmax = 5;
		lb = 0xc0;
	} else {
		bmax = 6;
		lb = 0xc0;
	}

	/* undecidable */
	if (nbytes < bmax) {
		return 0;
	}

	/* count valid continuation bytes */
	int vbytes = 1;
	for (int i = 1; i < bmax; ++i) {
		if (seq[i] >= 0x80 && seq[i] < 0xc0) {
			++vbytes;
		}
	}

	if (vbytes != bmax || seq[1] < lb || seq[1] >= ub) {
		vbytes *= -1;
	}

	return vbytes;
}

static int
write_segment(const unsigned char * const buf, const ssize_t n)
{
	ssize_t offs = 0;
	while (offs < n) {
		ssize_t o = write(STDOUT_FILENO, buf, n);
		if (o < 0) {
			perror("stdout");
			return 1;
		}
		offs += o;
	}

	return 0;
}

static int
fold(char * const path, const long w, const unsigned int mode)
{
	assert(BUFSIZ > UTF8_MAX_LEN);

	int fd;
	if (path[0] == '-' && path[1] == '\0') {
		fd = STDIN_FILENO;
	} else {
		if ((fd = open(path, O_RDONLY)) < 0) {
			perror(path);
			return 1;
		}
	}

	ssize_t n;
	unsigned char buf[BUFSIZ];
	/* indices (position in buf) and pointers (position in segment)
	 * NOTE: the index (bi) and the pointer (bp) of the last blank char in the
	 *       segment should point to the position after the char in question */
	ssize_t i, ri = 0, wb, we, cp = 0, bi, bp = w;
	ssize_t cstep;
	int l;
	while ((n = read(fd, &buf[ri], sizeof(buf) - ri - 1)) > 0) {
		n += ri;
		ri = 0;
		wb = 0;
		for (i = 0; i < n; i += l) {
			cstep = 0;
			if ((mode & MODE_BYTES) != 0) {
				l = 1;
				if (buf[i] == '\n') {
					cp = 0;
				} else {
					cstep = 1;
				}
			} else if ((l = utf8_len(&buf[i], n - i)) == 1) {
				if (buf[i] == '\b') {
					if (cp > 0) {
						--cp;
					}
				} else if (buf[i] == '\n' || buf[i] == '\r') {
					cp = 0;
				} else if (buf[i] == '\t') {
					cstep = 9 - cp % 8;
				} else {
					cstep = 1;
				}
			} else if (l > 1) {
				cstep = 1;
			} else if (l == 0 && i > n / 2) {
				ri = n - i;
				memcpy(buf, &buf[i], ri);
				break;
			} else {
				fprintf(stderr, "utf-8: invalid byte sequence\n");
				close(fd);
				return 1;
			}

			ssize_t cp_next = cp + cstep;

			if (cp_next > w) {
				if ((mode & MODE_BLANK) != 0 && bp < w
						&& isblank(buf[i]) == 0) {
					we = bi;
					cp = cp_next - bp;
					bp = w;
				} else {
					we = i;
					cp = (mode & MODE_BYTES) == 0 && buf[i] == '\t' ? 9
						: cstep;
				}

				unsigned char swap = buf[we];
				buf[we] = '\n';
				if (write_segment(&buf[wb], we - wb + 1) != 0) {
					close(fd);
					return 1;
				}
				buf[we] = swap;

				wb = we;
			} else {
				if ((mode & MODE_BLANK) != 0 && isblank(buf[i]) != 0) {
					bi = i + l;
					bp = cp_next;
				}
				cp = cp_next;
			}
		}

		if (write_segment(&buf[wb], n - ri - wb) != 0) {
			close(fd);
			return 1;
		}
	}

	close(fd);

	if (n < 0) {
		perror(fd == STDIN_FILENO ? "stdin" : path);
		return 1;
	}

	return 0;
}

int
main(int argc, char *argv[])
{
	long width = 80;
	unsigned int mode = 0;

	char opt;
	while ((opt = getopt(argc, argv, "bsw:")) != -1) {
		switch (opt) {
		case 'b':
			mode |= MODE_BYTES;
			break;
		case 's':
			mode |= MODE_BLANK;
			break;
		case 'w':
			width = strtol(optarg, NULL, 10);
			break;
		default:
			usage();
			return 1;
		}
	}

	if (optind > argc) {
		usage();
		return 1;
	}

	if (width <= 0) {
		fprintf(stderr, "-w: argument is not a positive integer\n");
		return 1;
	}

	char *dash[] = {"-"};
	if (optind == argc) {
		optind = 0;
		argc = 1;
		argv = dash;
	}

	for (int i = optind; i < argc; ++i) {
		if (fold(argv[i], width, mode) != 0) {
			return 1;
		}
	}

	return 0;
}