You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.4 KiB

  1. /*
  2. Wraps the iconv API present on most systems, which allows for conversion
  3. of bytes from one encoding to another. This package additionally provides
  4. some convenient interface implementations like a Reader and Writer.
  5. */
  6. package iconv
  7. // All in one Convert method, rather than requiring the construction of an iconv.Converter
  8. func Convert(input []byte, output []byte, fromEncoding string, toEncoding string) (bytesRead int, bytesWritten int, err error) {
  9. // create a temporary converter
  10. converter, err := NewConverter(fromEncoding, toEncoding)
  11. if err == nil {
  12. // call converter's Convert
  13. bytesRead, bytesWritten, err = converter.Convert(input, output)
  14. if err == nil {
  15. var shiftBytesWritten int
  16. // call Convert with a nil input to generate any end shift sequences
  17. _, shiftBytesWritten, err = converter.Convert(nil, output[bytesWritten:])
  18. // add shift bytes to total bytes
  19. bytesWritten += shiftBytesWritten
  20. }
  21. // close the converter
  22. converter.Close()
  23. }
  24. return
  25. }
  26. // All in one ConvertString method, rather than requiring the construction of an iconv.Converter
  27. func ConvertString(input string, fromEncoding string, toEncoding string) (output string, err error) {
  28. // create a temporary converter
  29. converter, err := NewConverter(fromEncoding, toEncoding)
  30. if err == nil {
  31. // convert the string
  32. output, err = converter.ConvertString(input)
  33. // close the converter
  34. converter.Close()
  35. }
  36. return
  37. }