github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/internal/sortedkv/key.go (about)

     1  // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors.
     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  package sortedkv
    16  
    17  import (
    18  	"encoding/binary"
    19  	"strconv"
    20  
    21  	"github.com/zuoyebang/bitalosdb/internal/hash"
    22  	"github.com/zuoyebang/bitalosdb/internal/utils"
    23  )
    24  
    25  func MakeKey(key []byte) []byte {
    26  	slotId := uint16(hash.Crc32(key) % 1024)
    27  	keyLen := 2 + len(key)
    28  	newKey := make([]byte, keyLen)
    29  	binary.BigEndian.PutUint16(newKey[0:2], slotId)
    30  	copy(newKey[2:keyLen], key)
    31  	return newKey
    32  }
    33  
    34  func MakeKey2(key []byte, slotId uint16, version uint64) []byte {
    35  	keyLen := 10 + len(key)
    36  	newKey := make([]byte, keyLen)
    37  	binary.BigEndian.PutUint16(newKey[0:2], slotId)
    38  	binary.LittleEndian.PutUint64(newKey[2:10], version)
    39  	if key != nil {
    40  		copy(newKey[10:keyLen], key)
    41  	}
    42  	return newKey
    43  }
    44  
    45  func MakeSlotKey(key []byte, slotId uint16) []byte {
    46  	keyLen := 2 + len(key)
    47  	newKey := make([]byte, keyLen)
    48  	binary.BigEndian.PutUint16(newKey[0:2], slotId)
    49  	copy(newKey[2:keyLen], key)
    50  	return newKey
    51  }
    52  
    53  func MakeSortedKey(n int) []byte {
    54  	if n < 0 {
    55  		return []byte(sortedKeyPrefix)
    56  	} else {
    57  		return []byte(sortedKeyPrefix + strconv.Itoa(n))
    58  	}
    59  }
    60  
    61  func MakeSortedSlotKey(n int, slotId uint16) []byte {
    62  	if n < 0 {
    63  		return MakeSlotKey([]byte(sortedKeyPrefix), slotId)
    64  	} else {
    65  		return MakeSlotKey([]byte(sortedKeyPrefix+strconv.Itoa(n)), slotId)
    66  	}
    67  }
    68  
    69  func MakeSortedKeyForBitrie(n int) []byte {
    70  	if n < 0 {
    71  		return []byte(sortedKeyPrefix)
    72  	} else {
    73  		return []byte(sortedKeyPrefix + string(utils.FuncRandBytes(1)) + "_bitalosdb_" + string(utils.FuncRandBytes(64)) + strconv.Itoa(n))
    74  	}
    75  }