//! Hyperlink attached to a cell (OSC 8). Both slices are borrowed from a //! buffer-owned string. const std = @import("std"); const Profile = @import("root.zig").Profile; const Allocator = std.mem.Allocator; const t = std.testing; const Link = @This(); url: []const u8 = "", params: []const u8 = "", pub fn init(url: []const u8, params: []const u8) Link { return .{ .url = url, .params = params }; } pub fn deinit(self: *Link, allocator: Allocator) void { allocator.free(self.params); allocator.free(self.url); } pub fn equal(a: Link, b: Link) bool { return std.mem.eql(u8, a.url, b.url) and std.mem.eql(u8, a.params, b.params); } pub fn isZero(l: Link) bool { return l.url.len == 0 and l.params.len == 0; } /// Reads an OSC 8 hyperlink payload into `link`, mirroring uv `ReadLink` /// (styled.go). `d` is the raw data (`;` after the OSC `8;` /// prefix). The params and url are copied into `d`-independent allocations. /// Malformed payloads (wrong part count) leave `link` untouched. pub fn read(self: *Link, allocator: Allocator, d: []const u8) !void { var parts: [3][]const u8 = undefined; var count: usize = 0; var it = std.mem.splitScalar(u8, d, ';'); while (it.next()) |part| { if (count >= 3) return; parts[count] = part; count += 1; } // The first part is the OSC command ("8"); reject anything else. if (count != 3) return; self.params = try allocator.dupe(u8, parts[1]); self.url = try allocator.dupe(u8, parts[2]); } /// Mirrors uv `ConvertLink` (cell.go): NoTTY drops the hyperlink. pub fn convertLink(self: Link, profile: Profile) Link { if (profile == .no_tty) return .{}; return self; } test "link equality and zero" { const link: Link = .{}; try t.expect(link.isZero()); const a: Link = .init("https://x", ""); const b: Link = .init("https://x", ""); try t.expect(a.equal(b)); const c: Link = .init("https://y", "id=1"); try t.expect(!a.equal(c)); } test "fuzz link" { try t.fuzz({}, fuzzLink, .{ .corpus = &.{ "", "id=1;https://example.com", ";https://x", ";;", "a;b;c;d", "\x00;", }, }); } fn fuzzLink(_: void, smith: *t.Smith) anyerror!void { var buf: [256]u8 = undefined; const len = smith.slice(&buf); var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); var link: Link = .{}; // `read` only allocates on well-formed payloads; reclaim everything via // the arena so corpus replay never leaks. link.read(arena.allocator(), buf[0..len]) catch return; _ = link.isZero(); _ = link.convertLink(.no_tty); _ = link.convertLink(.true_color); }