sync gf master

This commit is contained in:
jroam
2019-07-03 10:02:17 +08:00
parent adc3201dcf
commit e03fd80fd4
42 changed files with 214 additions and 120 deletions

View File

@ -4,20 +4,36 @@
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package gbase64 provides useful API for BASE64 encoding/decoding algorithms.
// Package gbase64 provides useful API for BASE64 encoding/decoding algorithm.
package gbase64
import (
"encoding/base64"
)
// base64 encode
func Encode(str string) string {
return base64.StdEncoding.EncodeToString([]byte(str))
// Encode encodes bytes with BASE64 algorithm.
func Encode(src []byte) []byte {
dst := make([]byte, base64.StdEncoding.EncodedLen(len(src)))
base64.StdEncoding.Encode(dst, src)
return dst
}
// base64 decode
func Decode(str string) (string, error) {
s, e := base64.StdEncoding.DecodeString(str)
return string(s), e
// Decode decodes bytes with BASE64 algorithm.
func Decode(dst []byte) ([]byte, error) {
src := make([]byte, base64.StdEncoding.DecodedLen(len(dst)))
n, err := base64.StdEncoding.Decode(src, dst)
if err != nil {
return nil, err
}
return src[:n], nil
}
// EncodeString encodes bytes with BASE64 algorithm.
func EncodeString(src []byte) string {
return string(Encode(src))
}
// DecodeString decodes string with BASE64 algorithm.
func DecodeString(str string) ([]byte, error) {
return Decode([]byte(str))
}

View File

@ -6,9 +6,10 @@
package gbase64_test
import (
"testing"
"github.com/gogf/gf/g/encoding/gbase64"
"github.com/gogf/gf/g/test/gtest"
"testing"
)
type testpair struct {
@ -42,10 +43,17 @@ var pairs = []testpair{
}
func TestBase64(t *testing.T) {
for k := range pairs {
gtest.Assert(gbase64.Encode(pairs[k].decoded), pairs[k].encoded)
gtest.Case(t, func() {
for k := range pairs {
// []byte
gtest.Assert(gbase64.Encode([]byte(pairs[k].decoded)), []byte(pairs[k].encoded))
e1, _ := gbase64.Decode([]byte(pairs[k].encoded))
gtest.Assert(e1, []byte(pairs[k].decoded))
e, _ := gbase64.Decode(pairs[k].encoded)
gtest.Assert(e, pairs[k].decoded)
}
// string
gtest.Assert(gbase64.EncodeString([]byte(pairs[k].decoded)), pairs[k].encoded)
e2, _ := gbase64.DecodeString(pairs[k].encoded)
gtest.Assert(e2, []byte(pairs[k].decoded))
}
})
}