varint.go 1.08 KB
Newer Older
1 2
package cid

Steven Allen's avatar
Steven Allen committed
3 4 5 6
import (
	"github.com/multiformats/go-varint"
)

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Version of varint function that work with a string rather than
// []byte to avoid unnecessary allocation

// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license as given at https://golang.org/LICENSE

// uvarint decodes a uint64 from buf and returns that value and the
// number of characters read (> 0). If an error occurred, the value is 0
// and the number of bytes n is <= 0 meaning:
//
// 	n == 0: buf too small
// 	n  < 0: value larger than 64 bits (overflow)
// 	        and -n is the number of bytes read
//
Steven Allen's avatar
Steven Allen committed
22
func uvarint(buf string) (uint64, int, error) {
23 24 25 26 27 28 29
	var x uint64
	var s uint
	// we have a binary string so we can't use a range loope
	for i := 0; i < len(buf); i++ {
		b := buf[i]
		if b < 0x80 {
			if i > 9 || i == 9 && b > 1 {
Steven Allen's avatar
Steven Allen committed
30 31 32
				return 0, 0, varint.ErrOverflow
			} else if b == 0 && i > 0 {
				return 0, 0, varint.ErrNotMinimal
33
			}
Steven Allen's avatar
Steven Allen committed
34
			return x | uint64(b)<<s, i + 1, nil
35 36 37 38
		}
		x |= uint64(b&0x7f) << s
		s += 7
	}
Steven Allen's avatar
Steven Allen committed
39
	return 0, 0, varint.ErrUnderflow
40
}