Files
wwqgtxx ebf82e2962 chore: reuse queues during DomainSet build
Build the succinct domain index one level at a time and alternate two reusable queues instead of retaining every processed node until construction completes.

Keep explicit node IDs to preserve terminal ordering, Foreach output, and binary serialization. Query logic and the serialized layout remain unchanged.

This reduces peak build memory and improves construction time for DomainMap. In isolated measurements, the mixed 100k-rule workload used about 53% less peak memory and completed about 11% faster, while deep 100k-rule input used about 72% less peak memory and completed about 24% faster.
2026-09-11 06:51:26 +08:00

337 lines
9.1 KiB
Go

package trie
// Package succinct provides several succinct data types.
// Modify from https://github.com/openacid/succinct/blob/d4684c35d123f7528b14e03c24327231723db704/sskv.go
import (
"sort"
"strings"
"unicode/utf8"
"github.com/metacubex/mihomo/common/utils"
"github.com/openacid/low/bitmap"
"golang.org/x/exp/slices"
)
const (
complexWildcardByte = byte('+')
wildcardByte = byte('*')
domainStepByte = byte('.')
)
type DomainSet struct {
leaves, labelBitmap []uint64
labels []byte
ranks, selects []int32
}
type qElt struct{ s, e int }
// DomainSetBuilder incrementally collects domain patterns for a DomainSet.
// Its zero value is ready to use.
type DomainSetBuilder struct {
keys []string
}
// Insert validates and adds a domain pattern to the builder. It accepts the
// same domain syntax as [DomainTrie.Insert].
func (b *DomainSetBuilder) Insert(domain string) error {
parts, err := ValidAndSplitDomain(domain)
if err != nil {
return err
}
if parts[0] == complexWildcard {
b.insert(parts[1:])
b.insert(parts)
} else {
b.insert(parts)
}
return nil
}
func (b *DomainSetBuilder) insert(parts []string) {
if parts[0] == dotWildcard {
parts[0] = complexWildcard
}
b.keys = append(b.keys, utils.Reverse(joinDomain(parts)))
}
// IsEmpty reports whether the builder contains any domain paths.
func (b *DomainSetBuilder) IsEmpty() bool {
return b == nil || len(b.keys) == 0
}
// Reset discards all domains accumulated by the builder.
func (b *DomainSetBuilder) Reset() {
b.keys = nil
}
// Build consumes the accumulated domains and creates an immutable DomainSet.
// The builder can be reused after Build returns.
func (b *DomainSetBuilder) Build() *DomainSet {
if b == nil {
return nil
}
keys := b.keys
b.keys = nil
return buildDomainSet(keys, nil)
}
// NewDomainSet creates a new *DomainSet struct, from a DomainTrie.
func (t *DomainTrie[T]) NewDomainSet() *DomainSet {
keys := make([]string, 0)
t.Foreach(func(domain string, _ T) bool {
if domain[0] == domainStepByte {
// Suffix-only patterns need an explicit '+' wildcard marker in
// the internal key; a leading dot alone is only a label separator.
domain = complexWildcard + domain
}
keys = append(keys, utils.Reverse(domain))
return true
})
return buildDomainSet(keys, nil)
}
func buildDomainSet(keys []string, onTerminal func(string)) *DomainSet {
if len(keys) == 0 {
return nil
}
// ensure that the same prefix is continuous
// and according to the ascending sequence of length
sort.Strings(keys)
// The construction loop below consumes only one terminal key per node, so a
// duplicate would be indexed past its end and panic.
keys = slices.Compact(keys)
ss := &DomainSet{}
lIdx := 0
nodeID := 0
queue := make([]qElt, 1, len(keys))
queue[0] = qElt{0, len(keys)}
next := make([]qElt, 0, len(keys))
for col := 0; len(queue) > 0; col++ {
for _, elt := range queue {
if col == len(keys[elt.s]) {
if onTerminal != nil {
onTerminal(keys[elt.s])
}
elt.s++
// a leaf node
setBit(&ss.leaves, nodeID, 1)
}
for j := elt.s; j < elt.e; {
frm := j
for ; j < elt.e && keys[j][col] == keys[frm][col]; j++ {
}
next = append(next, qElt{frm, j})
ss.labels = append(ss.labels, keys[frm][col])
setBit(&ss.labelBitmap, lIdx, 0)
lIdx++
}
setBit(&ss.labelBitmap, lIdx, 1)
lIdx++
nodeID++
}
queue, next = next, queue[:0]
}
ss.init()
return ss
}
// Has query for a key and return whether it presents in the DomainSet.
func (ss *DomainSet) Has(key string) bool {
if ss == nil {
return false
}
for i := 0; i < len(key); i++ {
if key[i] >= utf8.RuneSelf {
// The set is built with rune-wise reversal, which only matches
// byte-wise reversal for ASCII. Normalize the same way and
// byte-reverse so revLowerAt below observes it unchanged.
key = byteReverse(strings.ToLower(utils.Reverse(key)))
break
}
}
// no more labels in this node
// skip character matching
// go to next level
nodeId, bmIdx := 0, 0
type wildcardCursor struct {
bmIdx, index int
}
stack := make([]wildcardCursor, 0)
for i := 0; i < len(key); i++ {
RESTART:
c := revLowerAt(key, i)
for ; ; bmIdx++ {
if getBit(ss.labelBitmap, bmIdx) != 0 {
for len(stack) > 0 {
cursor := stack[len(stack)-1]
stack = stack[0 : len(stack)-1]
// back wildcard and find next node
nextNodeId := countZeros(ss.labelBitmap, ss.ranks, cursor.bmIdx+1)
j := cursor.index
for ; j < len(key) && revLowerAt(key, j) != domainStepByte; j++ {
}
if j == len(key) {
if getBit(ss.leaves, nextNodeId) != 0 {
// The wildcard consumed the rest of the key and reached a
// terminal node, so this branch matches.
return true
}
// Otherwise, this node is not terminal and this wildcard branch
// has no input left for child edges. Try any remaining saved wildcards.
continue
}
nextBmIdx := selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nextNodeId-1) + 1
for ; getBit(ss.labelBitmap, nextBmIdx) == 0; nextBmIdx++ {
if ss.labels[nextBmIdx-nextNodeId] == domainStepByte {
bmIdx = nextBmIdx
nodeId = nextNodeId
i = j
goto RESTART
}
}
}
return false
}
// handle wildcard for domain
if ss.labels[bmIdx-nodeId] == complexWildcardByte {
return true
} else if ss.labels[bmIdx-nodeId] == wildcardByte {
cursor := wildcardCursor{}
cursor.bmIdx = bmIdx
cursor.index = i
stack = append(stack, cursor)
} else if ss.labels[bmIdx-nodeId] == c {
break
}
}
nodeId = bmIdx - nodeId + 1 // countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
if i == len(key)-1 {
if getBit(ss.leaves, nodeId) != 0 {
// All input is consumed at a terminal node, so the key matches.
return true
}
if len(stack) == 0 {
// No input remains for this non-terminal node's child edges.
// With no saved wildcard branches left, the key cannot match.
return false
}
bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId)
goto RESTART
}
bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId-1) + 1
}
return getBit(ss.leaves, nodeId) != 0
}
// revLowerAt returns the i-th byte of key read back to front, lowercased for
// ASCII. It lets Has walk the reversed key without materializing it.
func revLowerAt(key string, i int) byte {
c := key[len(key)-1-i]
if c >= 'A' && c <= 'Z' {
c += 'a' - 'A'
}
return c
}
func byteReverse(s string) string {
buf := make([]byte, len(s))
for i := 0; i < len(s); i++ {
buf[i] = s[len(s)-1-i]
}
return string(buf)
}
func (ss *DomainSet) keys(f func(key string, nodeId int) bool) {
var currentKey []byte
var traverse func(int, int) bool
traverse = func(nodeId, bmIdx int) bool {
if getBit(ss.leaves, nodeId) != 0 {
if !f(string(currentKey), nodeId) {
return false
}
}
for ; ; bmIdx++ {
if getBit(ss.labelBitmap, bmIdx) != 0 {
return true
}
nextLabel := ss.labels[bmIdx-nodeId]
currentKey = append(currentKey, nextLabel)
nextNodeId := bmIdx - nodeId + 1 // countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
nextBmIdx := selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nextNodeId-1) + 1
if !traverse(nextNodeId, nextBmIdx) {
return false
}
currentKey = currentKey[:len(currentKey)-1]
}
}
traverse(0, 0)
return
}
// Foreach iterates over the stored domain patterns in unspecified order.
// Patterns use lowercase labels, "*" for a single-label wildcard, and a leading
// "." for subdomain-only matching. Exact and suffix-only patterns are separate
// entries; "+." shorthand is not emitted. Each pattern can be passed to
// DomainSetBuilder.Insert independently to reproduce the set.
func (ss *DomainSet) Foreach(f func(key string) bool) {
ss.keys(func(key string, _ int) bool {
// Internal keys are reversed, with a trailing '+' for suffix wildcards.
// Removing that marker leaves the leading-dot syntax after reversal.
return f(utils.Reverse(strings.TrimSuffix(key, complexWildcard)))
})
}
// MatchDomain implements C.DomainMatcher
func (ss *DomainSet) MatchDomain(domain string) bool {
return ss.Has(domain)
}
func setBit(bm *[]uint64, i int, v int) {
for i>>6 >= len(*bm) {
*bm = append(*bm, 0)
}
(*bm)[i>>6] |= uint64(v) << uint(i&63)
}
func getBit(bm []uint64, i int) uint64 {
return bm[i>>6] & (1 << uint(i&63))
}
// init builds pre-calculated cache to speed up rank() and select()
func (ss *DomainSet) init() {
ss.selects, ss.ranks = bitmap.IndexSelect32R64(ss.labelBitmap)
}
// countZeros counts the number of "0" in a bitmap before the i-th bit(excluding
// the i-th bit) on behalf of rank index.
// E.g.:
//
// countZeros("010010", 4) == 3
// // 012345
func countZeros(bm []uint64, ranks []int32, i int) int {
a, _ := bitmap.Rank64(bm, ranks, int32(i))
return i - int(a)
}
// selectIthOne returns the index of the i-th "1" in a bitmap, on behalf of rank
// and select indexes.
// E.g.:
//
// selectIthOne("010010", 1) == 4
// // 012345
func selectIthOne(bm []uint64, ranks, selects []int32, i int) int {
a, _ := bitmap.Select32R64(bm, selects, ranks, int32(i))
return int(a)
}