Files
opentimestamps/varn/varn.go
2025-04-11 13:31:02 +02:00

39 lines
1.3 KiB
Go

// Package varn implements variable-length encoding for unsigned integers and
// byte slices. It is used in the OpenTimestamps protocol to encode
// instructions and attestations. The encoding is similar to the one used in
// Protocol Buffers, but with a different format for the variable-length
// integers. The encoding is designed to be compact and efficient, while still
// being easy to decode. The package provides functions to read and write
// variable-length integers and byte slices, as well as a Buffer type for
// reading and writing data in a more convenient way. The package is not
// thread-safe and should not be used concurrently. It is intended for use in
// the OpenTimestamps protocol and is not a general-purpose encoding library.
package varn
// AppendVarUint appends a variable-length unsigned integer to the buffer
func AppendVarUint(buf []byte, value uint64) []byte {
if value == 0 {
buf = append(buf, 0)
} else {
for value != 0 {
b := byte(value & 0b01111111)
if value > 0b01111111 {
b |= 0b10000000
}
buf = append(buf, b)
if value <= 0b01111111 {
break
}
value >>= 7
}
}
return buf
}
func AppendVarBytes(buf []byte, value []byte) []byte {
buf = AppendVarUint(buf, uint64(len(value)))
buf = append(buf, value...)
return buf
}