forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounter.go
98 lines (87 loc) · 1.6 KB
/
counter.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
// ex7.1 provides line and word counters.
package counter
import (
"fmt"
"unicode"
"unicode/utf8"
)
type LineCounter struct {
lines int
}
func (c *LineCounter) Write(p []byte) (n int, err error) {
for _, b := range p {
if b == '\n' {
c.lines++
}
}
return len(p), nil
}
func (c *LineCounter) N() int {
return c.lines
}
func (c *LineCounter) String() string {
return fmt.Sprintf("%d", c.lines)
}
type WordCounter struct {
words int
inWord bool
}
func leadingSpaces(p []byte) int {
count := 0
cur := 0
for cur < len(p) {
r, size := utf8.DecodeRune(p[cur:])
if !unicode.IsSpace(r) {
return count
}
cur += size
count++
}
return count
}
func leadingNonSpaces(p []byte) int {
count := 0
cur := 0
for cur < len(p) {
r, size := utf8.DecodeRune(p[cur:])
if unicode.IsSpace(r) {
return count
}
cur += size
count++
}
return count
}
// A !IsSpace() -> IsSpace() transition is counted as a word.
//
// I couldn't figure out how to use bufio.ScanWords without either
// double-counting words split across buffer boundaries, giving incorrect
// intermediate counts, or doing some really awkward buffer manipulation.
func (c *WordCounter) Write(p []byte) (n int, err error) {
cur := 0
n = len(p)
for {
spaces := leadingSpaces(p[cur:])
cur += spaces
if spaces > 0 {
c.inWord = false
}
if cur == len(p) {
return
}
if !c.inWord {
c.words++
}
c.inWord = true
cur += leadingNonSpaces(p[cur:])
if cur == len(p) {
return
}
}
}
func (c *WordCounter) N() int {
return c.words
}
func (c *WordCounter) String() string {
return fmt.Sprintf("%d", c.words)
}