-
Notifications
You must be signed in to change notification settings - Fork 2
/
autodetect.go
61 lines (55 loc) · 1.36 KB
/
autodetect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package mbcs
import (
"bytes"
"unicode/utf8"
"golang.org/x/text/transform"
)
// NewAutoDecoder returns transform.Transformer that converts strings that are unknown to ANSI or UTF8 to UTF8.
func NewAutoDecoder(cp uintptr) transform.Transformer {
return AutoDecoder{CP: cp}
}
// AutoDecoder is an implementation of transform.Transformer that converts strings that are unknown to ANSI or UTF8 to UTF8.
type AutoDecoder struct {
CP uintptr
}
// Reset does nothing in AutoDecoder
func (f AutoDecoder) Reset() {}
// Transform converts a strings that are unknown to ANSI or UTF8 in src to a UTF8 string and stores it in dst.
func (f AutoDecoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
for len(src) > 0 {
// println("called Transform")
n := bytes.IndexByte(src, '\n')
var from []byte
if n < 0 {
n = len(src)
from = src
if !atEOF {
return nDst, nSrc, transform.ErrShortSrc
}
} else {
n++
from = src[:n]
}
var to string
if utf8.Valid(from) {
to = string(from)
} else {
var err error
to, err = ansiToUtf8(from, f.CP)
if err != nil {
return nDst, nSrc, err
}
}
if len(dst) < len(to) {
return nDst, nSrc, transform.ErrShortDst
}
for i, iEnd := 0, len(to); i < iEnd; i++ {
dst[i] = to[i]
}
nSrc += n
nDst += len(to)
src = src[n:]
dst = dst[len(to):]
}
return nDst, nSrc, nil
}