-
Notifications
You must be signed in to change notification settings - Fork 0
/
filtercomments.go
73 lines (65 loc) · 1.28 KB
/
filtercomments.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
package filtercomments
import (
"bufio"
"bytes"
"io"
)
type Reader struct {
rd *bufio.Reader
commchar byte
buf []byte
err error
}
func NewReader(r io.Reader, c byte) *Reader {
w := new(Reader)
w.rd = bufio.NewReader(r)
w.commchar = c
w.buf = []byte{}
w.err = nil
return w
}
func (b *Reader) Read(p []byte) (n int, err error) {
// If there has been an error...
if b.err != nil {
return 0, b.err
}
// Send saved text from previously.
if len(b.buf) > 0 {
if len(p) >= len(b.buf) {
//The entire buf can be send
n := copy(p, b.buf)
b.buf = []byte{}
return n, nil
}
// only part of buf can be send
n := copy(p, b.buf)
b.buf = b.buf[n:]
return n, nil
}
// Get new data
for {
// TODO: Prefix is ignored. Assuming it will return a whole new line.
b.buf, _, err = (*b.rd).ReadLine()
if err != nil {
b.err = err
return 0, b.err
}
// Check for comment or empty line
if len(b.buf) < 2 {
continue
}
if b.buf[0] == b.commchar {
continue
}
break
}
//Search for a comment in the line.
pos := bytes.IndexByte(b.buf, b.commchar)
if pos > -1 {
b.buf = b.buf[:pos]
}
b.buf = append(b.buf, '\n')
// Now that buf is full, return 0 so this method is called again.
// TODO: this is not very elegant...
return 0, nil
}