-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.cpp
More file actions
155 lines (135 loc) · 4.63 KB
/
sort.cpp
File metadata and controls
155 lines (135 loc) · 4.63 KB
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
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <string_view>
#include <vector>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/io.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "sort",
.version = CFBOX_VERSION_STRING,
.one_line = "sort lines of text",
.usage = "sort [OPTIONS] [FILE]...",
.options = " -r reverse the result of comparisons\n"
" -n compare according to string numerical value\n"
" -u output only the first of an equal run",
.extra = "",
};
struct SortOptions {
bool reverse = false;
bool numeric = false;
bool unique = false;
int key_field = 0; // 0 = whole line, N = field N (1-based)
};
auto extract_field(const std::string& line, int field) -> std::string {
if (field <= 0) return line;
int current = 1;
std::size_t start = 0;
for (std::size_t i = 0; i <= line.size(); ++i) {
if (i == line.size() || line[i] == ' ' || line[i] == '\t') {
if (start < i) {
if (current == field) {
return line.substr(start, i - start);
}
++current;
}
start = i + 1;
}
}
return "";
}
auto sort_lines(std::vector<std::string>& lines, const SortOptions& opts) -> void {
// Precompute sort keys to avoid repeated string allocation in comparator
struct Entry {
std::string key;
std::size_t index;
double num_val;
};
std::vector<Entry> entries;
entries.reserve(lines.size());
for (std::size_t i = 0; i < lines.size(); ++i) {
Entry e;
e.key = opts.key_field > 0 ? extract_field(lines[i], opts.key_field) : lines[i];
e.index = i;
e.num_val = opts.numeric ? std::strtod(e.key.c_str(), nullptr) : 0.0;
entries.push_back(std::move(e));
}
std::stable_sort(entries.begin(), entries.end(), [&](const Entry& a, const Entry& b) {
bool less;
if (opts.numeric) {
less = a.num_val < b.num_val;
} else {
less = a.key < b.key;
}
return opts.reverse ? !less && a.key != b.key : less;
});
std::vector<std::string> sorted;
sorted.reserve(lines.size());
for (const auto& e : entries) {
if (opts.unique && !sorted.empty() && sorted.back() == lines[e.index]) {
continue;
}
sorted.push_back(std::move(lines[e.index]));
}
lines = std::move(sorted);
}
} // namespace
auto sort_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'r', false, "reverse"},
cfbox::args::OptSpec{'n', false, "numeric-sort"},
cfbox::args::OptSpec{'u', false, "unique"},
cfbox::args::OptSpec{'k', true, "key"},
});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
SortOptions opts;
opts.reverse = parsed.has('r');
opts.numeric = parsed.has('n');
opts.unique = parsed.has('u');
if (parsed.has('k')) {
opts.key_field = static_cast<int>(
std::strtol(std::string{parsed.get('k').value_or("1")}.c_str(), nullptr, 10));
}
const auto& pos = parsed.positional();
std::vector<std::string> all_lines;
if (pos.empty()) {
auto result = cfbox::io::read_all_stdin();
if (!result) {
CFBOX_ERR("sort", "%s", result.error().msg.c_str());
return 1;
}
all_lines = cfbox::io::split_lines(result.value());
} else if (pos.size() == 1) {
auto result = (pos[0] == "-") ? cfbox::io::read_all_stdin() : cfbox::io::read_all(pos[0]);
if (!result) {
CFBOX_ERR("sort", "%s", result.error().msg.c_str());
return 1;
}
all_lines = cfbox::io::split_lines(result.value());
} else {
int rc = 0;
for (const auto& p : pos) {
auto result = (p == "-") ? cfbox::io::read_all_stdin() : cfbox::io::read_all(p);
if (!result) {
CFBOX_ERR("sort", "%s", result.error().msg.c_str());
rc = 1;
} else {
auto file_lines = cfbox::io::split_lines(result.value());
for (auto& l : file_lines) {
all_lines.push_back(std::move(l));
}
}
}
if (rc != 0) return rc;
}
sort_lines(all_lines, opts);
for (const auto& line : all_lines) {
std::printf("%s\n", line.c_str());
}
return 0;
}