varint.go 1006 Bytes
Newer Older
1 2
package cid

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

gammazero's avatar
gammazero committed
7
// Version of varint function that works with a string rather than
8 9 10 11 12 13 14
// []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
Rod Vagg's avatar
Rod Vagg committed
15
// number of bytes read (> 0). If an error occurred, then 0 is
gammazero's avatar
gammazero committed
16 17
// returned for both the value and the number of bytes read, and an
// error is returned.
Steven Allen's avatar
Steven Allen committed
18
func uvarint(buf string) (uint64, int, error) {
19 20
	var x uint64
	var s uint
gammazero's avatar
gammazero committed
21
	// we have a binary string so we can't use a range loop
22 23 24 25
	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
26
				return 0, 0, varint.ErrOverflow
gammazero's avatar
gammazero committed
27 28
			}
			if b == 0 && i > 0 {
Steven Allen's avatar
Steven Allen committed
29
				return 0, 0, varint.ErrNotMinimal
30
			}
Steven Allen's avatar
Steven Allen committed
31
			return x | uint64(b)<<s, i + 1, nil
32 33 34 35
		}
		x |= uint64(b&0x7f) << s
		s += 7
	}
Steven Allen's avatar
Steven Allen committed
36
	return 0, 0, varint.ErrUnderflow
37
}