forked from la5nta/wl2k-go
/
message_body.go
66 lines (54 loc) · 1.51 KB
/
message_body.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
62
63
64
65
66
// Copyright 2015 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
// Use of this source code is governed by the MIT-license that can be
// found in the LICENSE file.
package wl2k
import (
"bufio"
"bytes"
"github.com/paulrosania/go-charset/charset"
_ "github.com/paulrosania/go-charset/data"
)
// StringToBytes converts the body into a slice of bytes with the given charset encoding.
//
// CRLF line break is enforced.
// Line break are inserted if a line is longer than 1000 characters (including CRLF).
func StringToBody(str, encoding string) ([]byte, error) {
in := bufio.NewScanner(bytes.NewBufferString(str))
out := new(bytes.Buffer)
var err error
var line []byte
for in.Scan() {
line = in.Bytes()
for {
// Lines can not be longer that 1000 characters including CRLF.
n := min(len(line), 1000-2)
out.Write(line[:n])
out.WriteString("\r\n")
line = line[n:]
if len(line) == 0 {
break
}
}
}
translator, err := charset.TranslatorTo(encoding)
if err != nil {
return out.Bytes(), err
}
_, translated, err := translator.Translate(out.Bytes(), true)
return translated, err
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// BodyFromBytes translated the data based on the given charset encoding into a proper utf-8 string.
func BodyFromBytes(data []byte, encoding string) (string, error) {
translator, err := charset.TranslatorFrom(encoding)
if err != nil {
return string(data), err
}
_, utf8, err := translator.Translate(data, true)
return string(utf8), err
}