-
Notifications
You must be signed in to change notification settings - Fork 0
/
ioutil.go
86 lines (69 loc) · 1.59 KB
/
ioutil.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
package main
import (
"bufio"
"io"
"log"
"os"
"strings"
)
type ReadInputHandler func(lineReady <-chan bool, wordChannel <-chan string, readNextLine chan<- bool, doneChannel chan<- bool)
func ReadInput(fileName string, bufferSize int, maxWorldsOnLine int, handler ReadInputHandler) {
file, err := os.Open(fileName)
if err != nil {
log.Fatalln(err)
}
defer file.Close()
wordChannel := make(chan string, maxWorldsOnLine)
lineReady := make(chan bool, 1)
readNextLine := make(chan bool, 1)
doneChannel := make(chan bool, 1)
go handler(lineReady, wordChannel, readNextLine, doneChannel)
reader := bufio.NewReader(file)
buffer := make([]byte, bufferSize)
var currentWordBuilder strings.Builder
var seenSpace bool
for {
bytesRead, err := reader.Read(buffer)
if err != nil {
if err == io.EOF {
break
}
log.Fatalln(err)
}
chunk := buffer[:bytesRead]
for _, b := range chunk {
switch b {
case '\r':
continue
case ' ':
seenSpace = true
case '\n':
seenSpace = false
wordChannel <- currentWordBuilder.String()
currentWordBuilder.Reset()
lineReady <- true
<-readNextLine
default:
if seenSpace {
seenSpace = false
newString := currentWordBuilder.String()
if newString != "" {
wordChannel <- newString
currentWordBuilder.Reset()
}
}
currentWordBuilder.WriteByte(b)
}
}
}
if currentWordBuilder.Len() > 0 {
wordChannel <- currentWordBuilder.String()
lineReady <- true
<-readNextLine
}
close(wordChannel)
close(readNextLine)
close(lineReady)
<-doneChannel
close(doneChannel)
}