github.com/vescale/zgraph@v0.0.0-20230410094002-959c02d50f95/storage/mvcc/codec.go (about)

     1  // Copyright 2022 zGraph Authors. All rights reserved.
     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 mvcc
    16  
    17  import (
    18  	"github.com/pingcap/errors"
    19  	"github.com/vescale/zgraph/codec"
    20  	"github.com/vescale/zgraph/storage/kv"
    21  )
    22  
    23  var (
    24  	// ErrInvalidEncodedKey describes parsing an invalid format of EncodedKey.
    25  	ErrInvalidEncodedKey = errors.New("invalid encoded key")
    26  )
    27  
    28  // LockKey returns the encoded lock key of specified raw key.
    29  func LockKey(key kv.Key) Key {
    30  	return Encode(key, LockVer)
    31  }
    32  
    33  // Encode encodes a user defined key with timestamp.
    34  func Encode(key kv.Key, ver kv.Version) Key {
    35  	return codec.EncodeUintDesc(codec.EncodeBytes(nil, key), uint64(ver))
    36  }
    37  
    38  // Decode parses the origin key and version of an encoded key.
    39  // Will return the original key if the encoded key is a meta key.
    40  func Decode(encodedKey []byte) (kv.Key, kv.Version, error) {
    41  	// Skip DataPrefix
    42  	remainBytes, key, err := codec.DecodeBytes(encodedKey, nil)
    43  	if err != nil {
    44  		// should never happen
    45  		return nil, 0, err
    46  	}
    47  	// if it's meta key
    48  	if len(remainBytes) == 0 {
    49  		return key, 0, nil
    50  	}
    51  	var ver uint64
    52  	remainBytes, ver, err = codec.DecodeUintDesc(remainBytes)
    53  	if err != nil {
    54  		// should never happen
    55  		return nil, 0, err
    56  	}
    57  	if len(remainBytes) != 0 {
    58  		return nil, 0, errors.Trace(ErrInvalidEncodedKey)
    59  	}
    60  	return key, kv.Version(ver), nil
    61  }