File tree 3 files changed +41
-5
lines changed
3 files changed +41
-5
lines changed Original file line number Diff line number Diff line change @@ -3,6 +3,12 @@ package main
3
3
var CNIPDataStart []uint32
4
4
var CNIPDataNum []uint
5
5
6
+ //data range by first byte
7
+ var CNIPDataRange [256 ]struct {
8
+ start int
9
+ end int
10
+ }
11
+
6
12
func initCNIPData () {
7
13
CNIPDataStart = []uint32 {
8
14
16777472 ,
@@ -9738,4 +9744,19 @@ func initCNIPData() {
9738
9744
512 ,
9739
9745
}
9740
9746
9747
+ n := len (CNIPDataStart )
9748
+ var curr uint32 = 0
9749
+ var preFirstByte uint32 = 0
9750
+ for i := 0 ; i < n ; i ++ {
9751
+ firstByte := CNIPDataStart [i ] >> 24
9752
+ if curr != firstByte {
9753
+ curr = firstByte
9754
+ if preFirstByte != 0 {
9755
+ CNIPDataRange [preFirstByte ].end = i - 1
9756
+ }
9757
+ CNIPDataRange [firstByte ].start = i
9758
+ preFirstByte = firstByte
9759
+ }
9760
+ }
9761
+ CNIPDataRange [preFirstByte ].end = n - 1
9741
9762
}
Original file line number Diff line number Diff line change 1
1
package main
2
2
3
- import (
4
- "sort"
5
- )
6
-
7
3
func ipShouldDirect (ip string ) (direct bool ) {
8
4
direct = false
9
5
defer func () {
@@ -22,7 +18,11 @@ func ipShouldDirect(ip string) (direct bool) {
22
18
if ipLong == 0 {
23
19
return true
24
20
}
25
- ipIndex := sort .Search (len (CNIPDataStart ), func (i int ) bool {
21
+ firstByte := ipLong >> 24
22
+ if CNIPDataRange [firstByte ].end == 0 {
23
+ return false
24
+ }
25
+ ipIndex := searchRange (CNIPDataRange [firstByte ].start , CNIPDataRange [firstByte ].end , func (i int ) bool {
26
26
return CNIPDataStart [i ] > ipLong
27
27
})
28
28
ipIndex --
Original file line number Diff line number Diff line change @@ -416,3 +416,18 @@ func ip2long(ipstr string) (uint32, error) {
416
416
}
417
417
return binary .BigEndian .Uint32 (ip ), nil
418
418
}
419
+
420
+ // search between [start, end]
421
+ func searchRange (start , end int , f func (int ) bool ) int {
422
+ i , j := start , end + 1
423
+ for i < j {
424
+ h := i + (j - i )/ 2 // avoid overflow when computing h
425
+ // i ≤ h < j
426
+ if ! f (h ) {
427
+ i = h + 1 // preserves f(i-1) == false
428
+ } else {
429
+ j = h // preserves f(j) == true
430
+ }
431
+ }
432
+ return i
433
+ }
You can’t perform that action at this time.
0 commit comments