kunt

golang IRC bot
git clone git://git.2f30.org/kunt
Log | Files | Refs | LICENSE

commit 056ab622a802686f1183418f014d2c4ba8baeb37
parent 5cefadb10dabb87e00bef067faeabb201fab492f
Author: sin <sin@2f30.org>
Date:   Mon, 29 Apr 2013 16:36:28 +0100

add mapfs iterator, don't enforce mapfs to deal with dups

Diffstat:
Msrc/kunt/kunt.go | 27+++++++++++++++++++++++++--
Msrc/mapfs/TODO | 1-
Msrc/mapfs/mapfs.go | 31++++++++++++++++++++++++++-----
3 files changed, 51 insertions(+), 8 deletions(-)

diff --git a/src/kunt/kunt.go b/src/kunt/kunt.go @@ -120,7 +120,7 @@ func cmdAddQuote(msg irc.IrcMessage) { s = strings.TrimSpace(s) s += "\n" buf := []byte(s) - if quoteDb.Dup(buf) { + if quoteDb.CountMatches(buf) > 0 { kunt.ircCtx.SendPrivmsg(msg.Params[0], fmt.Errorf("Duplicate entry: %s", buf).Error()) return @@ -170,7 +170,7 @@ func cmdAddUrl(msg irc.IrcMessage) { s = strings.TrimSpace(s) s += "\n" buf := []byte(s) - if urlDb.Dup(buf) { + if urlDb.CountMatches(buf) > 0 { kunt.ircCtx.SendPrivmsg(msg.Params[0], fmt.Errorf("Duplicate entry: %s", buf).Error()) return @@ -293,6 +293,29 @@ func main() { log.Fatal(err) } + // Check for duplicate entries + iter := mapfs.MakeMapIter(quoteDb) + for { + k, v, ok := iter() + if !ok { + break + } + if quoteDb.CountMatches(v) > 1 { + log.Fatal(fmt.Errorf("Duplicate entry in quote DB with key: %d - val: %s", k, v)) + } + } + + iter = mapfs.MakeMapIter(urlDb) + for { + k, v, ok := iter() + if !ok { + break + } + if urlDb.CountMatches(v) > 1 { + log.Fatal(fmt.Errorf("Duplicate entry in url DB with key: %d - val: %s", k, v)) + } + } + rand.Seed(time.Now().UnixNano()) dispatch := map[string]func(irc.IrcMessage){ diff --git a/src/mapfs/TODO b/src/mapfs/TODO @@ -1 +0,0 @@ -Add iterator interface (with a callback function or similar) diff --git a/src/mapfs/mapfs.go b/src/mapfs/mapfs.go @@ -2,6 +2,7 @@ package mapfs import ( + "bytes" "fmt" "math/rand" "os" @@ -25,6 +26,25 @@ type mapfsVal struct { data []byte // Actual raw data } +type MapIter func() (key int, data []byte, ok bool) + +func MakeMapIter(m *Mapfs) MapIter { + i := 0 + return func() (key int, data []byte, ok bool) { + m.lock.Lock() + defer m.lock.Unlock() + for i < len(m.dict) { + v, ok := m.dict[i] + if ok { + i++ + return i - 1, v.data, true + } + i++ + } + return -1, nil, false + } +} + func NewMapfs(name string, path string, prefix string) *Mapfs { return &Mapfs{ name: name, @@ -126,16 +146,17 @@ func (m *Mapfs) Load() error { return err } -// Check if `buf' already exists in the map -func (m *Mapfs) Dup(buf []byte) bool { +// Count how many instances of `buf' exist in the map +func (m *Mapfs) CountMatches(buf []byte) int { m.lock.Lock() defer m.lock.Unlock() + i := 0 for _, v := range m.dict { - if string(v.data) == string(buf) { - return true + if bytes.Equal(v.data, buf) { + i++ } } - return false + return i } func (m *Mapfs) Put(key int, buf []byte) error {