-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencodeWorker.go
72 lines (66 loc) · 1.39 KB
/
encodeWorker.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
package main
import (
"bufio"
"encoding/gob"
"fmt"
"log"
"os"
"strconv"
)
type EncodeWorker struct {
files []*os.File
writers []*bufio.Writer
encoders []*gob.Encoder
nSlice int
}
func NewEncodeWorker(nSlice int) *EncodeWorker {
// Initialize all required resources
files := make([]*os.File, nSlice)
writers := make([]*bufio.Writer, nSlice)
encoders := make([]*gob.Encoder, nSlice)
for i := 0; i < nSlice; i++ {
f, err := os.Create("tmp-" + strconv.Itoa(i))
if err != nil {
log.Fatal(err)
}
files[i] = f
writers[i] = bufio.NewWriter(f)
encoders[i] = gob.NewEncoder(writers[i])
}
return &EncodeWorker{
files,
writers,
encoders,
nSlice,
}
}
// SaveWordsMap map and save current wordsMap to different file slices
// through hash function and remainder operation
func (ew *EncodeWorker) SaveWordsMap(wordsMap *WordsMap) error {
for word, ci := range *wordsMap {
idx := ihash(word) % ew.nSlice
wordDict := WordDict{word, ci}
err := ew.encoders[idx].Encode(wordDict)
if err != nil {
return fmt.Errorf("Failed to encode WordDict. %T:%v\n", err, err)
}
}
return nil
}
func (ew *EncodeWorker) FlushAll() error {
for _, w := range ew.writers {
if err := w.Flush(); err != nil {
return err
}
}
return nil
}
func (ew *EncodeWorker) CloseAllFile() error {
for _, f := range ew.files {
err := f.Close()
if err != nil {
return err
}
}
return nil
}