mph_matcher.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package strmatcher
  2. import (
  3. "math/bits"
  4. "regexp"
  5. "sort"
  6. "strings"
  7. "unsafe"
  8. )
  9. // PrimeRK is the prime base used in Rabin-Karp algorithm.
  10. const PrimeRK = 16777619
  11. // calculate the rolling murmurHash of given string
  12. func RollingHash(s string) uint32 {
  13. h := uint32(0)
  14. for i := len(s) - 1; i >= 0; i-- {
  15. h = h*PrimeRK + uint32(s[i])
  16. }
  17. return h
  18. }
  19. // A MphMatcherGroup is divided into three parts:
  20. // 1. `full` and `domain` patterns are matched by Rabin-Karp algorithm and minimal perfect hash table;
  21. // 2. `substr` patterns are matched by ac automaton;
  22. // 3. `regex` patterns are matched with the regex library.
  23. type MphMatcherGroup struct {
  24. ac *ACAutomaton
  25. otherMatchers []matcherEntry
  26. rules []string
  27. level0 []uint32
  28. level0Mask int
  29. level1 []uint32
  30. level1Mask int
  31. count uint32
  32. ruleMap *map[string]uint32
  33. }
  34. func (g *MphMatcherGroup) AddFullOrDomainPattern(pattern string, t Type) {
  35. h := RollingHash(pattern)
  36. switch t {
  37. case Domain:
  38. (*g.ruleMap)["."+pattern] = h*PrimeRK + uint32('.')
  39. fallthrough
  40. case Full:
  41. (*g.ruleMap)[pattern] = h
  42. default:
  43. }
  44. }
  45. func NewMphMatcherGroup() *MphMatcherGroup {
  46. return &MphMatcherGroup{
  47. ac: nil,
  48. otherMatchers: nil,
  49. rules: nil,
  50. level0: nil,
  51. level0Mask: 0,
  52. level1: nil,
  53. level1Mask: 0,
  54. count: 1,
  55. ruleMap: &map[string]uint32{},
  56. }
  57. }
  58. // AddPattern adds a pattern to MphMatcherGroup
  59. func (g *MphMatcherGroup) AddPattern(pattern string, t Type) (uint32, error) {
  60. switch t {
  61. case Substr:
  62. if g.ac == nil {
  63. g.ac = NewACAutomaton()
  64. }
  65. g.ac.Add(pattern, t)
  66. case Full, Domain:
  67. pattern = strings.ToLower(pattern)
  68. g.AddFullOrDomainPattern(pattern, t)
  69. case Regex:
  70. r, err := regexp.Compile(pattern)
  71. if err != nil {
  72. return 0, err
  73. }
  74. g.otherMatchers = append(g.otherMatchers, matcherEntry{
  75. m: &regexMatcher{pattern: r},
  76. id: g.count,
  77. })
  78. default:
  79. panic("Unknown type")
  80. }
  81. return g.count, nil
  82. }
  83. // Build builds a minimal perfect hash table and ac automaton from insert rules
  84. func (g *MphMatcherGroup) Build() {
  85. if g.ac != nil {
  86. g.ac.Build()
  87. }
  88. keyLen := len(*g.ruleMap)
  89. g.level0 = make([]uint32, nextPow2(keyLen/4))
  90. g.level0Mask = len(g.level0) - 1
  91. g.level1 = make([]uint32, nextPow2(keyLen))
  92. g.level1Mask = len(g.level1) - 1
  93. var sparseBuckets = make([][]int, len(g.level0))
  94. var ruleIdx int
  95. for rule, hash := range *g.ruleMap {
  96. n := int(hash) & g.level0Mask
  97. g.rules = append(g.rules, rule)
  98. sparseBuckets[n] = append(sparseBuckets[n], ruleIdx)
  99. ruleIdx++
  100. }
  101. g.ruleMap = nil
  102. var buckets []indexBucket
  103. for n, vals := range sparseBuckets {
  104. if len(vals) > 0 {
  105. buckets = append(buckets, indexBucket{n, vals})
  106. }
  107. }
  108. sort.Sort(bySize(buckets))
  109. occ := make([]bool, len(g.level1))
  110. var tmpOcc []int
  111. for _, bucket := range buckets {
  112. var seed = uint32(0)
  113. for {
  114. findSeed := true
  115. tmpOcc = tmpOcc[:0]
  116. for _, i := range bucket.vals {
  117. n := int(strhashFallback(unsafe.Pointer(&g.rules[i]), uintptr(seed))) & g.level1Mask
  118. if occ[n] {
  119. for _, n := range tmpOcc {
  120. occ[n] = false
  121. }
  122. seed++
  123. findSeed = false
  124. break
  125. }
  126. occ[n] = true
  127. tmpOcc = append(tmpOcc, n)
  128. g.level1[n] = uint32(i)
  129. }
  130. if findSeed {
  131. g.level0[bucket.n] = seed
  132. break
  133. }
  134. }
  135. }
  136. }
  137. func nextPow2(v int) int {
  138. if v <= 1 {
  139. return 1
  140. }
  141. const MaxUInt = ^uint(0)
  142. n := (MaxUInt >> bits.LeadingZeros(uint(v))) + 1
  143. return int(n)
  144. }
  145. // Lookup searches for s in t and returns its index and whether it was found.
  146. func (g *MphMatcherGroup) Lookup(h uint32, s string) bool {
  147. i0 := int(h) & g.level0Mask
  148. seed := g.level0[i0]
  149. i1 := int(strhashFallback(unsafe.Pointer(&s), uintptr(seed))) & g.level1Mask
  150. n := g.level1[i1]
  151. return s == g.rules[int(n)]
  152. }
  153. // Match implements IndexMatcher.Match.
  154. func (g *MphMatcherGroup) Match(pattern string) []uint32 {
  155. result := []uint32{}
  156. hash := uint32(0)
  157. for i := len(pattern) - 1; i >= 0; i-- {
  158. hash = hash*PrimeRK + uint32(pattern[i])
  159. if pattern[i] == '.' {
  160. if g.Lookup(hash, pattern[i:]) {
  161. result = append(result, 1)
  162. return result
  163. }
  164. }
  165. }
  166. if g.Lookup(hash, pattern) {
  167. result = append(result, 1)
  168. return result
  169. }
  170. if g.ac != nil && g.ac.Match(pattern) {
  171. result = append(result, 1)
  172. return result
  173. }
  174. for _, e := range g.otherMatchers {
  175. if e.m.Match(pattern) {
  176. result = append(result, e.id)
  177. return result
  178. }
  179. }
  180. return nil
  181. }
  182. type indexBucket struct {
  183. n int
  184. vals []int
  185. }
  186. type bySize []indexBucket
  187. func (s bySize) Len() int { return len(s) }
  188. func (s bySize) Less(i, j int) bool { return len(s[i].vals) > len(s[j].vals) }
  189. func (s bySize) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  190. type stringStruct struct {
  191. str unsafe.Pointer
  192. len int
  193. }
  194. func strhashFallback(a unsafe.Pointer, h uintptr) uintptr {
  195. x := (*stringStruct)(a)
  196. return memhashFallback(x.str, h, uintptr(x.len))
  197. }
  198. const (
  199. // Constants for multiplication: four random odd 64-bit numbers.
  200. m1 = 16877499708836156737
  201. m2 = 2820277070424839065
  202. m3 = 9497967016996688599
  203. m4 = 15839092249703872147
  204. )
  205. var hashkey = [4]uintptr{1, 1, 1, 1}
  206. func memhashFallback(p unsafe.Pointer, seed, s uintptr) uintptr {
  207. h := uint64(seed + s*hashkey[0])
  208. tail:
  209. switch {
  210. case s == 0:
  211. case s < 4:
  212. h ^= uint64(*(*byte)(p))
  213. h ^= uint64(*(*byte)(add(p, s>>1))) << 8
  214. h ^= uint64(*(*byte)(add(p, s-1))) << 16
  215. h = rotl31(h*m1) * m2
  216. case s <= 8:
  217. h ^= uint64(readUnaligned32(p))
  218. h ^= uint64(readUnaligned32(add(p, s-4))) << 32
  219. h = rotl31(h*m1) * m2
  220. case s <= 16:
  221. h ^= readUnaligned64(p)
  222. h = rotl31(h*m1) * m2
  223. h ^= readUnaligned64(add(p, s-8))
  224. h = rotl31(h*m1) * m2
  225. case s <= 32:
  226. h ^= readUnaligned64(p)
  227. h = rotl31(h*m1) * m2
  228. h ^= readUnaligned64(add(p, 8))
  229. h = rotl31(h*m1) * m2
  230. h ^= readUnaligned64(add(p, s-16))
  231. h = rotl31(h*m1) * m2
  232. h ^= readUnaligned64(add(p, s-8))
  233. h = rotl31(h*m1) * m2
  234. default:
  235. v1 := h
  236. v2 := uint64(seed * hashkey[1])
  237. v3 := uint64(seed * hashkey[2])
  238. v4 := uint64(seed * hashkey[3])
  239. for s >= 32 {
  240. v1 ^= readUnaligned64(p)
  241. v1 = rotl31(v1*m1) * m2
  242. p = add(p, 8)
  243. v2 ^= readUnaligned64(p)
  244. v2 = rotl31(v2*m2) * m3
  245. p = add(p, 8)
  246. v3 ^= readUnaligned64(p)
  247. v3 = rotl31(v3*m3) * m4
  248. p = add(p, 8)
  249. v4 ^= readUnaligned64(p)
  250. v4 = rotl31(v4*m4) * m1
  251. p = add(p, 8)
  252. s -= 32
  253. }
  254. h = v1 ^ v2 ^ v3 ^ v4
  255. goto tail
  256. }
  257. h ^= h >> 29
  258. h *= m3
  259. h ^= h >> 32
  260. return uintptr(h)
  261. }
  262. func add(p unsafe.Pointer, x uintptr) unsafe.Pointer {
  263. return unsafe.Pointer(uintptr(p) + x)
  264. }
  265. func readUnaligned32(p unsafe.Pointer) uint32 {
  266. q := (*[4]byte)(p)
  267. return uint32(q[0]) | uint32(q[1])<<8 | uint32(q[2])<<16 | uint32(q[3])<<24
  268. }
  269. func rotl31(x uint64) uint64 {
  270. return (x << 31) | (x >> (64 - 31))
  271. }
  272. func readUnaligned64(p unsafe.Pointer) uint64 {
  273. q := (*[8]byte)(p)
  274. return uint64(q[0]) | uint64(q[1])<<8 | uint64(q[2])<<16 | uint64(q[3])<<24 | uint64(q[4])<<32 | uint64(q[5])<<40 | uint64(q[6])<<48 | uint64(q[7])<<56
  275. }