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.

50 lines
922 B

10 years ago
  1. package mahonia
  2. import "unicode/utf8"
  3. // Translate enables a Decoder to implement go-charset's Translator interface.
  4. func (d Decoder) Translate(data []byte, eof bool) (n int, cdata []byte, err error) {
  5. cdata = make([]byte, len(data)+1)
  6. destPos := 0
  7. for n < len(data) {
  8. rune, size, status := d(data[n:])
  9. switch status {
  10. case STATE_ONLY:
  11. n += size
  12. continue
  13. case NO_ROOM:
  14. if !eof {
  15. return n, cdata[:destPos], nil
  16. }
  17. rune = 0xfffd
  18. n = len(data)
  19. default:
  20. n += size
  21. }
  22. if rune < 128 {
  23. if destPos >= len(cdata) {
  24. cdata = doubleLength(cdata)
  25. }
  26. cdata[destPos] = byte(rune)
  27. destPos++
  28. } else {
  29. if destPos+utf8.RuneLen(rune) > len(cdata) {
  30. cdata = doubleLength(cdata)
  31. }
  32. destPos += utf8.EncodeRune(cdata[destPos:], rune)
  33. }
  34. }
  35. return n, cdata[:destPos], nil
  36. }
  37. func doubleLength(b []byte) []byte {
  38. b2 := make([]byte, 2*len(b))
  39. copy(b2, b)
  40. return b2
  41. }