github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/gopkg.in/sourcemap.v1/base64vlq/base64_vlq.go (about)

     1  package base64vlq
     2  
     3  import (
     4  	"io"
     5  )
     6  
     7  const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
     8  
     9  const (
    10  	vlqBaseShift       = 5
    11  	vlqBase            = 1 << vlqBaseShift
    12  	vlqBaseMask        = vlqBase - 1
    13  	vlqSignBit         = 1
    14  	vlqContinuationBit = vlqBase
    15  )
    16  
    17  var decodeMap [256]byte
    18  
    19  func init() {
    20  	for i := 0; i < len(encodeStd); i++ {
    21  		decodeMap[encodeStd[i]] = byte(i)
    22  	}
    23  }
    24  
    25  func toVLQSigned(n int) int {
    26  	if n < 0 {
    27  		return -n<<1 + 1
    28  	}
    29  	return n << 1
    30  }
    31  
    32  func fromVLQSigned(n int) int {
    33  	isNeg := n&vlqSignBit != 0
    34  	n >>= 1
    35  	if isNeg {
    36  		return -n
    37  	}
    38  	return n
    39  }
    40  
    41  type Encoder struct {
    42  	w io.ByteWriter
    43  }
    44  
    45  func NewEncoder(w io.ByteWriter) *Encoder {
    46  	return &Encoder{
    47  		w: w,
    48  	}
    49  }
    50  
    51  func (enc Encoder) Encode(n int) error {
    52  	n = toVLQSigned(n)
    53  	for digit := vlqContinuationBit; digit&vlqContinuationBit != 0; {
    54  		digit = n & vlqBaseMask
    55  		n >>= vlqBaseShift
    56  		if n > 0 {
    57  			digit |= vlqContinuationBit
    58  		}
    59  
    60  		err := enc.w.WriteByte(encodeStd[digit])
    61  		if err != nil {
    62  			return err
    63  		}
    64  	}
    65  	return nil
    66  }
    67  
    68  type Decoder struct {
    69  	r io.ByteReader
    70  }
    71  
    72  func NewDecoder(r io.ByteReader) *Decoder {
    73  	return &Decoder{
    74  		r: r,
    75  	}
    76  }
    77  
    78  func (dec Decoder) Decode() (n int, err error) {
    79  	shift := uint(0)
    80  	for continuation := true; continuation; {
    81  		c, err := dec.r.ReadByte()
    82  		if err != nil {
    83  			return 0, err
    84  		}
    85  
    86  		c = decodeMap[c]
    87  		continuation = c&vlqContinuationBit != 0
    88  		n += int(c&vlqBaseMask) << shift
    89  		shift += vlqBaseShift
    90  	}
    91  	return fromVLQSigned(n), nil
    92  }