-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
91 lines (82 loc) · 1.59 KB
/
reader.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package skkdict
import (
"bufio"
"fmt"
"io"
"strings"
)
// Word represents a word.
type Word struct {
Text string
Desc string
}
// Entry represents an entry in SKK dictionary.
type Entry struct {
Label string
Words []Word
}
type lineReader interface {
ReadLine() (line []byte, isPrefix bool, err error)
}
// Reader reads SKK dictionary file and parses as Entry.
type Reader struct {
lr lineReader
lnum int64
ll string
}
// NewReader creates a SKK dictionary Reader.
func NewReader(r io.Reader) *Reader {
lr, ok := r.(lineReader)
if !ok {
lr = bufio.NewReader(r)
}
return &Reader{
lr: lr,
}
}
// Read reads an entry.
func (r *Reader) Read() (*Entry, error) {
r.ll = ""
b, isPrefix, err := r.lr.ReadLine()
if err != nil {
return nil, err
}
r.lnum++
if isPrefix {
return nil, fmt.Errorf("too long line at %d", r.lnum)
}
r.ll = string(b)
return parseEntry(r.ll)
}
// parseEntry parses a string as Entry.
func parseEntry(s string) (*Entry, error) {
if strings.HasPrefix(s, ";;") {
return nil, nil
}
s = strings.TrimRight(s, " \t\r\n")
items := strings.SplitN(s, " ", 2)
if items == nil || len(items) != 2 {
return nil, fmt.Errorf("invalid format: %s", s)
}
label := items[0]
values := strings.Split(strings.Trim(items[1], "/"), "/")
words := make([]Word, len(values))
for i, v := range values {
words[i] = parseWord(v)
}
return &Entry{
Label: label,
Words: words,
}, nil
}
// parseWord parses a string as Word
func parseWord(v string) Word {
n := strings.Index(v, ";")
if n < 0 {
return Word{Text: v}
}
return Word{
Text: v[0:n],
Desc: v[n+1:],
}
}