-
Notifications
You must be signed in to change notification settings - Fork 1
/
filesource.go
105 lines (94 loc) · 2.01 KB
/
filesource.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
99
100
101
102
103
104
105
package disttopk
import (
"encoding/gob"
"fmt"
"io"
"os"
"path/filepath"
)
type FileSourceAdaptor interface {
FillMapFromFile(filename string, m map[uint32]map[int]float64)
CacheFileNameSuffix() string
}
type FileSource struct {
FileSourceAdaptor
}
func (this *FileSource) ReadFiles(fileglob string) []ItemList {
files, err := filepath.Glob(fileglob)
if err != nil {
panic(err)
}
mn := make(map[uint32]map[int]float64)
if len(files) == 0 {
panic(fmt.Sprintln("Cannot find files in", fileglob))
}
for _, f := range files {
this.FillMapFromFile(f, mn)
}
il := make([]ItemList, 0, len(mn))
for _, v := range mn {
//m := v.AddToMap(nil)
l := MakeItemList(v)
l.Sort()
//fmt.Println(l)
il = append(il, l)
}
return il
}
func (this *FileSource) ReadFilesAndCache(fileglob string, cachebase string) []ItemList {
cachefilename := cachebase + this.CacheFileNameSuffix()
fmt.Println("Cache file name", cachefilename)
if _, err := os.Stat(cachefilename); os.IsNotExist(err) {
fmt.Println("Generating cache", cachefilename)
l := this.ReadFiles(fileglob)
f, err := os.Create(cachefilename)
if err != nil {
panic(err)
}
enc := gob.NewEncoder(f)
for _, itemlist := range l {
if err := enc.Encode(len(itemlist)); err != nil {
panic(err)
}
for _, item := range itemlist {
if err := enc.Encode(item.Id); err != nil {
panic(err)
}
if err := enc.Encode(item.Score); err != nil {
panic(err)
}
}
}
f.Close()
fmt.Println("Finished Generating cache", cachefilename)
}
f, err := os.Open(cachefilename)
if err != nil {
panic(err)
}
dec := gob.NewDecoder(f)
var l []ItemList
for {
length := 0
err = dec.Decode(&length)
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
il := NewItemList()
for i := 0; i < length; i++ {
item := Item{}
if err := dec.Decode(&item.Id); err != nil {
panic(err)
}
if err := dec.Decode(&item.Score); err != nil {
panic(err)
}
il = append(il, item)
}
l = append(l, il)
}
return l
}