summaryrefslogtreecommitdiff
path: root/last.go
blob: 34a30229b8d8b99d403100cdc8e43c5f589f22b3 (plain)
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
package main

import (
	"container/ring"
	"fmt"
	"time"
)

type Msg struct {
	Time time.Time
	Nick string
	Text string
}

type LastBuf struct {
	*ring.Ring
}

func NewLastBuf(n int) *LastBuf {
	return &LastBuf{ring.New(n)}
}

func (v *LastBuf) Push(t time.Time, nick, text string) {
	v.Value = Msg{Time: t, Nick: nick, Text: text}
	v.Ring = v.Next()
}

// walk through buffer and find last message
func (v *LastBuf) Last(nick string) string {
	var msg string
	v.Do(func(v interface{}) {
		if l, ok := v.(Msg); ok {
			if l.Nick == nick {
				msg = l.Text
			}
		}
	})
	return msg
}

func (v *LastBuf) Dump(c chan string) {
	v.Do(func(v interface{}) {
		if l, ok := v.(Msg); ok {
			c <- fmt.Sprintf("%v <%v> %v",
				l.Time.UTC().Format(time.Kitchen),
				l.Nick, l.Text)
		}
	})
}