source: code/trunk/ring.go@ 239

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

Remove RingConsumer.Close

This is now unused.

File size: 2.5 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 closed bool
18}
19
20// NewRing creates a new ring buffer.
21func NewRing(capacity int) *Ring {
22 return &Ring{
23 buffer: make([]*irc.Message, capacity),
24 cap: uint64(capacity),
25 }
26}
27
28// Produce appends a new message to the ring buffer.
29func (r *Ring) Produce(msg *irc.Message) {
30 if r.closed {
31 panic("soju: Ring.Produce called after Close")
32 }
33
34 i := int(r.cur % r.cap)
35 r.buffer[i] = msg
36 r.cur++
37}
38
39func (r *Ring) Cur() uint64 {
40 return r.cur
41}
42
43func (r *Ring) Close() {
44 if r.closed {
45 panic("soju: Ring.Close called twice")
46 }
47
48 r.closed = true
49}
50
51// NewConsumer creates a new ring buffer consumer.
52//
53// If seq is nil, the consumer will get messages starting from the last
54// producer message. If seq is non-nil, the consumer will get messages starting
55// from the specified history sequence number (see RingConsumer.Close).
56//
57// The consumer can only be used from a single goroutine.
58func (r *Ring) NewConsumer(seq *uint64) *RingConsumer {
59 consumer := &RingConsumer{ring: r}
60
61 if seq != nil {
62 consumer.cur = *seq
63 } else {
64 consumer.cur = r.cur
65 }
66 r.consumers = append(r.consumers, consumer)
67
68 return consumer
69}
70
71// RingConsumer is a ring buffer consumer.
72type RingConsumer struct {
73 ring *Ring
74 cur uint64
75}
76
77// diff returns the number of pending messages. It assumes the Ring is locked.
78func (rc *RingConsumer) diff() uint64 {
79 if rc.cur > rc.ring.cur {
80 panic(fmt.Sprintf("soju: consumer cursor (%v) greater than producer cursor (%v)", rc.cur, rc.ring.cur))
81 }
82 return rc.ring.cur - rc.cur
83}
84
85// Peek returns the next pending message if any without consuming it. A nil
86// message is returned if no message is available.
87func (rc *RingConsumer) Peek() *irc.Message {
88 diff := rc.diff()
89 if diff == 0 {
90 return nil
91 }
92 if diff > rc.ring.cap {
93 // Consumer drops diff - cap entries
94 rc.cur = rc.ring.cur - rc.ring.cap
95 }
96 i := int(rc.cur % rc.ring.cap)
97 msg := rc.ring.buffer[i]
98 if msg == nil {
99 panic(fmt.Sprintf("soju: unexpected nil ring buffer entry at index %v", i))
100 }
101 return msg
102}
103
104// Consume consumes and returns the next pending message. A nil message is
105// returned if no message is available.
106func (rc *RingConsumer) Consume() *irc.Message {
107 msg := rc.Peek()
108 if msg != nil {
109 rc.cur++
110 }
111 return msg
112}
Note: See TracBrowser for help on using the repository browser.