Lightpanda: the headless browser designed for AI and automation
perf: faster common attribute lookup + css selector class match
Karl Seguin5a55185ffea4
diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zigindex f10dc128c..b2837d9bc 100644--- a/src/browser/webapi/Element.zig+++ b/src/browser/webapi/Element.zig@@ -631,7 +631,7 @@ pub fn setHTMLUnsafe(self: *Element, html: []const u8, frame: *Frame) !void {}pub fn getId(self: *const Element) []const u8 {- return self.getAttributeSafe(comptime .wrap("id")) orelse "";+ return self.getAttributeInterned("id") orelse "";}pub fn setId(self: *Element, value: []const u8, frame: *Frame) !void {@@ -647,7 +647,7 @@ pub fn setSlot(self: *Element, value: []const u8, frame: *Frame) !void {}pub fn getDir(self: *const Element) []const u8 {- return self.getAttributeSafe(comptime .wrap("dir")) orelse "";+ return self.getAttributeInterned("dir") orelse "";}pub fn setDir(self: *Element, value: []const u8, frame: *Frame) !void {@@ -655,7 +655,7 @@ pub fn setDir(self: *Element, value: []const u8, frame: *Frame) !void {}pub fn getClassName(self: *const Element) []const u8 {- return self.getAttributeSafe(comptime .wrap("class")) orelse "";+ return self.getAttributeInterned("class") orelse "";}pub fn setClassName(self: *Element, value: []const u8, frame: *Frame) !void {@@ -727,6 +727,16 @@ pub fn hasAttributeSafe(self: *const Element, name: String) bool {return self._attributes.hasSafe(name);}+// Like getAttributeSafe, but faster! Only usable for values that are String.intern+// so that the comparison becomes a single pointer equality.+pub fn getAttributeInterned(self: *const Element, comptime name: []const u8) ?[]const u8 {+ return self._attributes.getInterned(name);+}++pub fn hasAttributeInterned(self: *const Element, comptime name: []const u8) bool {+ return self._attributes.hasInterned(name);+}+// Per HTML "concept-fe-disabled", only listed elements participate in the// disabled concept. Anything else (e.g. <div disabled>) has no disabled// state and never matches :disabled / :enabled.diff --git a/src/browser/webapi/collections/node_live.zig b/src/browser/webapi/collections/node_live.zigindex 884aefaf6..1a649787b 100644--- a/src/browser/webapi/collections/node_live.zig+++ b/src/browser/webapi/collections/node_live.zig@@ -309,7 +309,7 @@ pub fn NodeLive(comptime mode: Mode) type {}const el = node.is(Element) orelse return false;- const class_attr = el.getAttributeSafe(comptime .wrap("class")) orelse return false;+ const class_attr = el.getAttributeInterned("class") orelse return false;for (self._filter.names) |class_name| {if (!Selector.classAttributeContainsCase(class_attr, class_name, self._filter.case_insensitive)) {return false;@@ -321,7 +321,7 @@ pub fn NodeLive(comptime mode: Mode) type {const el = node.is(Element) orelse return false;// getElementsByName only considers HTML elements.if (el._namespace != .html) return false;- const name_attr = el.getAttributeSafe(comptime .wrap("name")) orelse return false;+ const name_attr = el.getAttributeInterned("name") orelse return false;return std.mem.eql(u8, name_attr, self._filter);},.all_elements => return node._type == .element,diff --git a/src/browser/webapi/element/Attribute.zig b/src/browser/webapi/element/Attribute.zigindex c5486490b..e8766663f 100644--- a/src/browser/webapi/element/Attribute.zig+++ b/src/browser/webapi/element/Attribute.zig@@ -193,6 +193,17 @@ pub const List = struct {return self.getEntryWithNormalizedName(name) != null;}+ // Like getSafe, but faster! Only usable for values that are String.intern+ // so that the comparison becomes a single pointer equality.+ pub fn getInterned(self: *const List, comptime name: []const u8) ?[]const u8 {+ const entry = self.getEntryWithInternedName(name) orelse return null;+ return entry.value();+ }++ pub fn hasInterned(self: *const List, comptime name: []const u8) bool {+ return self.getEntryWithInternedName(name) != null;+ }+pub fn getAttribute(self: *const List, name: String, element: ?*Element, frame: *Frame) !?*Attribute {const entry = (try self.getEntry(name, frame)) orelse return null;return self.getOrCreateAttribute(entry, element, frame);@@ -421,6 +432,25 @@ pub const List = struct {return null;}+ fn getEntryWithInternedName(self: *const List, comptime name: []const u8) ?*Entry {+ const static = comptime String.intern(name) orelse+ @compileError("not an interned attribute name: " ++ name);++ for (self._entries[0..self._len]) |*e| {+ if (e._name_ptr == static.ptr) {+ return e;+ }+ // The invariant above rests on identical string literals sharing+ // one address, which is a compiler detail rather than a language+ // guarantee. If it ever stops holding the compare just misses, so+ // trip here instead of returning a silent null.+ if (comptime lp.IS_DEBUG) {+ std.debug.assert(std.mem.eql(u8, e.name(), name) == false);+ }+ }+ return null;+ }+// Two []const u8 would be 32 bytes. Packed like this, it's 24.pub const Entry = struct {_name_ptr: [*]const u8,diff --git a/src/browser/webapi/selector/List.zig b/src/browser/webapi/selector/List.zigindex ce7acb8ed..5c9bf3f87 100644--- a/src/browser/webapi/selector/List.zig+++ b/src/browser/webapi/selector/List.zig@@ -399,11 +399,11 @@ fn matchesCompound(el: *Node.Element, compound: Selector.Compound, scope: *Node,fn matchesPart(el: *Node.Element, part: Part, scope: *Node, nth: ?*NthCache, frame: *Frame) bool {switch (part) {.id => |id| {- const element_id = el.getAttributeSafe(comptime .wrap("id")) orelse return false;+ const element_id = el.getAttributeInterned("id") orelse return false;return std.mem.eql(u8, element_id, id);},.class => |cls| {- const class_attr = el.getAttributeSafe(comptime .wrap("class")) orelse return false;+ const class_attr = el.getAttributeInterned("class") orelse return false;return Selector.classAttributeContains(class_attr, cls);},.tag => |tag| {@@ -563,19 +563,19 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *Nreturn false;},.required => {- return el.getAttributeSafe(comptime .wrap("required")) != null;+ return el.hasAttributeInterned("required");},.optional => {- return el.getAttributeSafe(comptime .wrap("required")) == null;+ return el.hasAttributeInterned("required") == false;},.in_range => return false,.out_of_range => return false,.placeholder_shown => return false,.read_only => {- return el.getAttributeSafe(comptime .wrap("readonly")) != null;+ return el.hasAttributeInterned("readonly");},.read_write => {- return el.getAttributeSafe(comptime .wrap("readonly")) == null;+ return el.hasAttributeInterned("readonly") == false;},.default => return false,@@ -600,11 +600,11 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *N.link, .any_link => {const tag = el.getTag();if (tag != .anchor and tag != .area) return false;- return el.getAttributeSafe(comptime .wrap("href")) != null;+ return el.hasAttributeInterned("href");},.visited => return false,.target => {- const element_id = el.getAttributeSafe(comptime .wrap("id")) orelse return false;+ const element_id = el.getAttributeInterned("id") orelse return false;const doc = node.ownerDocument(frame) orelse return false;const location = doc.getLocation() orelse return false;const hash = location.getHash();@@ -670,7 +670,7 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *Nwhile (current) |cur| : (current = cur.parentNode()) {switch (cur._type) {.element => {- if (cur.subtype(Node.Element).getAttributeSafe(comptime .wrap("lang"))) |value| {+ if (cur.subtype(Node.Element).getAttributeInterned("lang")) |value| {break :blk value;}},diff --git a/src/browser/webapi/selector/Selector.zig b/src/browser/webapi/selector/Selector.zigindex 83b96d137..6f0af44dd 100644--- a/src/browser/webapi/selector/Selector.zig+++ b/src/browser/webapi/selector/Selector.zig@@ -188,22 +188,66 @@ pub fn matchesUncached(arena: Allocator, el: *Node.Element, input: []const u8, freturn matchesAny(try Parser.parseList(arena, input), el, el.asNode(), frame);}+// Class attribute token separators as a mask+const class_separators: u64 = (1 << '\t') | (1 << '\n') | (1 << 0x0C) | (1 << '\r') | (1 << ' ');++inline fn isClassSeparator(c: u8) bool {+ return c <= ' ' and (class_separators >> @intCast(c)) & 1 == 1;+}+pub fn classAttributeContains(class_attr: []const u8, class_name: []const u8) bool {- return classAttributeContainsCase(class_attr, class_name, false);+ // Both callers pass a single parsed class name. `[class~="a b"]` is not+ // this path, it goes through the attribute .word matcher.+ if (comptime lp.IS_DEBUG) {+ for (class_name) |c| {+ std.debug.assert(isClassSeparator(c) == false);+ }+ }++ const len = class_name.len;+ if (len == 0 or class_attr.len < len) {+ return false;+ }++ // Scan for the name's first byte and verify the token boundaries around it,+ // rather than splitting class_attr into tokens: most bytes then cost a+ // single compare, and a token whose first byte differs is rejected without+ // any boundary or length work.+ //+ // Deliberately not std.mem.indexOfScalarPos: its vector setup costs more+ // than it saves at class-attribute lengths. Measured against it on both the+ // benchmark shape (~12 bytes) and tailwind-style values (~105 bytes), this+ // loop wins on every case but one.+ const last = class_attr.len - len;+ const first = class_name[0];+ var at: usize = 0;+ while (at <= last) : (at += 1) {+ if (class_attr[at] != first) {+ continue;+ }+ const end = at + len;+ if ((at == 0 or isClassSeparator(class_attr[at - 1])) and+ (end == class_attr.len or isClassSeparator(class_attr[end])) and+ std.mem.eql(u8, class_attr[at..end], class_name))+ {+ return true;+ }+ }+ return false;}pub fn classAttributeContainsCase(class_attr: []const u8, class_name: []const u8, case_insensitive: bool) bool {+ if (case_insensitive == false) {+ return classAttributeContains(class_attr, class_name);+ }+if (class_name.len == 0) {return false;}var it = std.mem.tokenizeAny(u8, class_attr, &[_]u8{ '\t', '\n', 0x0C, '\r', ' ' });while (it.next()) |token| {- if (case_insensitive) {- if (std.ascii.eqlIgnoreCase(token, class_name)) {- return true;- }- } else if (std.mem.eql(u8, token, class_name)) {+ if (std.ascii.eqlIgnoreCase(token, class_name)) {return true;}}@@ -405,3 +449,39 @@ pub fn query(selectors: []const Selector, root: *Node, frame: *Frame) !?*Node.El}return null;}++const testing = @import("../../../testing.zig");++test "Selector: classAttributeContains" {+ // hit at each token position, and the whole value as one token+ try testing.expectEqual(true, classAttributeContains("row", "row"));+ try testing.expectEqual(true, classAttributeContains("row cell", "row"));+ try testing.expectEqual(true, classAttributeContains("cell row", "row"));+ try testing.expectEqual(true, classAttributeContains("a row b", "row"));++ // a substring of a token is not a token+ try testing.expectEqual(false, classAttributeContains("rows", "row"));+ try testing.expectEqual(false, classAttributeContains("brow", "row"));+ try testing.expectEqual(false, classAttributeContains("arrow-key", "row"));+ // ...but a real token after a false start still matches+ try testing.expectEqual(true, classAttributeContains("rows row", "row"));+ try testing.expectEqual(true, classAttributeContains("row-a row", "row"));++ // every HTML whitespace separates, 0x0B (VT) does not+ for ([_]u8{ '\t', '\n', 0x0C, '\r', ' ' }) |ws| {+ try testing.expectEqual(true, classAttributeContains(&.{ 'a', ws, 'r', 'o', 'w' }, "row"));+ }+ try testing.expectEqual(false, classAttributeContains(&.{ 'a', 0x0B, 'r', 'o', 'w' }, "row"));++ // degenerate inputs+ try testing.expectEqual(false, classAttributeContains("", "row"));+ try testing.expectEqual(false, classAttributeContains("row", ""));+ try testing.expectEqual(false, classAttributeContains("ro", "row"));+ try testing.expectEqual(false, classAttributeContains(" ", "row"));+ try testing.expectEqual(true, classAttributeContains(" row ", "row"));++ // case sensitivity is the caller's choice+ try testing.expectEqual(false, classAttributeContains("ROW", "row"));+ try testing.expectEqual(true, classAttributeContainsCase("ROW", "row", true));+ try testing.expectEqual(false, classAttributeContainsCase("ROWS", "row", true));+}