package base62

// FormatInt encodes an integer num to base62 using the encoding enc.
func (enc *Encoding) FormatInt(num int64) []byte {
	dst := make([]byte, 0)
	return enc.AppendUint(dst, uint64(num))
}

// FormatUint encodes an unsigned integer num to base62 using the encoding enc.
func (enc *Encoding) FormatUint(num uint64) []byte {
	dst := make([]byte, 0)
	return enc.AppendUint(dst, num)
}

// AppendInt appends the base62 representation of the integer num,
// as generated by FormatInt, to dst and returns the extended buffer.
func (enc *Encoding) AppendInt(dst []byte, num int64) []byte {
	return enc.AppendUint(dst, uint64(num))
}

// AppendUint appends the base62 representation of the unsigned integer num,
// as generated by FormatUint, to dst and returns the extended buffer.
func (enc *Encoding) AppendUint(dst []byte, num uint64) []byte {
	if num == 0 {
		dst = append(dst, enc.encode[0])
		return dst
	}

	var buf [11]byte
	var i = 11
	for num > 0 {
		r := num % base
		num /= base
		i--
		buf[i] = enc.encode[r]
	}
	dst = append(dst, buf[i:]...)
	return dst
}

// ParseInt returns an integer from its base62 representation.
//
// If src contains invalid base62 data, it returns 0 and CorruptInputError.
func (enc *Encoding) ParseInt(src []byte) (int64, error) {
	num, err := enc.ParseUint(src)
	if err != nil {
		return 0, err
	}
	return int64(num), nil
}

// ParseUint returns an unsigned integer from its base62 representation.
//
// If src contains invalid base62 data, it returns 0 and CorruptInputError.
func (enc *Encoding) ParseUint(src []byte) (uint64, error) {
	var num uint64
	for i, c := range src {
		x := enc.decodeMap[c]
		if x == 0xFF {
			return 0, CorruptInputError(i)
		}
		num = num*base + uint64(x)
	}
	return num, nil
}
