forked from tikv/pd
/
test_util.go
80 lines (74 loc) · 2.25 KB
/
test_util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"math"
"github.com/gogo/protobuf/proto"
"github.com/pingcap/kvproto/pkg/metapb"
)
// SplitRegions split a set of metapb.Region by the middle of regionKey
func SplitRegions(regions []*metapb.Region) []*metapb.Region {
results := make([]*metapb.Region, 0, len(regions)*2)
for _, region := range regions {
start, end := byte(0), byte(math.MaxUint8)
if len(region.StartKey) > 0 {
start = region.StartKey[0]
}
if len(region.EndKey) > 0 {
end = region.EndKey[0]
}
middle := []byte{start/2 + end/2}
left := proto.Clone(region).(*metapb.Region)
left.Id = region.Id + uint64(len(regions))
left.EndKey = middle
left.RegionEpoch.Version++
right := proto.Clone(region).(*metapb.Region)
right.Id = region.Id + uint64(len(regions)*2)
right.StartKey = middle
right.RegionEpoch.Version++
results = append(results, left, right)
}
return results
}
// MergeRegions merge a set of metapb.Region by regionKey
func MergeRegions(regions []*metapb.Region) []*metapb.Region {
results := make([]*metapb.Region, 0, len(regions)/2)
for i := 0; i < len(regions); i += 2 {
left := regions[i]
right := regions[i]
if i+1 < len(regions) {
right = regions[i+1]
}
region := &metapb.Region{
Id: left.Id + uint64(len(regions)),
StartKey: left.StartKey,
EndKey: right.EndKey,
}
if left.RegionEpoch.Version > right.RegionEpoch.Version {
region.RegionEpoch = left.RegionEpoch
} else {
region.RegionEpoch = right.RegionEpoch
}
region.RegionEpoch.Version++
results = append(results, region)
}
return results
}
// NewRegion create a metapb.Region
func NewRegion(start, end []byte) *metapb.Region {
return &metapb.Region{
StartKey: start,
EndKey: end,
RegionEpoch: &metapb.RegionEpoch{},
}
}