github.com/KinWaiYuen/client-go/v2@v2.5.4/kv/key.go (about) 1 // Copyright 2021 TiKV Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // NOTE: The code in this file is based on code from the 16 // TiDB project, licensed under the Apache License v 2.0 17 // 18 // https://github.com/pingcap/tidb/tree/cc5e161ac06827589c4966674597c137cc9e809c/store/tikv/kv/key.go 19 // 20 21 // Copyright 2021 PingCAP, Inc. 22 // 23 // Licensed under the Apache License, Version 2.0 (the "License"); 24 // you may not use this file except in compliance with the License. 25 // You may obtain a copy of the License at 26 // 27 // http://www.apache.org/licenses/LICENSE-2.0 28 // 29 // Unless required by applicable law or agreed to in writing, software 30 // distributed under the License is distributed on an "AS IS" BASIS, 31 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 32 // See the License for the specific language governing permissions and 33 // limitations under the License. 34 35 package kv 36 37 import ( 38 "bytes" 39 "encoding/hex" 40 ) 41 42 // NextKey returns the next key in byte-order. 43 func NextKey(k []byte) []byte { 44 // add 0x0 to the end of key 45 buf := make([]byte, len(k)+1) 46 copy(buf, k) 47 return buf 48 } 49 50 // PrefixNextKey returns the next prefix key. 51 // 52 // Assume there are keys like: 53 // 54 // rowkey1 55 // rowkey1_column1 56 // rowkey1_column2 57 // rowKey2 58 // 59 // If we seek 'rowkey1' NextKey, we will get 'rowkey1_column1'. 60 // If we seek 'rowkey1' PrefixNextKey, we will get 'rowkey2'. 61 func PrefixNextKey(k []byte) []byte { 62 buf := make([]byte, len(k)) 63 copy(buf, k) 64 var i int 65 for i = len(k) - 1; i >= 0; i-- { 66 buf[i]++ 67 if buf[i] != 0 { 68 break 69 } 70 } 71 if i == -1 { 72 // Unlike TiDB, for the specific key 0xFF 73 // we return empty slice instead of {0xFF, 0x0} 74 buf = make([]byte, 0) 75 } 76 return buf 77 } 78 79 // CmpKey returns the comparison result of two key. 80 // The result will be 0 if a==b, -1 if a < b, and +1 if a > b. 81 func CmpKey(k, another []byte) int { 82 return bytes.Compare(k, another) 83 } 84 85 // StrKey returns string for key. 86 func StrKey(k []byte) string { 87 return hex.EncodeToString(k) 88 } 89 90 // KeyRange represents a range where StartKey <= key < EndKey. 91 type KeyRange struct { 92 StartKey []byte 93 EndKey []byte 94 }