2016-10-28 12:05:01 -05:00
|
|
|
package base64vlq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
|
|
|
|
|
|
|
const (
|
|
|
|
vlqBaseShift = 5
|
|
|
|
vlqBase = 1 << vlqBaseShift
|
|
|
|
vlqBaseMask = vlqBase - 1
|
|
|
|
vlqSignBit = 1
|
|
|
|
vlqContinuationBit = vlqBase
|
|
|
|
)
|
|
|
|
|
2017-02-16 06:21:11 -06:00
|
|
|
var decodeMap [256]byte
|
2016-10-28 12:05:01 -05:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
for i := 0; i < len(encodeStd); i++ {
|
2017-02-16 06:21:11 -06:00
|
|
|
decodeMap[encodeStd[i]] = byte(i)
|
2016-10-28 12:05:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func toVLQSigned(n int) int {
|
|
|
|
if n < 0 {
|
|
|
|
return -n<<1 + 1
|
|
|
|
}
|
2017-02-16 06:21:11 -06:00
|
|
|
return n << 1
|
2016-10-28 12:05:01 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func fromVLQSigned(n int) int {
|
|
|
|
isNeg := n&vlqSignBit != 0
|
|
|
|
n >>= 1
|
|
|
|
if isNeg {
|
|
|
|
return -n
|
|
|
|
}
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
|
|
|
|
type Encoder struct {
|
|
|
|
w io.ByteWriter
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewEncoder(w io.ByteWriter) *Encoder {
|
|
|
|
return &Encoder{
|
|
|
|
w: w,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-16 06:21:11 -06:00
|
|
|
func (enc Encoder) Encode(n int) error {
|
2016-10-28 12:05:01 -05:00
|
|
|
n = toVLQSigned(n)
|
|
|
|
for digit := vlqContinuationBit; digit&vlqContinuationBit != 0; {
|
|
|
|
digit = n & vlqBaseMask
|
|
|
|
n >>= vlqBaseShift
|
|
|
|
if n > 0 {
|
|
|
|
digit |= vlqContinuationBit
|
|
|
|
}
|
2017-02-16 06:21:11 -06:00
|
|
|
|
2016-10-28 12:05:01 -05:00
|
|
|
err := enc.w.WriteByte(encodeStd[digit])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type Decoder struct {
|
|
|
|
r io.ByteReader
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDecoder(r io.ByteReader) *Decoder {
|
|
|
|
return &Decoder{
|
|
|
|
r: r,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-16 06:21:11 -06:00
|
|
|
func (dec Decoder) Decode() (n int, err error) {
|
2016-10-28 12:05:01 -05:00
|
|
|
shift := uint(0)
|
|
|
|
for continuation := true; continuation; {
|
|
|
|
c, err := dec.r.ReadByte()
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2017-02-16 06:21:11 -06:00
|
|
|
c = decodeMap[c]
|
|
|
|
continuation = c&vlqContinuationBit != 0
|
|
|
|
n += int(c&vlqBaseMask) << shift
|
2016-10-28 12:05:01 -05:00
|
|
|
shift += vlqBaseShift
|
|
|
|
}
|
|
|
|
return fromVLQSigned(n), nil
|
|
|
|
}
|