diff --git a/convertor/convertor.go b/convertor/convertor.go index 2a46929..e9e0b6f 100644 --- a/convertor/convertor.go +++ b/convertor/convertor.go @@ -11,12 +11,15 @@ import ( "encoding/json" "errors" "fmt" + "io" "math" "reflect" "strconv" "strings" "github.com/duke-git/lancet/v2/structs" + "golang.org/x/text/encoding/simplifiedchinese" + "golang.org/x/text/transform" ) // ToBool convert string to boolean. @@ -375,3 +378,19 @@ func ToInterface(v reflect.Value) (value interface{}, ok bool) { return nil, false } } + +// Utf8ToGbk convert utf8 encoding to GBK encoding. +// Play: todo +func Utf8ToGbk(bs []byte) ([]byte, error) { + r := transform.NewReader(bytes.NewReader(bs), simplifiedchinese.GBK.NewEncoder()) + b, err := io.ReadAll(r) + return b, err +} + +// GbkToUtf8 convert GBK encoding to utf8 encoding. +// Play: todo +func GbkToUtf8(bs []byte) ([]byte, error) { + r := transform.NewReader(bytes.NewReader(bs), simplifiedchinese.GBK.NewDecoder()) + b, err := io.ReadAll(r) + return b, err +} diff --git a/convertor/convertor_example_test.go b/convertor/convertor_example_test.go index 6990b2c..297fe47 100644 --- a/convertor/convertor_example_test.go +++ b/convertor/convertor_example_test.go @@ -4,6 +4,9 @@ import ( "fmt" "reflect" "strconv" + "unicode/utf8" + + "github.com/duke-git/lancet/v2/validator" ) func ExampleToBool() { @@ -364,3 +367,27 @@ func ExampleToInterface() { // abc // true } + +func ExampleUtf8ToGbk() { + utf8Data := []byte("hello") + gbkData, _ := Utf8ToGbk(utf8Data) + + fmt.Println(utf8.Valid(utf8Data)) + fmt.Println(validator.IsGBK(gbkData)) + + // Output: + // true + // true +} + +func ExampleGbkToUtf8() { + gbkData, _ := Utf8ToGbk([]byte("hello")) + utf8Data, _ := GbkToUtf8(gbkData) + + fmt.Println(utf8.Valid(utf8Data)) + fmt.Println(string(utf8Data)) + + // Output: + // true + // hello +} diff --git a/convertor/convertor_test.go b/convertor/convertor_test.go index 0f97b31..dada174 100644 --- a/convertor/convertor_test.go +++ b/convertor/convertor_test.go @@ -5,9 +5,11 @@ import ( "reflect" "strconv" "testing" + "unicode/utf8" "github.com/duke-git/lancet/v2/internal" "github.com/duke-git/lancet/v2/slice" + "github.com/duke-git/lancet/v2/validator" ) func TestToChar(t *testing.T) { @@ -396,3 +398,25 @@ func TestToInterface(t *testing.T) { assert.EqualValues(nil, nilVal) assert.Equal(false, ok) } + +func TestUtf8ToGbk(t *testing.T) { + assert := internal.NewAssert(t, "TestUtf8ToGbk") + + utf8Data := []byte("hello") + gbkData, err := Utf8ToGbk(utf8Data) + + assert.Equal(true, utf8.Valid(utf8Data)) + assert.Equal(true, validator.IsGBK(gbkData)) + assert.IsNil(err) +} + +func TestGbkToUtf8(t *testing.T) { + assert := internal.NewAssert(t, "TestGbkToUtf8") + + gbkData, err := Utf8ToGbk([]byte("hello")) + utf8Data, err := GbkToUtf8(gbkData) + + assert.IsNil(err) + assert.Equal(true, utf8.Valid(utf8Data)) + assert.Equal("hello", string(utf8Data)) +}