github.com/sagernet/sing-box@v1.9.0-rc.20/route/rule_item_user_id.go (about)

     1  package route
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/sagernet/sing-box/adapter"
     7  	F "github.com/sagernet/sing/common/format"
     8  )
     9  
    10  var _ RuleItem = (*UserIdItem)(nil)
    11  
    12  type UserIdItem struct {
    13  	userIds   []int32
    14  	userIdMap map[int32]bool
    15  }
    16  
    17  func NewUserIDItem(userIdList []int32) *UserIdItem {
    18  	rule := &UserIdItem{
    19  		userIds:   userIdList,
    20  		userIdMap: make(map[int32]bool),
    21  	}
    22  	for _, userId := range userIdList {
    23  		rule.userIdMap[userId] = true
    24  	}
    25  	return rule
    26  }
    27  
    28  func (r *UserIdItem) Match(metadata *adapter.InboundContext) bool {
    29  	if metadata.ProcessInfo == nil || metadata.ProcessInfo.UserId == -1 {
    30  		return false
    31  	}
    32  	return r.userIdMap[metadata.ProcessInfo.UserId]
    33  }
    34  
    35  func (r *UserIdItem) String() string {
    36  	var description string
    37  	pLen := len(r.userIds)
    38  	if pLen == 1 {
    39  		description = "user_id=" + F.ToString(r.userIds[0])
    40  	} else {
    41  		description = "user_id=[" + strings.Join(F.MapToString(r.userIds), " ") + "]"
    42  	}
    43  	return description
    44  }