`
bishen
  • 浏览: 11672 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

iconv.go,GO编码转换

阅读更多
/*
Wraps the iconv API present on most systems, which allows for conversion
of bytes from one encoding to another. This package additionally provides
some convenient interface implementations like a Reader and Writer.
*/
package iconv

/*
#include <errno.h>
*/
import "C"
import "os"

// Alias os.Error for convenience
type Error os.Error

// Error codes returned from iconv functions
var (
	E2BIG Error = os.Errno(int(C.E2BIG))
	EBADF Error = os.Errno(int(C.EBADF))
	EINVAL Error = os.Errno(int(C.EINVAL))
	EILSEQ Error = os.Errno(int(C.EILSEQ))
	ENOMEM Error = os.Errno(int(C.ENOMEM))
)

// All in one Convert method, rather than requiring the construction of an iconv.Converter
func Convert(input []byte, output []byte, fromEncoding string, toEncoding string) (bytesRead int, bytesWritten int, err Error) {
	// create a temporary converter
	converter, err := NewConverter(fromEncoding, toEncoding)

	if err == nil {
		// call converter's Convert
		bytesRead, bytesWritten, err = converter.Convert(input, output)

		if err == nil {
			var shiftBytesWritten int

			// call Convert with a nil input to generate any end shift sequences
			_, shiftBytesWritten, err = converter.Convert(nil, output[bytesWritten:])

			// add shift bytes to total bytes
			bytesWritten += shiftBytesWritten
		}

		// close the converter
		converter.Close()
	}

	return
}

// All in one ConvertString method, rather than requiring the construction of an iconv.Converter
func ConvertString(input string, fromEncoding string, toEncoding string) (output string, err Error) {
	// create a temporary converter
	converter, err := NewConverter(fromEncoding, toEncoding)

	if err == nil {
		// convert the string
		output, err = converter.ConvertString(input)

		// close the converter
		converter.Close()
	}

	return
}
分享到:
评论
1 楼 ysw1983 2011-04-14  
博主,请问你的NewConverter方法是哪来的呀

相关推荐

Global site tag (gtag.js) - Google Analytics