| ... | ... | @@ -1,55 +0,0 @@ |
| 1 | | const std = @import("../std.zig"); |
| 2 | | const io = std.io; |
| 3 | | const mem = std.mem; |
| 4 | | const assert = std.debug.assert; |
| 5 | | |
| 6 | | /// Used to detect if the data written to a stream differs from a source buffer |
| 7 | | pub fn ChangeDetectionStream(comptime WriterType: type) type { |
| 8 | | return struct { |
| 9 | | const Self = @This(); |
| 10 | | pub const Error = WriterType.Error; |
| 11 | | pub const Writer = io.GenericWriter(*Self, Error, write); |
| 12 | | |
| 13 | | anything_changed: bool, |
| 14 | | underlying_writer: WriterType, |
| 15 | | source_index: usize, |
| 16 | | source: []const u8, |
| 17 | | |
| 18 | | pub fn writer(self: *Self) Writer { |
| 19 | | return .{ .context = self }; |
| 20 | | } |
| 21 | | |
| 22 | | fn write(self: *Self, bytes: []const u8) Error!usize { |
| 23 | | if (!self.anything_changed) { |
| 24 | | const end = self.source_index + bytes.len; |
| 25 | | if (end > self.source.len) { |
| 26 | | self.anything_changed = true; |
| 27 | | } else { |
| 28 | | const src_slice = self.source[self.source_index..end]; |
| 29 | | self.source_index += bytes.len; |
| 30 | | if (!mem.eql(u8, bytes, src_slice)) { |
| 31 | | self.anything_changed = true; |
| 32 | | } |
| 33 | | } |
| 34 | | } |
| 35 | | |
| 36 | | return self.underlying_writer.write(bytes); |
| 37 | | } |
| 38 | | |
| 39 | | pub fn changeDetected(self: *Self) bool { |
| 40 | | return self.anything_changed or (self.source_index != self.source.len); |
| 41 | | } |
| 42 | | }; |
| 43 | | } |
| 44 | | |
| 45 | | pub fn changeDetectionStream( |
| 46 | | source: []const u8, |
| 47 | | underlying_writer: anytype, |
| 48 | | ) ChangeDetectionStream(@TypeOf(underlying_writer)) { |
| 49 | | return ChangeDetectionStream(@TypeOf(underlying_writer)){ |
| 50 | | .anything_changed = false, |
| 51 | | .underlying_writer = underlying_writer, |
| 52 | | .source_index = 0, |
| 53 | | .source = source, |
| 54 | | }; |
| 55 | | } |