taldir

Directory service to resolve wallet mailboxes by messenger addresses
Log | Files | Refs | Submodules | README | LICENSE

varint.go (1493B)


      1 // Copyright 2017 The Go Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 package catmsg
      6 
      7 // This file implements varint encoding analogous to the one in encoding/binary.
      8 // We need a string version of this function, so we add that here and then add
      9 // the rest for consistency.
     10 
     11 import "errors"
     12 
     13 var (
     14 	errIllegalVarint  = errors.New("catmsg: illegal varint")
     15 	errVarintTooLarge = errors.New("catmsg: varint too large for uint64")
     16 )
     17 
     18 const maxVarintBytes = 10 // maximum length of a varint
     19 
     20 // encodeUint encodes x as a variable-sized integer into buf and returns the
     21 // number of bytes written. buf must be at least maxVarintBytes long
     22 func encodeUint(buf []byte, x uint64) (n int) {
     23 	for ; x > 127; n++ {
     24 		buf[n] = 0x80 | uint8(x&0x7F)
     25 		x >>= 7
     26 	}
     27 	buf[n] = uint8(x)
     28 	n++
     29 	return n
     30 }
     31 
     32 func decodeUintString(s string) (x uint64, size int, err error) {
     33 	i := 0
     34 	for shift := uint(0); shift < 64; shift += 7 {
     35 		if i >= len(s) {
     36 			return 0, i, errIllegalVarint
     37 		}
     38 		b := uint64(s[i])
     39 		i++
     40 		x |= (b & 0x7F) << shift
     41 		if b&0x80 == 0 {
     42 			return x, i, nil
     43 		}
     44 	}
     45 	return 0, i, errVarintTooLarge
     46 }
     47 
     48 func decodeUint(b []byte) (x uint64, size int, err error) {
     49 	i := 0
     50 	for shift := uint(0); shift < 64; shift += 7 {
     51 		if i >= len(b) {
     52 			return 0, i, errIllegalVarint
     53 		}
     54 		c := uint64(b[i])
     55 		i++
     56 		x |= (c & 0x7F) << shift
     57 		if c&0x80 == 0 {
     58 			return x, i, nil
     59 		}
     60 	}
     61 	return 0, i, errVarintTooLarge
     62 }