2019-06-09 07:24:20 +00:00
|
|
|
package multiaddr
|
|
|
|
|
|
|
|
import (
|
2021-06-16 20:19:45 +00:00
|
|
|
"math"
|
2019-06-09 07:24:20 +00:00
|
|
|
|
2021-06-16 20:19:45 +00:00
|
|
|
"github.com/multiformats/go-varint"
|
|
|
|
)
|
2019-06-09 07:24:20 +00:00
|
|
|
|
|
|
|
// CodeToVarint converts an integer to a varint-encoded []byte
|
|
|
|
func CodeToVarint(num int) []byte {
|
2021-06-16 20:19:45 +00:00
|
|
|
if num < 0 || num > math.MaxInt32 {
|
|
|
|
panic("invalid code")
|
|
|
|
}
|
|
|
|
return varint.ToUvarint(uint64(num))
|
2019-06-09 07:24:20 +00:00
|
|
|
}
|
|
|
|
|
2021-06-16 20:19:45 +00:00
|
|
|
func ReadVarintCode(b []byte) (int, int, error) {
|
|
|
|
code, n, err := varint.FromUvarint(b)
|
2019-06-09 07:24:20 +00:00
|
|
|
if err != nil {
|
2021-06-16 20:19:45 +00:00
|
|
|
return 0, 0, err
|
2019-06-09 07:24:20 +00:00
|
|
|
}
|
2021-06-16 20:19:45 +00:00
|
|
|
if code > math.MaxInt32 {
|
|
|
|
// we only allow 32bit codes.
|
|
|
|
return 0, 0, varint.ErrOverflow
|
2019-06-09 07:24:20 +00:00
|
|
|
}
|
2021-06-16 20:19:45 +00:00
|
|
|
return int(code), n, err
|
2019-06-09 07:24:20 +00:00
|
|
|
}
|