-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessors.go
More file actions
113 lines (91 loc) · 1.79 KB
/
processors.go
File metadata and controls
113 lines (91 loc) · 1.79 KB
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
package main
import (
"bufio"
"errors"
"io"
"os"
"strings"
)
type Processor interface {
process(file *os.File) error
getValue() int
}
type ValueGetter struct {
value int
}
func (v ValueGetter) getValue() int {
return v.value
}
type ByteCountProcessor struct {
ValueGetter
}
type LineCountProcessor struct {
ValueGetter
}
type WordCountProcessor struct {
ValueGetter
}
type CharacterCountProcessor struct {
ValueGetter
}
func (processor *CharacterCountProcessor) process(file *os.File) error {
err := resetFile(file)
if err != nil {
return err
}
reader := bufio.NewReader(file)
for {
_, _, err := reader.ReadRune()
if err == io.EOF {
break
} else if err != nil {
return err
}
processor.value++
}
return nil
}
func (processor *WordCountProcessor) process(file *os.File) error {
err := resetFile(file)
if err != nil {
return err
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
words := strings.Fields(scanner.Text())
processor.value += len(words)
}
if err := scanner.Err(); err != nil {
return errors.New("unable to parse file")
}
return nil
}
func (processor *LineCountProcessor) process(file *os.File) error {
err := resetFile(file)
if err != nil {
return err
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
processor.value++
}
if err := scanner.Err(); err != nil {
return errors.New("unable to parse file")
}
return nil
}
func (processor *ByteCountProcessor) process(file *os.File) error {
fileInfo, err := file.Stat()
if err != nil {
return errors.New("unable to parse file")
}
fileSize := fileInfo.Size()
processor.value = int(fileSize)
return nil
}
func resetFile(file *os.File) error {
if _, err := file.Seek(0, io.SeekStart); err != nil {
return errors.New("error rewinding temporary file")
}
return nil
}