2011-01-29 14:31:00 +08:00
|
|
|
/*
|
|
|
|
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.
|
|
|
|
*/
|
2011-01-15 07:34:30 +08:00
|
|
|
package iconv
|
|
|
|
|
2011-01-17 03:40:30 +08:00
|
|
|
/*
|
|
|
|
#include <errno.h>
|
|
|
|
*/
|
2011-01-15 07:34:30 +08:00
|
|
|
import "C"
|
2011-01-29 14:31:00 +08:00
|
|
|
import "os"
|
2011-01-15 07:34:30 +08:00
|
|
|
|
2011-01-29 14:31:00 +08:00
|
|
|
// Alias os.Error for convenience
|
2011-01-15 07:34:30 +08:00
|
|
|
type Error os.Error
|
|
|
|
|
2011-01-29 14:31:00 +08:00
|
|
|
// Error codes returned from iconv functions
|
2011-01-15 07:34:30 +08:00
|
|
|
var (
|
|
|
|
E2BIG Error = os.Errno(int(C.E2BIG))
|
2011-01-29 14:31:00 +08:00
|
|
|
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))
|
2011-01-15 07:34:30 +08:00
|
|
|
)
|
|
|
|
|
2011-01-29 14:31:00 +08:00
|
|
|
// All in one Convert method, rather than requiring the construction of an iconv.Converter
|
2011-01-15 17:06:50 +08:00
|
|
|
func Convert(input []byte, output []byte, fromEncoding string, toEncoding string) (bytesRead int, bytesWritten int, err Error) {
|
2011-01-29 14:31:00 +08:00
|
|
|
// create a temporary converter
|
2011-01-15 07:34:30 +08:00
|
|
|
converter, err := NewConverter(fromEncoding, toEncoding)
|
|
|
|
|
|
|
|
if err == nil {
|
2011-01-29 14:31:00 +08:00
|
|
|
// call converter's Convert
|
2011-01-15 07:34:30 +08:00
|
|
|
bytesRead, bytesWritten, err = converter.Convert(input, output)
|
|
|
|
|
2011-01-29 14:31:00 +08:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2011-01-15 07:34:30 +08:00
|
|
|
// close the converter
|
|
|
|
converter.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2011-01-29 14:31:00 +08:00
|
|
|
// All in one ConvertString method, rather than requiring the construction of an iconv.Converter
|
2011-01-15 17:06:50 +08:00
|
|
|
func ConvertString(input string, fromEncoding string, toEncoding string) (output string, err Error) {
|
2011-01-29 14:31:00 +08:00
|
|
|
// create a temporary converter
|
2011-01-15 07:34:30 +08:00
|
|
|
converter, err := NewConverter(fromEncoding, toEncoding)
|
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
// convert the string
|
|
|
|
output, err = converter.ConvertString(input)
|
|
|
|
|
|
|
|
// close the converter
|
|
|
|
converter.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|