make multiple substitutions work and other cleanup

This commit is contained in:
Emil Lerch 2025-09-18 13:44:05 -07:00
parent 899d5fdfc5
commit a30c6d9ea1
Signed by: lobo
GPG key ID: A7B62D657EF764F8
2 changed files with 17 additions and 24 deletions

View file

@ -45,8 +45,6 @@ pub fn main() !u8 {
}; };
defer file.close(); defer file.close();
var buffer: [4096]u8 = undefined;
const temp_path = try std.fmt.allocPrint(allocator, "{s}.tmp", .{file_path}); const temp_path = try std.fmt.allocPrint(allocator, "{s}.tmp", .{file_path});
defer allocator.free(temp_path); defer allocator.free(temp_path);
@ -56,12 +54,16 @@ pub fn main() !u8 {
}; };
defer temp_file.close(); defer temp_file.close();
var output_buffer: [4096]u8 = undefined; // don't screw with vars and consts in this block...
var reader = file.reader(&buffer).interface; var reader_buffer: [4096]u8 = undefined;
var writer = temp_file.writer(&output_buffer).interface; var freader = file.reader(&reader_buffer);
const reader = &freader.interface;
var writer_buffer: [4096]u8 = undefined;
var fwriter = temp_file.writer(&writer_buffer);
const writer = &fwriter.interface;
try substituteLines( try substituteLines(
&reader, reader,
&writer, writer,
substitutions, substitutions,
); );
try writer.flush(); try writer.flush();
@ -82,27 +84,23 @@ const Substitution = struct {
}; };
fn substituteLines(reader: *std.Io.Reader, writer: *std.Io.Writer, substitutions: []const Substitution) !void { fn substituteLines(reader: *std.Io.Reader, writer: *std.Io.Writer, substitutions: []const Substitution) !void {
var line_buf: [1024]u8 = undefined; while (reader.takeDelimiterExclusive('\n')) |line| {
var line = std.Io.Writer.fixed(&line_buf);
while ((try reader.streamDelimiterEnding(&line, '\n')) > 0) : (_ = line.consumeAll()) {
const line_content = line.buffered();
var substituted = false; var substituted = false;
for (substitutions) |sub| { for (substitutions) |sub| {
if (std.mem.eql(u8, line_content, sub.original)) { if (std.mem.eql(u8, line, sub.original)) {
try writer.writeAll(sub.replacement); try writer.writeAll(sub.replacement);
substituted = true; substituted = true;
break; break;
} }
} }
if (!substituted) if (!substituted)
try writer.writeAll(line_content); try writer.writeAll(line);
// Write our \n if (reader.peekByte() != error.EndOfStream)
if (reader.takeByte()) |b| try writer.writeByte('\n');
try writer.writeByte(b) } else |err| if (err != error.EndOfStream) return err;
else |_| {} // end of stream // write the final newline
} // try writer.writeByte('\n');
} }
test "substitute lines exact match" { test "substitute lines exact match" {

View file

@ -1,5 +0,0 @@
line1
old_text
line3
another_old
line5