github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/iconv/iconv.go (about) 1 package iconv 2 3 func Convert(input []byte, output []byte, fromEncoding string, toEncoding string) (bytesRead int, bytesWritten int, err error) { 4 // create a temporary converter 5 converter, err := NewConverter(fromEncoding, toEncoding) 6 if err == nil { 7 // call converter's Convert 8 bytesRead, bytesWritten, err = converter.Convert(input, output) 9 10 if err == nil { 11 var shiftBytesWritten int 12 // call Convert with a nil input to generate any end shift sequences 13 _, shiftBytesWritten, err = converter.Convert(nil, output[bytesWritten:]) 14 // add shift bytes to total bytes 15 bytesWritten += shiftBytesWritten 16 } 17 // close the converter 18 _ = converter.Close() 19 } 20 return 21 } 22 23 // ConvertString All in one ConvertString method, rather than requiring the construction of an iconv.Converter 24 func ConvertString(input string, fromEncoding string, toEncoding string) (output string, err error) { 25 // create a temporary converter 26 converter, err := NewConverter(fromEncoding, toEncoding) 27 if err == nil { 28 // convert the string 29 output, err = converter.ConvertString(input) 30 // close the converter 31 _ = converter.Close() 32 } 33 return 34 } 35 36 func GB2312ToUTF8String(in string) (string, error) { 37 return ConvertString(in, "GB2312", "UTF-8") 38 } 39 40 func GB2312ToUTF8(in []byte) ([]byte, error) { 41 output := make([]byte, len(in)*2) 42 _, outputLen, err := Convert(in, output, "GB2312", "UTF-8") 43 if err != nil { 44 return nil, err 45 } 46 return output[0:outputLen], nil 47 } 48 49 func GBKToUTF8(in []byte) ([]byte, error) { 50 output := make([]byte, len(in)*2) 51 _, outputLen, err := Convert(in, output, "GBK", "UTF-8") 52 if err != nil { 53 return nil, err 54 } 55 return output[0:outputLen], nil 56 }