Go implementation of signed/unsigned LEB128. Encodes/decodes 8 byte integers.
Full documentation is available at pkg.go.dev.
Read from an io.Reader in to an int64 or uint64:
package main
import (
"bytes"
"fmt"
"github.com/jcalabro/leb128"
)
func unsigned() {
// Encodings whose value would not fit in 64 bits return leb128.ErrOverflow.
// An empty reader returns io.EOF; a truncated encoding (continuation bit
// set on the final byte read) returns io.ErrUnexpectedEOF.
buf := bytes.NewBuffer([]byte{128, 2})
num, err := leb128.DecodeU64(buf)
if err != nil {
panic(err)
}
fmt.Println(num) // 256
}
func signed() {
buf := bytes.NewBuffer([]byte{128, 126})
num, err := leb128.DecodeS64(buf)
if err != nil {
panic(err)
}
fmt.Println(num) // -256
}
func main() {
unsigned()
signed()
}Convert an int64 or uint64 to a []byte:
package main
import (
"fmt"
"github.com/jcalabro/leb128"
)
func unsigned() {
buf := leb128.EncodeU64(256)
fmt.Println(buf) // [128 2]
}
func signed() {
buf := leb128.EncodeS64(-256)
fmt.Println(buf) // [128 126]
}
func main() {
unsigned()
signed()
}