source: code/trunk/ring.go@ 242

Last change on this file since 242 was 242, checked in by contact, 5 years ago

Make Ring.NewConsumer seq argument mandatory

There's no point in supporting a nil argument anymore.

File size: 2.1 KB
Line 
1package soju
2
3import (
4 "fmt"
5
6 "gopkg.in/irc.v3"
7)
8
9// Ring implements a single producer, multiple consumer ring buffer. The ring
10// buffer size is fixed. The ring buffer is stored in memory.
11type Ring struct {
12 buffer []*irc.Message
13 cap uint64
14
15 cur uint64
16 consumers []*RingConsumer
17}
18
19// NewRing creates a new ring buffer.
20func NewRing(capacity int) *Ring {
21 return &Ring{
22 buffer: make([]*irc.Message, capacity),
23 cap: uint64(capacity),
24 }
25}
26
27// Produce appends a new message to the ring buffer.
28func (r *Ring) Produce(msg *irc.Message) {
29 i := int(r.cur % r.cap)
30 r.buffer[i] = msg
31 r.cur++
32}
33
34// Cur returns the current history sequence number.
35func (r *Ring) Cur() uint64 {
36 return r.cur
37}
38
39// NewConsumer creates a new ring buffer consumer.
40//
41// The consumer will get messages starting from the specified history sequence
42// number (see Ring.Cur).
43func (r *Ring) NewConsumer(seq uint64) *RingConsumer {
44 consumer := &RingConsumer{ring: r, cur: seq}
45 r.consumers = append(r.consumers, consumer)
46 return consumer
47}
48
49// RingConsumer is a ring buffer consumer.
50type RingConsumer struct {
51 ring *Ring
52 cur uint64
53}
54
55// diff returns the number of pending messages. It assumes the Ring is locked.
56func (rc *RingConsumer) diff() uint64 {
57 if rc.cur > rc.ring.cur {
58 panic(fmt.Sprintf("soju: consumer cursor (%v) greater than producer cursor (%v)", rc.cur, rc.ring.cur))
59 }
60 return rc.ring.cur - rc.cur
61}
62
63// Peek returns the next pending message if any without consuming it. A nil
64// message is returned if no message is available.
65func (rc *RingConsumer) Peek() *irc.Message {
66 diff := rc.diff()
67 if diff == 0 {
68 return nil
69 }
70 if diff > rc.ring.cap {
71 // Consumer drops diff - cap entries
72 rc.cur = rc.ring.cur - rc.ring.cap
73 }
74 i := int(rc.cur % rc.ring.cap)
75 msg := rc.ring.buffer[i]
76 if msg == nil {
77 panic(fmt.Sprintf("soju: unexpected nil ring buffer entry at index %v", i))
78 }
79 return msg
80}
81
82// Consume consumes and returns the next pending message. A nil message is
83// returned if no message is available.
84func (rc *RingConsumer) Consume() *irc.Message {
85 msg := rc.Peek()
86 if msg != nil {
87 rc.cur++
88 }
89 return msg
90}
Note: See TracBrowser for help on using the repository browser.