-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrune_clozer.go
65 lines (60 loc) · 1.25 KB
/
rune_clozer.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
package main
import (
"bytes"
"fmt"
"io"
)
type runeClozer struct{}
func (tc *runeClozer) Cloze(rd io.ReadCloser, opts ...clozeOpt) (string, error) {
bs, err := io.ReadAll(rd)
if err != nil {
return "", err
}
defer rd.Close()
txt := []rune(string(bs))
var bf1, bf2 bytes.Buffer
idx := 0
for i := 0; i < len(txt); i++ {
// 非 rune 的字符,例如英语单词。
var notRuneWord []rune
for i < len(txt) {
if multiByteRune(txt[i]) {
break
}
notRuneWord = append(notRuneWord, txt[i])
i++
}
if len(notRuneWord) > 0 {
bf1.WriteString(string(notRuneWord))
bf2.WriteString(string(notRuneWord))
// 回退到前一个字符。
i--
continue
}
c := txt[i]
s1, s2 := string(c), string(c)
if !ignRunes[c] {
if idx%2 == 0 {
s1 = replaceChar(s1, true)
} else {
s2 = replaceChar(s1, true)
}
idx++
}
_, err = bf1.WriteString(s1)
if err != nil {
return "", fmt.Errorf("failed to write buffer, error: %+v", err)
}
_, err = bf2.WriteString(s2)
if err != nil {
return "", fmt.Errorf("failed to write buffer, error: %+v", err)
}
}
return bf1.String() + "\n" + bf2.String(), nil
}
func replaceChar(c string, cloze bool) string {
if !cloze {
return symbol
}
return "{{c1::" + c + "}}"
}