100 lines
1.9 KiB
Go
100 lines
1.9 KiB
Go
|
package models
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"io/ioutil"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
|
||
|
"github.com/spf13/viper"
|
||
|
)
|
||
|
|
||
|
type EntryFrequency struct {
|
||
|
Times int
|
||
|
Entry string
|
||
|
}
|
||
|
|
||
|
func (ef *EntryFrequency) ToBytes() []byte {
|
||
|
var ret []byte
|
||
|
ret = append(ret, []byte(strconv.Itoa(ef.Times))...)
|
||
|
ret = append(ret, byte('\t'))
|
||
|
ret = append(ret, []byte(ef.Entry)...)
|
||
|
return ret
|
||
|
}
|
||
|
|
||
|
func FromBytes(bts []byte) (*EntryFrequency, error) {
|
||
|
fields := bytes.Split(bts, []byte{'\t'})
|
||
|
times, err := strconv.Atoi(string(fields[0]))
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return &EntryFrequency{
|
||
|
Times: times,
|
||
|
Entry: string(fields[1]),
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
type Frequencies struct {
|
||
|
Entries []*EntryFrequency
|
||
|
}
|
||
|
|
||
|
func LoadFrequencies() (*Frequencies, error) {
|
||
|
fl := viper.ConfigFileUsed()
|
||
|
fl = fl[:strings.LastIndex(fl, "/")+1] + "freq"
|
||
|
req := &Frequencies{}
|
||
|
b, err := ioutil.ReadFile(fl)
|
||
|
if err != nil {
|
||
|
err = req.Save()
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return req, nil
|
||
|
}
|
||
|
lines := bytes.Split(b, []byte{'\n'})
|
||
|
for i := range lines {
|
||
|
var ef *EntryFrequency
|
||
|
ef, err = FromBytes(lines[i])
|
||
|
if err == nil {
|
||
|
req.AddEntry(ef)
|
||
|
}
|
||
|
}
|
||
|
return req, nil
|
||
|
}
|
||
|
|
||
|
func (f *Frequencies) AddEntry(ef *EntryFrequency) {
|
||
|
f.Entries = append(f.Entries, ef)
|
||
|
}
|
||
|
|
||
|
func (f *Frequencies) GetTimes(entry string) int {
|
||
|
for i := range f.Entries {
|
||
|
if f.Entries[i].Entry == entry {
|
||
|
return f.Entries[i].Times
|
||
|
}
|
||
|
}
|
||
|
return 0
|
||
|
}
|
||
|
|
||
|
func (f *Frequencies) IncrementEntry(entry string) {
|
||
|
for i := range f.Entries {
|
||
|
if f.Entries[i].Entry == entry {
|
||
|
f.Entries[i].Times++
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
f.Entries = append(f.Entries, &EntryFrequency{
|
||
|
Times: 1,
|
||
|
Entry: entry,
|
||
|
})
|
||
|
}
|
||
|
|
||
|
func (f *Frequencies) Save() error {
|
||
|
fl := viper.ConfigFileUsed()
|
||
|
fl = fl[:strings.LastIndex(fl, "/")+1] + "freq"
|
||
|
var b []byte
|
||
|
for _, e := range f.Entries {
|
||
|
b = append(b, e.ToBytes()...)
|
||
|
b = append(b, byte('\n'))
|
||
|
}
|
||
|
return ioutil.WriteFile(fl, b, 0600)
|
||
|
}
|