-
Notifications
You must be signed in to change notification settings - Fork 3
/
collection.go
145 lines (119 loc) · 2.33 KB
/
collection.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package feature
import (
"bufio"
"io"
"os"
"path/filepath"
"strings"
)
type CollectionIter struct{ dir }
func (it *CollectionIter) Close() error { return it.close() }
func (it *CollectionIter) Next() bool { return it.next() }
func (it *CollectionIter) Name() string { return it.name() }
func (it *CollectionIter) IDs() *IDIter {
return &IDIter{readfile(filepath.Join(it.path, it.name()))}
}
type IDIter struct{ file }
func (it *IDIter) Close() error { return it.close() }
func (it *IDIter) Next() bool { return it.next() }
func (it *IDIter) Name() string { return it.line }
type Collection struct {
file *os.File
buf *bufio.Writer
err error
}
func (col *Collection) Path() string {
if col.file != nil {
return col.file.Name()
}
return ""
}
func (col *Collection) Close() error {
if col.buf != nil {
col.err = col.buf.Flush()
col.buf = nil
}
if col.file != nil {
col.file.Close()
col.file = nil
}
return col.err
}
func (col *Collection) Sync() error {
if col.buf != nil {
return col.buf.Flush()
}
return nil
}
func (col *Collection) IDs() *IDIter {
return &IDIter{col.ids()}
}
func (col *Collection) ids() file {
if col.file != nil {
return readfile(col.file.Name())
}
return file{}
}
func (col *Collection) Add(id string) error {
if col.err == nil {
col.err = col.writeLine(id)
}
return col.err
}
func (col *Collection) writeLine(s string) error {
if col.file == nil {
return nil
}
if col.buf == nil {
col.buf = bufio.NewWriter(col.file)
}
if _, err := col.buf.WriteString(s); err != nil {
return err
}
return col.buf.WriteByte('\n')
}
type file struct {
file *os.File
buf *bufio.Reader
line string
err error
}
func (f *file) close() error {
if f.file != nil {
f.file.Close()
}
f.file, f.buf, f.line = nil, nil, ""
return f.err
}
func (f *file) next() bool {
if f.file == nil {
return false
}
if f.buf == nil {
f.buf = bufio.NewReader(f.file)
}
for {
line, err := f.buf.ReadString('\n')
if err != nil && (err != io.EOF || line == "") {
if err == io.EOF {
err = nil
}
f.err = err
f.close()
return false
}
if line = strings.TrimSuffix(line, "\n"); line != "" {
f.line = line
return true
}
}
}
func readfile(path string) file {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
}
return file{file: f, err: err}
}