chore: avoid a separate rule slice in DumpMrs

DomainSet emits at most one exact entry and one suffix-only entry for each domain. Sorting without the leading dot makes matching pairs adjacent, so they can be combined in place.

Replace per-entry binary searches and the separate rule slice with an adjacent pairing pass. Merge pairs into +.domain, remove consumed entries from the original slice, and sort the resulting rules by their full text.

Add regression coverage for multiple pairs and wildcard ordering. Output semantics and early termination remain unchanged.
This commit is contained in:
wwqgtxx committed 2026-09-10 22:28:36 +08:00
1 parent 518c7036df
commit 6087521e60
2 files changed
+34 -16

No files matched your search

+19 -16
View File
@@ -81,25 +81,28 @@ func (d *domainStrategy) DumpMrs(f func(key string) bool) {
keys = append(keys, key)
return true
})
// Group exact and suffix-only entries for the same domain.
// Set entries are unique, so each group contains at most two entries.
slices.SortFunc(keys, func(left, right string) int {
left = strings.TrimPrefix(left, ".")
right = strings.TrimPrefix(right, ".")
return strings.Compare(left, right)
})
for index := 0; index+1 < len(keys); index++ {
domain := strings.TrimPrefix(keys[index], ".")
if domain == strings.TrimPrefix(keys[index+1], ".") {
// Both the domain itself and its subdomains are covered by one "+." rule.
keys[index] = "+." + domain
keys[index+1] = ""
index++
}
}
keys = slices.DeleteFunc(keys, func(key string) bool { return key == "" })
// Sort the compact rules by their full text, including wildcard prefixes.
slices.Sort(keys)
// Keep keys unchanged for binary searches; sort the compact rules separately.
rules := make([]string, 0, len(keys))
for _, key := range keys {
if strings.HasPrefix(key, ".") {
if _, ok := slices.BinarySearch(keys, key[1:]); ok {
// Both the domain itself and its subdomains are covered by one "+." rule.
key = "+" + key
}
} else if _, ok := slices.BinarySearch(keys, "."+key); ok {
// The paired suffix entry represents this exact entry in the combined rule.
continue
}
rules = append(rules, key)
}
slices.Sort(rules)
for _, key := range rules {
if !f(key) {
return
}
+15
View File
@@ -52,6 +52,21 @@ func TestDomainStrategyDumpMrs(test *testing.T) {
"www.example.org": true,
},
},
{
"wildcards",
[]string{"*.example.com", "+.example.org", "test.*.google.com", ".test.*.google.com", ".example.net"},
[]string{"*.example.com", "+.example.org", "+.test.*.google.com", ".example.net"},
map[string]bool{
"example.com": false,
"www.example.com": true,
"example.org": true,
"www.example.org": true,
"test.www.google.com": true,
"www.test.www.google.com": true,
"example.net": false,
"www.example.net": true,
},
},
}
for _, testCase := range tests {
test.Run(testCase.name, func(test *testing.T) {