github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/store/prolly/message/varint.go (about)

     1  // Copyright 2022 Dolthub, 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  // 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 message
    16  
    17  import (
    18  	"encoding/binary"
    19  )
    20  
    21  func encodeVarints(ints []uint64, buf []byte) []byte {
    22  	return endcodeSignedDeltas(ints, buf)
    23  }
    24  
    25  func decodeVarints(buf []byte, ints []uint64) []uint64 {
    26  	return decodeSignedDeltas(buf, ints)
    27  }
    28  
    29  func maxEncodedSize(n int) int {
    30  	return (n + 1) * binary.MaxVarintLen64
    31  }
    32  
    33  func endcodeSignedDeltas(ints []uint64, buf []byte) []byte {
    34  	pos, prev := 0, int64(0)
    35  	for i := range ints {
    36  		curr := int64(ints[i])
    37  		delta := curr - prev
    38  		prev = curr
    39  
    40  		n := binary.PutVarint(buf[pos:], delta)
    41  		pos += n
    42  	}
    43  	return buf[:pos]
    44  }
    45  
    46  func decodeSignedDeltas(buf []byte, ints []uint64) []uint64 {
    47  	prev := int64(0)
    48  	for i := range ints {
    49  		delta, n := binary.Varint(buf)
    50  		buf = buf[n:]
    51  
    52  		curr := prev + delta
    53  		ints[i] = uint64(curr)
    54  		prev = curr
    55  	}
    56  	assertTrue(len(buf) == 0, "extra bytes after decoding varints")
    57  	return ints
    58  }