~nabijaczleweli/voreutils

ref: 72087d46a1d3f95f4e58bc8d4803aa05ab64b9f0 voreutils/cmd/head.cpp -rw-r--r-- 5.2 KiB
72087d46наб OpenBSD port 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
// SPDX-License-Identifier: 0BSD


#include <cstdio>
#include <cstring>
#include <deque>
#include <errno.h>
#include <tuple>
#include <vector>
#include <vore-file>
#include <vore-getopt>
#include <vore-optarg>
#include <vore-print>
#include <vore-size>
#include <vore-stdio>

using namespace std::literals;


#define USAGE(self)                             \
	"usage: %s [-n [-]lines] [-zqv] [file]...\n"  \
	"usage: %s [-c [-]bytes]  [-qv] [file]...\n", \
	    self, self


static constexpr const char * const default_files[] = {"-", nullptr};

enum class unit_t : bool { lines, bytes };


int main(int argc, char * const * argv) {
	std::optional<bool> headers_opt;
	std::uint64_t count = 10;
	char line_sep       = '\n';
	auto unit           = unit_t::lines;
	auto except         = false;
	for(auto [arg, val] : vore::opt::get{argc,
	                                     argv,
	                                     "n:c:zqv"
	                                     "0::1::2::3::4::5::6::7::8::9::",
	                                     {{"lines", required_argument, nullptr, 'n'},
	                                      {"bytes", required_argument, nullptr, 'c'},
	                                      {"zero-terminated", no_argument, nullptr, 'z'},
	                                      {"quiet", no_argument, nullptr, 'q'},
	                                      {"silent", no_argument, nullptr, 'q'},
	                                      {"verbose", no_argument, nullptr, 'v'}}})
		switch(arg) {
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				char argbuf[2];
				if(val)
					--val;
				else {
					argbuf[0] = arg, argbuf[1] = '\0';
					val = argbuf;
				}
				arg = 'n';
				[[fallthrough]];
			case 'n':
			case 'c':
				unit   = arg == 'n' ? unit_t::lines : unit_t::bytes;
				except = val[0] == '-';
				if(auto c = vore::parse_size<std::uint64_t, true>(argv[0], val + except))
					count = *c;
				else
					return 1;
				break;
			case 'z':
				line_sep = '\0';
				break;
			case 'q':
				headers_opt = false;
				break;
			case 'v':
				headers_opt = true;
				break;
			default:
				return std::fprintf(stderr, USAGE(argv[0])), 1;
		}
	auto headers = headers_opt.value_or(*(argv + optind) && *(argv + optind + 1));

	if(unit == unit_t::bytes)
		std::setvbuf(stdout, nullptr, _IONBF, 0);  // Cleanly intersperse fprintf(stdout) with write(1) without explicit fflush()es


	bool err{}, headered{};
	int err_e{};
	char * line{};
	std::size_t linecap{};
	std::deque<std::vector<char>> lines;
	std::vector<char> bytes;
	for(auto file : vore::opt::args{*(argv + optind) ? argv + optind : default_files}) {
		if(headers)
			std::fprintf(stdout, "%s==> %s <==\n", headered ? "\n" : "", file), headered = true;

		switch(unit) {
			case unit_t::lines: {
				vore::file::FILE<true> input{file, "re"};
				if(!input) {
					std::fprintf(stderr, "%s: %s: %s\n", argv[0], file, std::strerror(errno)), err = true;
					continue;
				}

				ssize_t len;
				if(!except)
					for(auto left = count; left && (len = getdelim(&line, &linecap, line_sep, input)) != -1; --left)
						vore::fwrite(line, 1, len, stdout);
				else {
					for(auto && l : lines)
						l.clear();

					while((len = getdelim(&line, &linecap, line_sep, input)) != -1) {
						std::vector<char> l;
						if(lines.size() == count) {
							vore::fwrite(lines.front().data(), 1, lines.front().size(), stdout);
							std::swap(l, lines.front());
							lines.pop_front();
						}
						l.assign(line, line + len);
						lines.emplace_back(std::move(l));
					}
				}
			} break;
			case unit_t::bytes: {
				vore::file::fd<true> fd{file, O_RDONLY | O_CLOEXEC};
				if(fd == -1) {
					std::fprintf(stderr, "%s: %s: %s\n", argv[0], file, std::strerror(errno)), err = true;
					continue;
				}

				auto write_all = [&](const char * begin, const char * end) {
					for(auto cur = begin; cur != end;) {
						auto wr = write(1, cur, end - cur);
						if(wr == -1) {
							if(errno == EINTR)
								continue;
							else {
								err_e = errno;
								return false;
							}
						}
						cur += wr;
					}
					return true;
				};

				auto read_all = [&](int fd, char * buf, std::size_t s) {
					ssize_t rd;
					while((rd = read(fd, buf, s)) == -1 && errno == EINTR)
						;
					if(rd == -1) {
						std::fprintf(stderr, "%s: %s: %s\n", argv[0], file, std::strerror(errno)), err = true;
						rd = 0;
					}
					return rd;
				};

				char buf[64 * 1024];
				if(!except) {
					auto left = count;
					for(ssize_t rd; left && (rd = read_all(fd, buf, std::min(static_cast<std::uint64_t>(sizeof(buf)), left)));) {
						left -= rd;

						if(!write_all(buf, buf + rd))
							break;
					}
				} else {
					bytes.clear();
					bytes.reserve(count + sizeof(buf));
					for(ssize_t rd; (rd = read_all(fd, buf, sizeof(buf)));) {
						bytes.insert(std::end(bytes), buf, buf + rd);

						if(bytes.size() > count) {
							if(!write_all(bytes.data(), bytes.data() + bytes.size() - count))
								break;
							bytes.erase(std::begin(bytes), std::end(bytes) - count);
						}
					}
				}
			} break;
		}
	}

	return vore::flush_stdout(argv[0]) || [&] {
		if(err_e)
			std::fprintf(stderr, "%s: %s\n", argv[0], std::strerror(err_e));
		return err_e;
	}() || err;
}