-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutfconv.go
More file actions
39 lines (36 loc) · 822 Bytes
/
utfconv.go
File metadata and controls
39 lines (36 loc) · 822 Bytes
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
package utfconv
import (
"unicode/utf16"
"unicode/utf8"
"encoding/binary"
)
const (
replacementChar = '\uFFFD'
)
func Read(charset string, data []byte) string {
switch charset {
case "utf8":
var runes []rune
for i := 0; i < len(data); {
r,size := utf8.DecodeRune(data[i:])
if r != utf8.RuneError {
runes = append(runes, r)
i += size
}
}
return string(runes)
case "utf16le":
uint16s := make([]uint16, len(data)/2)
for i := 0; i < len(uint16s); i++ {
uint16s[i] = binary.LittleEndian.Uint16(data[i*2:])
}
return string(utf16.Decode(uint16s))
case "utf16be":
uint16s := make([]uint16, len(data)/2)
for i := 0; i < len(uint16s); i++ {
uint16s[i] = binary.BigEndian.Uint16(data[i*2:])
}
return string(utf16.Decode(uint16s))
}
return string([]rune{replacementChar})
}