Ai
1 Star 0 Fork 2

王布衣/pkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
wireup.go 2.75 KB
一键复制 编辑 原始数据 按行查看 历史
package fastqueue
import "errors"
var (
errMissingWaitStrategy = errors.New("a wait strategy must be provided")
errCapacityTooSmall = errors.New("the capacity must be at least 1")
errCapacityPowerOfTwo = errors.New("the capacity be a power of two, e.g. 2, 4, 8, 16")
errMissingConsumers = errors.New("no consumers have been provided")
errMissingConsumersInGroup = errors.New("the consumer group does not have any consumers")
errEmptyConsumer = errors.New("an empty consumer was specified in the consumer group")
)
type Wireup struct {
waiter WaitStrategy
capacity int64
consumerGroups [][]Consumer
}
type Option func(*Wireup)
func NewDisruptor(options ...Option) Disruptor {
if this, err := NewWireup(options...); err != nil {
panic(err)
} else {
return createDisruptor(this.Build())
}
}
func NewWireup(options ...Option) (*Wireup, error) {
this := &Wireup{}
WithWaitStrategy(NewWaitStrategy())(this)
for _, option := range options {
option(this)
}
if err := this.validate(); err != nil {
return nil, err
}
return this, nil
}
func (this *Wireup) validate() error {
if this.waiter == nil {
return errMissingWaitStrategy
}
if this.capacity <= 0 {
return errCapacityTooSmall
}
if this.capacity&(this.capacity-1) != 0 {
return errCapacityPowerOfTwo
}
if len(this.consumerGroups) == 0 {
return errMissingConsumers
}
for _, consumerGroup := range this.consumerGroups {
if len(consumerGroup) == 0 {
return errMissingConsumersInGroup
}
for _, consumer := range consumerGroup {
if consumer == nil {
return errEmptyConsumer
}
}
}
return nil
}
func (this *Wireup) Build() (Writer, Reader) {
var writerSequence = NewCursor()
readers, readBarrier := this.buildReaders(writerSequence)
return NewWriter(writerSequence, readBarrier, this.capacity), compositeReader(readers)
}
func (this *Wireup) buildReaders(writerSequence *Cursor) (readers []Reader, upstream Barrier) {
upstream = writerSequence
for _, consumerGroup := range this.consumerGroups {
var consumerGroupSequences []*Cursor
for _, consumer := range consumerGroup {
currentSequence := NewCursor()
readers = append(readers, NewReader(currentSequence, writerSequence, upstream, this.waiter, consumer))
consumerGroupSequences = append(consumerGroupSequences, currentSequence)
}
upstream = NewCompositeBarrier(consumerGroupSequences...)
}
return readers, upstream
}
func WithWaitStrategy(value WaitStrategy) Option {
return func(this *Wireup) {
this.waiter = value
}
}
func WithCapacity(value int64) Option {
return func(this *Wireup) {
this.capacity = value
}
}
func WithConsumerGroup(value ...Consumer) Option {
return func(this *Wireup) {
this.consumerGroups = append(this.consumerGroups, value)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/quant1x/pkg.git
git@gitee.com:quant1x/pkg.git
quant1x
pkg
pkg
v0.5.2

搜索帮助