github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/kv/key.go (about) 1 // Copyright 2015 PingCAP, Inc. 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package kv 15 16 import "bytes" 17 18 // Key represents high-level Key type. 19 type Key []byte 20 21 // Next returns the next key in byte-order. 22 func (k Key) Next() Key { 23 // add 0x0 to the end of key 24 buf := make([]byte, len([]byte(k))+1) 25 copy(buf, []byte(k)) 26 return buf 27 } 28 29 // PrefixNext returns the next prefix key. 30 // 31 // Assume there are keys like: 32 // 33 // rowkey1 34 // rowkey1_column1 35 // rowkey1_column2 36 // rowKey2 37 // 38 // If we seek 'rowkey1' Next, we will get 'rowkey1_colum1'. 39 // If we seek 'rowkey1' PrefixNext, we will get 'rowkey2'. 40 func (k Key) PrefixNext() Key { 41 buf := make([]byte, len([]byte(k))) 42 copy(buf, []byte(k)) 43 var i int 44 for i = len(k) - 1; i >= 0; i-- { 45 buf[i]++ 46 if buf[i] != 0 { 47 break 48 } 49 } 50 if i == -1 { 51 copy(buf, k) 52 buf = append(buf, 0) 53 } 54 return buf 55 } 56 57 // Cmp returns the comparison result of two key. 58 // The result will be 0 if a==b, -1 if a < b, and +1 if a > b. 59 func (k Key) Cmp(another Key) int { 60 return bytes.Compare(k, another) 61 } 62 63 // HasPrefix tests whether the Key begins with prefix. 64 func (k Key) HasPrefix(prefix Key) bool { 65 return bytes.HasPrefix(k, prefix) 66 } 67 68 // Clone returns a copy of the Key. 69 func (k Key) Clone() Key { 70 return append([]byte(nil), k...) 71 } 72 73 // EncodedKey represents encoded key in low-level storage engine. 74 type EncodedKey []byte 75 76 // Cmp returns the comparison result of two key. 77 // The result will be 0 if a==b, -1 if a < b, and +1 if a > b. 78 func (k EncodedKey) Cmp(another EncodedKey) int { 79 return bytes.Compare(k, another) 80 } 81 82 // Next returns the next key in byte-order. 83 func (k EncodedKey) Next() EncodedKey { 84 return EncodedKey(bytes.Join([][]byte{k, Key{0}}, nil)) 85 }