// base64url provides base64url encoding/decoding functions
package base64

import (
	"encoding/base64"
	"strings"
)

// decodes base64url string to bytes
func DecodeURL(data string) ([]byte, error) {
	data = strings.Replace(data, "-", "+", -1)
	data = strings.Replace(data, "_", "/", -1)

	switch len(data) % 4 {
	case 0:
	case 2:
		data += "=="
	case 3:
		data += "="
	}

	return base64.StdEncoding.DecodeString(data)
}

// encodes given bytes to base64url string
func EncodeURL(data []byte) string {
	result := base64.StdEncoding.EncodeToString(data)
	result = strings.Replace(result, "+", "-", -1)
	result = strings.Replace(result, "/", "_", -1)
	result = strings.Replace(result, "=", "", -1)

	return result
}
