source: code/trunk/ring.go@ 241

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

Remove Ring.Close

This is unused.

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