Debian Codegraph @

charset/iconv/iconv.go

raw symbols SCIP
1 // The iconv package provides an interface to the GNU iconv character set
2 // conversion library (see http://www.gnu.org/software/libiconv/).
3 // It automatically registers all the character sets with the charset package,
4 // so it is usually used simply for the side effects of importing it.
5 // Example:
6 // import (
7 // "go-charset.googlecode.com/hg/charset"
8 // _ "go-charset.googlecode.com/hg/charset/iconv"
9 // )
10 package iconv
11
12 /*
13 #cgo darwin LDFLAGS: -liconv
14 #include <stdlib.h>
15 #include <iconv.h>
16 #include <errno.h>
17
18 iconv_t iconv_open_error = (iconv_t)-1;
19 size_t iconv_error = (size_t)-1;
20
21 // From: https://github.com/djimenez/iconv-go/blob/master/converter.go
22 //
23 // As of Go 1.6 passing a pointer to Go pointer will lead to panic
24 // Therefore we use this wrapper function, to avoid passing **char directly from go
25 size_t call_iconv(iconv_t ctx, char *in, size_t *size_in, char *out, size_t *size_out) {
26 return iconv(ctx, &in, size_in, &out, size_out);
27 }
28 */
29 import "C"
30 import (
31 "errors"
32 "fmt"
33 "runtime"
34 "strings"
35 "syscall"
36 "unicode/utf8"
37 "unsafe"
38
39 "github.com/paulrosania/go-charset/charset"
40 )
41
42 type iconvTranslator struct {
43 cd C.iconv_t
44 invalid rune
45 scratch []byte
46 }
47
48 func canonicalChar(c rune) rune {
49 if c >= 'a' && c <= 'z' {
50 return c - 'a' + 'A'
51 }
52 return c
53 }
54
55 func canonicalName(s string) string {
56 return strings.Map(canonicalChar, s)
57 }
58
59 func init() {
60 charset.Register(iconvFactory{})
61 }
62
63 type iconvFactory struct {
64 }
65
66 func (iconvFactory) TranslatorFrom(name string) (charset.Translator, error) {
67 return Translator("UTF-8", name, utf8.RuneError)
68 }
69
70 func (iconvFactory) TranslatorTo(name string) (charset.Translator, error) {
71 // BUG This is wrong. The target character set may not be ASCII
72 // compatible. There's no easy solution to this other than
73 // removing the offending code point.
74 return Translator(name, "UTF-8", '?')
75 }
76
77 // Translator returns a Translator that translates between
78 // the named character sets. When an invalid multibyte
79 // character is found, the bytes in invalid are substituted instead.
80 func Translator(toCharset, fromCharset string, invalid rune) (charset.Translator, error) {
81 cto, cfrom := C.CString(toCharset), C.CString(fromCharset)
82 cd, err := C.iconv_open(cto, cfrom)
83
84 C.free(unsafe.Pointer(cfrom))
85 C.free(unsafe.Pointer(cto))
86
87 if cd == C.iconv_open_error {
88 if err == syscall.EINVAL {
89 return nil, errors.New("iconv: conversion not supported")
90 }
91 return nil, err
92 }
93 t := &iconvTranslator{cd: cd, invalid: invalid}
94 runtime.SetFinalizer(t, func(*iconvTranslator) {
95 C.iconv_close(cd)
96 })
97 return t, nil
98 }
99
100 func (iconvFactory) Names() []string {
101 all := aliases()
102 names := make([]string, 0, len(all))
103 for name, aliases := range all {
104 if aliases[0] == name {
105 names = append(names, name)
106 }
107 }
108 return names
109 }
110
111 func (iconvFactory) Info(name string) *charset.Charset {
112 name = strings.ToLower(name)
113 all := aliases()
114 a, ok := all[name]
115 if !ok {
116 return nil
117 }
118 return &charset.Charset{
119 Name: name,
120 Aliases: a,
121 }
122 }
123
124 func (p *iconvTranslator) Translate(data []byte, eof bool) (rn int, rd []byte, rerr error) {
125 n := 0
126 p.scratch = p.scratch[:0]
127 for len(data) > 0 {
128 p.scratch = ensureCap(p.scratch, len(p.scratch)+len(data)*utf8.UTFMax)
129 cData := (*C.char)(unsafe.Pointer(&data[:1][0]))
130 nData := C.size_t(len(data))
131
132 ns := len(p.scratch)
133 cScratch := (*C.char)(unsafe.Pointer(&p.scratch[ns : ns+1][0]))
134 nScratch := C.size_t(cap(p.scratch) - ns)
135 r, err := C.call_iconv(p.cd, cData, &nData, cScratch, &nScratch)
136
137 p.scratch = p.scratch[0 : cap(p.scratch)-int(nScratch)]
138 n += len(data) - int(nData)
139 data = data[len(data)-int(nData):]
140
141 if r != C.iconv_error || err == nil {
142 return n, p.scratch, nil
143 }
144 switch err := err.(syscall.Errno); err {
145 case C.EILSEQ:
146 // invalid multibyte sequence - skip one byte and continue
147 p.scratch = appendRune(p.scratch, p.invalid)
148 n++
149 data = data[1:]
150 case C.EINVAL:
151 // incomplete multibyte sequence
152 return n, p.scratch, nil
153 case C.E2BIG:
154 // output buffer not large enough; try again with larger buffer.
155 p.scratch = ensureCap(p.scratch, cap(p.scratch)+utf8.UTFMax)
156 default:
157 panic(fmt.Sprintf("unexpected error code: %v", err))
158 }
159 }
160 return n, p.scratch, nil
161 }
162
163 // ensureCap returns s with a capacity of at least n bytes.
164 // If cap(s) < n, then it returns a new copy of s with the
165 // required capacity.
166 func ensureCap(s []byte, n int) []byte {
167 if n <= cap(s) {
168 return s
169 }
170 // logic adapted from appendslice1 in runtime
171 m := cap(s)
172 if m == 0 {
173 m = n
174 } else {
175 for {
176 if m < 1024 {
177 m += m
178 } else {
179 m += m / 4
180 }
181 if m >= n {
182 break
183 }
184 }
185 }
186 t := make([]byte, len(s), m)
187 copy(t, s)
188 return t
189 }
190
191 func appendRune(buf []byte, r rune) []byte {
192 n := len(buf)
193 buf = ensureCap(buf, n+utf8.UTFMax)
194 nu := utf8.EncodeRune(buf[n:n+utf8.UTFMax], r)
195 return buf[0 : n+nu]
196 }