summaryrefslogtreecommitdiff
path: root/src/ghost_io.zig
diff options
context:
space:
mode:
authort <t@tjp.lol>2026-11-24 15:36:26 -0700
committert <t@tjp.lol>2026-11-24 21:10:19 -0700
commit3594d230f5368d4200e590654aad040432bee82e (patch)
tree6d0a58e3545df021ee24d02f47a18e870aa17e31 /src/ghost_io.zig
Add Write_Away macOS writing prototype
Diffstat (limited to 'src/ghost_io.zig')
-rw-r--r--src/ghost_io.zig135
1 files changed, 135 insertions, 0 deletions
diff --git a/src/ghost_io.zig b/src/ghost_io.zig
new file mode 100644
index 0000000..e5061ff
--- /dev/null
+++ b/src/ghost_io.zig
@@ -0,0 +1,135 @@
+//! Remove and restore ghost spans without interpreting Markdown.
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+/// `ghosts` is an array or slice of records with `at: usize` (a full-body byte
+/// offset) and `text: []const u8`. Spans must be sorted, nonempty, disjoint,
+/// and match the body exactly at UTF-8 codepoint boundaries. Adjacent spans
+/// are allowed. The caller owns the returned slice, even with no ghosts.
+pub fn visible(allocator: Allocator, body: []const u8, ghosts: anytype) ![]const u8 {
+ if (ghosts.len != 0 and !std.unicode.utf8ValidateSlice(body)) return error.InvalidUtf8;
+ var end: usize = 0;
+ var removed: usize = 0;
+ for (ghosts) |g| {
+ if (g.text.len == 0 or g.at < end or g.at > body.len or g.text.len > body.len - g.at)
+ return error.InvalidGhost;
+ end = g.at + g.text.len;
+ if (!isBoundary(body, g.at) or !isBoundary(body, end) or
+ !std.mem.eql(u8, body[g.at..end], g.text)) return error.InvalidGhost;
+ removed += g.text.len;
+ }
+
+ const out = try allocator.alloc(u8, body.len - removed);
+ var read: usize = 0;
+ var written: usize = 0;
+ for (ghosts) |g| {
+ const keep = body[read..g.at];
+ @memcpy(out[written..][0..keep.len], keep);
+ written += keep.len;
+ read = g.at + g.text.len;
+ }
+ @memcpy(out[written..], body[read..]);
+ return out;
+}
+
+/// Reinsert every ghost, or return an error without producing a partial body.
+/// Pass the exact visible bytes, excluding metadata and its framing. The caller
+/// owns the returned slice. On failure, keep the original Markdown and metadata
+/// intact rather than continuing with a partially decoded document.
+///
+/// Offset-only records cannot detect edits that leave all insertion points in
+/// bounds and on codepoint boundaries. In that case restore inserts all text at
+/// the recorded positions, without guessing new ones. To reject such edits,
+/// the caller must verify a separately stored digest of the visible bytes and
+/// fall back to the original Markdown on mismatch.
+pub fn restore(allocator: Allocator, body_visible: []const u8, ghosts: anytype) ![]const u8 {
+ if (ghosts.len != 0 and !std.unicode.utf8ValidateSlice(body_visible)) return error.InvalidUtf8;
+ var removed: usize = 0;
+ var read: usize = 0;
+ for (ghosts) |g| {
+ if (g.text.len == 0 or g.at < removed) return error.InvalidGhost;
+ const at = g.at - removed;
+ if (at < read or at > body_visible.len or !isBoundary(body_visible, at))
+ return error.InvalidGhost;
+ if (!std.unicode.utf8ValidateSlice(g.text)) return error.InvalidUtf8;
+ removed = try std.math.add(usize, removed, g.text.len);
+ read = at;
+ }
+
+ const out = try allocator.alloc(u8, try std.math.add(usize, body_visible.len, removed));
+ read = 0;
+ var written: usize = 0;
+ removed = 0;
+ for (ghosts) |g| {
+ const at = g.at - removed;
+ @memcpy(out[written..g.at], body_visible[read..at]);
+ written = g.at + g.text.len;
+ @memcpy(out[g.at..written], g.text);
+ removed += g.text.len;
+ read = at;
+ }
+ @memcpy(out[written..], body_visible[read..]);
+ return out;
+}
+
+// Only called for an in-bounds offset in a validated UTF-8 slice.
+fn isBoundary(bytes: []const u8, at: usize) bool {
+ return at == bytes.len or bytes[at] & 0xc0 != 0x80;
+}
+
+const TestGhost = struct { at: usize, text: []const u8 };
+const t = std.testing;
+
+fn expectRoundTrip(body: []const u8, expected: []const u8, ghosts: []const TestGhost) !void {
+ const stripped = try visible(t.allocator, body, ghosts);
+ defer t.allocator.free(stripped);
+ try t.expectEqualStrings(expected, stripped);
+ const restored = try restore(t.allocator, stripped, ghosts);
+ defer t.allocator.free(restored);
+ try t.expectEqualStrings(body, restored);
+}
+
+test "strip exact occurrences in a heading and a code fence, including adjacent multiline Unicode ghosts" {
+ const heading = "# café";
+ const code = "\n```zig\nx = x";
+ const multiline = ";\n// 👻\n";
+ const adjacent = "// ghost";
+ const suffix = "\n```\n";
+ const end = (heading ++ " café" ++ code).len;
+ try expectRoundTrip(heading ++ " café" ++ code ++ multiline ++ adjacent ++ suffix, heading ++ code ++ suffix, &.{
+ .{ .at = heading.len, .text = " café" },
+ .{ .at = end, .text = multiline },
+ .{ .at = end + multiline.len, .text = adjacent },
+ });
+}
+
+test "empty ghost list, empty visible body, and ghosts at both edges" {
+ try expectRoundTrip("\xff\r\n", "\xff\r\n", &.{});
+ try expectRoundTrip("👻a", "", &.{ .{ .at = 0, .text = "👻" }, .{ .at = "👻".len, .text = "a" } });
+ try expectRoundTrip("abc", "b", &.{ .{ .at = 0, .text = "a" }, .{ .at = 2, .text = "c" } });
+}
+
+test "reject malformed records instead of relocating or dropping a ghost" {
+ const overlap = [_]TestGhost{ .{ .at = 1, .text = "bc" }, .{ .at = 2, .text = "c" } };
+ const unsorted = [_]TestGhost{ .{ .at = 2, .text = "c" }, .{ .at = 0, .text = "a" } };
+ const empty = [_]TestGhost{.{ .at = 0, .text = "" }};
+ const far = [_]TestGhost{.{ .at = std.math.maxInt(usize), .text = "a" }};
+ for ([_][]const TestGhost{ &overlap, &unsorted, &empty, &far }) |ghosts| {
+ try t.expectError(error.InvalidGhost, visible(t.allocator, "abc", ghosts));
+ try t.expectError(error.InvalidGhost, restore(t.allocator, "abc", ghosts));
+ }
+ try t.expectError(error.InvalidGhost, visible(t.allocator, "aba", [_]TestGhost{.{ .at = 1, .text = "a" }}));
+ try t.expectError(error.InvalidGhost, visible(t.allocator, "a", [_]TestGhost{.{ .at = 0, .text = "ab" }}));
+ try t.expectError(error.InvalidGhost, visible(t.allocator, "é", [_]TestGhost{.{ .at = 0, .text = "\xc3" }}));
+ try t.expectError(error.InvalidGhost, visible(t.allocator, "é", [_]TestGhost{.{ .at = 1, .text = "\xa9" }}));
+ try t.expectError(error.InvalidUtf8, restore(t.allocator, "", [_]TestGhost{.{ .at = 0, .text = "\xa9" }}));
+}
+
+test "external edits can invalidate an offset; otherwise restore keeps every ghost at its recorded position" {
+ const ghosts = [_]TestGhost{.{ .at = 1, .text = "👻" }};
+ try t.expectError(error.InvalidGhost, restore(t.allocator, "", ghosts));
+ try t.expectError(error.InvalidGhost, restore(t.allocator, "é", ghosts));
+ const restored = try restore(t.allocator, "xyz", ghosts);
+ defer t.allocator.free(restored);
+ try t.expectEqualStrings("x👻yz", restored);
+}