blob: 5f75734a0f2ba706d75ab8bf4d24e5c84724a179 (
plain)
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
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const types = @import("./lib/types.zig");
const CommandStatus = types.CommandStatus;
const CommandContext = types.CommandContext;
pub const Sort = struct {
pub fn eval(sort: Sort, ctx: CommandContext) !CommandStatus {
_ = sort;
var lines = ArrayList([]const u8){};
defer {
for (lines.items) |line| {
ctx.allocator.free(line);
}
lines.deinit(ctx.allocator);
}
// Read input lines from unified input reader
var reader = ctx.input_reader;
// Check if we're reading from stdin vs file redirection for DOS-authentic behavior
switch (ctx.input_reader) {
.stdin => {
// Reading from interactive stdin - show usage message (DOS behavior)
const msg = "SORT: Use input redirection (< file.txt) to sort file contents\n";
var writer = ctx.output_writer;
try writer.write(msg);
return CommandStatus{ .Code = 0 };
},
.source => {
// Read from input redirection
while (try reader.readLine(ctx.allocator)) |line| {
try lines.append(ctx.allocator, line);
}
},
}
// Sort the lines
std.mem.sort([]const u8, lines.items, {}, struct {
fn lessThan(_: void, lhs: []const u8, rhs: []const u8) bool {
return std.mem.order(u8, lhs, rhs) == .lt;
}
}.lessThan);
// Output sorted lines
var output_buffer = ArrayList(u8){};
defer output_buffer.deinit(ctx.allocator);
for (lines.items) |line| {
try output_buffer.writer(ctx.allocator).print("{s}\n", .{line});
}
var writer = ctx.output_writer;
try writer.write(output_buffer.items);
return CommandStatus{ .Code = 0 };
}
};
|